// FILE: comprador.js
// GOAL: To define functions to support the comprador report

// Begin

// FUNCTION: formatCurrency
// PURPOSE:  To print currency appropriately
function formatCurrency(amt, dec)
{
	var value = "" + Math.round(eval(amt)*Math.pow(10,dec))

	while (value.length <= dec)
	{
		value = "0" + value;
	}
	
	var decpt = value.length - dec;
	value = value.substring(0, decpt) + "." + value.substring(decpt, value.length);
	var leftmost = value.length;
	if (leftmost > 6)
	{
		for (i=6; i<value.length-1; i+=3)
		{
			value = value.substring(0, leftmost-i) + "," + value.substring(leftmost-i, value.length);	
		}
	
	}
	
	// Fix leading comma issue
	if (value.substring(0,1) == ",")
	{
		value = value.substring(1,value.length);
	}
		
	return value;
}
	

// FUNCTION: printCurrency
// PURPOSE:  To print currency appropriately
function printCurrency(amt)
{
	var value = formatCurrency(amt, 2)
	
	switch (g_currency)
	{
		case 1:
			document.write(g_currency_lead + value);
			break;
			
		default:
			document.write(value + ' ' + g_currency);
			break;
	}
	
}


// FUNCTION: stringCurrency
// PURPOSE:  To format a currency amount
function stringCurrency(amt)
{
	var value = formatCurrency(amt, 2)
	var result = "1.00";
	
	switch (g_currency)
	{
		case 1:
			result = g_currency_lead + value;
			break;
			
		default:
			result = value + ' ' + g_currency;
			break;
	}
	
	// Return result
	return result;
}


// FUNCTION: showHong
// PURPOSE:  To show the current name of the Hong
function showHong()
{
	document.write('<strong>' + c_hong + '</strong>');   
}

// FUNCTION: showAddress
// PURPOSE:  To show the current address of the Hong
function showAddress()
{
	document.write('<strong>' + '12 Harbor Place<br />');
	document.write('Hong Kong' + '</strong>');   
}

// FUNCTION: showOrder
// PURPOSE:  To show the current name of the Hong
function showOrder()
{
	var now = new Date();
	var now_hr = now.getHours();
	var now_min = now.getMinutes();
	var now_sec = now.getSeconds();
	document.write('<strong>' + now_hr + now_min + now_sec + '</strong>');   
}

// FUNCTION: showDate
// PURPOSE:  To show the current name of the Hong
function showDate()
{
	var now = new Date();
	var now_mth = now.getMonth() + 1;
	var now_day = now.getDate();
	var now_yr  = now.getYear();
	document.write('<strong>' + now_mth + '/' + now_day + '/' + now_yr + '</strong>');   
}


// FUNCTION: showDestination
// PURPOSE:  To show the current destination
function showDestination()
{
	// Handle destinations with an underscore
	var where = g_destination[c_locus];
	where = where.replace("_", " ");
	document.write('<strong>' + where + '</strong>'); 
}


// FUNCTION: showOcean
// PURPOSE:  To show the ocean we are traveling
function showOcean()
{
	// Display the location in the ocean
	var where = g_destination[0];
	where = where.replace("_", " ");
	document.write('<strong>' + where + '</strong>'); 
}


// FUNCTION: showShips
// PURPOSE:  To show the current number of ships
function showShips()
{
	document.write(c_ship);   
}


// FUNCTION: showShipCount
// PURPOSE:  To show the current number of ships
function showShipCount()
{
	if (c_ship == 1)
	{
		document.write(c_ship + ' ship');
	}
	else
	{
		document.write(c_ship + ' ships');   
	}
}


// FUNCTION: showGuns
// PURPOSE:  To show the current number of guns
function showGuns()
{
	document.write(c_gun);   
}


// FUNCTION: showCannonNeed
// PURPOSE:  To show the expected number of guns
function showCannonNeed()
{
	var needed = Math.floor(c_tonnage / 10);
	var expected = needed - c_gun;
	
	// DEBUG: alert('You need ' + needed +' cannon to protect cargo ' + c_tonnage + ' and you have ' + c_gun);
	
	if (needed > c_gun)
	{
		document.write('You still need ' + expected + ' cannon.');
	}
	else
	{
		document.write('You have enough cannon.');
	}
}


// FUNCTION: showCargo
// PURPOSE:  To show the current cargo manifest
function showCargo()
{
	// Calculate total cargo
	c_cargo = c_jade_quant + c_silk_quant + c_arm_quant + c_rice_quant + c_gen_quant;
	
	// Calculate percentage and display it
	var percent = 1.00;
	document.write(c_cargo + ' of ' + c_tonnage + ' units  (');   
	percent = 100.00 * c_cargo / c_tonnage;
	if (percent < 1.00) 
		{ percent = 1.00; }
	if (percent > 100.00) 
		{ percent = 100.00; }
	
	// Round it up to 1 percent and display it
	var percentage = "" + Math.round(percent)
	document.write(percentage + '% full)');
}


// FUNCTION: showInventory
// PURPOSE:  To show the current cargo inventory
function showInventory()
{
	// Display inventory
	// DEBUG: alert('Now displaying current inventory: Jade is ' + c_jade_quant);
	
	document.write('<table width="90%" border="1" cellspacing="2" cellpadding="2">');
	document.write('<tr class="inverted_element">');
    document.write('   <td width="50%">');
	document.write('&nbsp;');
	document.write('</td>');
    document.write('   <td width="10%">');
	document.write('Units');
	document.write('</td>');
    document.write('   <td width="20%" align="right">');
	document.write('Price');
	document.write('</td>');
    document.write('   <td width="10%" align="right">');
	document.write('Value');
	document.write('</td>');
    document.write('   <td width="10%" align="center">');
	document.write('Action');
	document.write('</td>');
	document.write('</tr>');
	
	// Write JADE line
	document.write('<tr>');
	document.write('    <td>');
	document.write('Jade');
	document.write('</td>');
	document.write('<td align="right">');
	document.write(c_jade_quant);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(g_jade_price);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(c_jade_quant * g_jade_price);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_sale(1);" class="menu"><img src="images/sell_btn.gif" alt="Sell Jade goods" /></a>');
	document.write('</td>');
	document.write('</tr>');
	
	// Write SILK line
	document.write('<tr>');
	document.write('    <td>');
	document.write('Silk');
	document.write('</td>');
	document.write('<td align="right">');
	document.write(c_silk_quant);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(g_silk_price);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(c_silk_quant * g_silk_price);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_sale(2);" class="menu"><img src="images/sell_btn.gif" alt="Sell Silk goods" /></a>');
	document.write('</td>');
	document.write('</tr>');
	
	// Write ARMS line
	document.write('<tr>');
	document.write('    <td>');
	document.write('Arms');
	document.write('</td>');
	document.write('<td align="right">');
	document.write(c_arm_quant);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(g_arm_price);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(c_arm_quant * g_arm_price);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_sale(3);" class="menu"><img src="images/sell_btn.gif" alt="Sell Armament goods" /></a>');
	document.write('</td>');
	document.write('</tr>');
	
	// Write RICE line
	document.write('<tr>');
	document.write('    <td>');
	document.write('Rice');
	document.write('</td>');
	document.write('<td align="right">');
	document.write(c_rice_quant);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(g_rice_price);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(c_rice_quant * g_rice_price);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_sale(4);" class="menu"><img src="images/sell_btn.gif" alt="Sell Rice goods" /></a>');
	document.write('</td>');
	document.write('</tr>');
	
	// Write GENERAL line
	document.write('<tr>');
	document.write('    <td>');
	document.write('General');
	document.write('</td>');
	document.write('<td align="right">');
	document.write(c_gen_quant);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(g_gen_price);
	document.write('</td>');
	document.write('<td align="right">');
	printCurrency(c_gen_quant * g_gen_price);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_sale(5);" class="menu"><img src="images/sell_btn.gif" alt="Sell General goods" /></a>');
	document.write('</td>');
	document.write('</tr>');
	
	document.write('</table>');
}


// FUNCTION: updateInventory
// PURPOSE:  To update the current inventory value
function updateInventory()
{
    // Calculate the value based on global prices and current quantities
	p_inventory = c_jade_quant * g_jade_price + c_silk_quant * g_silk_price + 
				  c_arm_quant * g_arm_price + c_rice_quant * g_rice_price + c_gen_quant * g_gen_price;

	// Also update the cargo hold
	c_cargo = c_jade_quant + c_silk_quant + c_arm_quant + c_rice_quant + c_gen_quant;

	return p_inventory;
}


// FUNCTION: showHolding
// PURPOSE:  To show the current ship holdings
function showHolding()
{
	// If cash goes negative, then the game is over
	if (c_cash < 0.00)
	{
		alert('Comprador: You have gone broke. You will have to sell your ship and retire.');
		window.load = "quit.htm";
	}
	
	// Recalculate the current total holdings
	updateInventory();
	c_total = c_cash + p_inventory - c_debt;
	// DEBUG: alert('Total calculated as ' + c_total);
	
	// Write it out in a table
	document.write('<table>');

	document.write('<tr>');
	document.write('<td>');
	document.write('Cash on hand:  ');
	document.write('</td><td align="right">');
	printCurrency(c_cash);
	document.write('</td>');
	document.write('</tr>');

	document.write('<tr>');
	document.write('<td>');
	document.write('Inventory:     ');
	document.write('</td><td align="right">');
	printCurrency(p_inventory);
	document.write('</td>');
	document.write('</tr>');

	document.write('<tr>');
	document.write('<td>');
	document.write('Debt:          ');
	document.write('</td><td align="right">');
	printCurrency(c_debt);
	document.write('</td>');
	document.write('</tr>');
	document.write('<tr>');
	document.write('<td>');
	document.write('<hr>');
	document.write('Total&nbsp;Holdings:');
	document.write('</td><td align="right">');
	document.write('<hr>');
	printCurrency(c_total);
	document.write('</td></tr>');
	document.write('</table>');
}


// FUNCTION: affordability
// PURPOSE:  To determine the affordability of the current market place
function affordability()
{
	// Determine maximum quantities that you can purchase, given cash on hand
	// Recalculate maximum quantities you can purchase
	p_jade_quant = Math.floor(c_cash / g_jade_price);
	p_silk_quant = Math.floor(c_cash / g_silk_price);
	p_arm_quant = Math.floor(c_cash / g_arm_price);
	p_rice_quant = Math.floor(c_cash / g_rice_price);
	p_gen_quant = Math.floor(c_cash / g_gen_price);

	// DEBUG: alert('Calculating affordability as cash: ' + c_cash + ' jade units: ' + p_jade_quant + ' price: ' + g_jade_price);
	
	// Set limits based on current size of the hold tonnage
	var max_quant = c_tonnage - c_cargo;
	p_jade_quant = p_jade_quant > max_quant ? max_quant : p_jade_quant;
	p_silk_quant = p_silk_quant > max_quant ? max_quant : p_silk_quant;
	p_arm_quant = p_arm_quant > max_quant ? max_quant : p_arm_quant;
	p_rice_quant = p_rice_quant > max_quant ? max_quant : p_rice_quant;
	p_gen_quant = p_gen_quant > max_quant ? max_quant : p_gen_quant;

}


// FUNCTION: availability
// PURPOSE:  To determine the availability of the current items for sale
// NOTE:     Does NOT update the cookie
function availability()
{
	// Determine maximum quantities that you can sell, given current inventory
	p_jade_quant = c_jade_quant;
	p_silk_quant = c_silk_quant;
	p_arm_quant = c_arm_quant;
	p_rice_quant = c_rice_quant;
	p_gen_quant = c_gen_quant;
}


// FUNCTION: showMarket
// PURPOSE:  To show the current market place
function showMarket()
{
	// Recalculate maximum quantities you can purchase
	affordability();
	
	// Show market prices and quantities available
	document.write('<table width="90%" border="1" cellspacing="2" cellpadding="2">');
	document.write('<tr class="inverted_element">');
    document.write('   <td width="50%">');
	document.write('&nbsp;');
	document.write('</td>');
    document.write('   <td width="20%" align="right">');
	document.write('Price');
	document.write('</td>');
    document.write('   <td width="20%" align="right">');
	document.write('Can&nbsp;Afford');
	document.write('</td>');
    document.write('   <td width="10%" align="center">');
	document.write('Action');
	document.write('</td>');
	document.write('</tr>');
	
	// Write JADE line
	document.write('<tr>');
	document.write('    <td>');
	document.write('Jade');
	document.write('</td>');
	document.write('<td align="right" name="jade_price_pt">');
	printCurrency(g_jade_price);
	document.write('</td>');
	document.write('<td align="right">');
	document.write(p_jade_quant);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_item(1);" class="menu"><img src="images/buy_btn.gif" alt="Buy Jade goods" /></a>');
	document.write('</td>');
	document.write('</tr>');

	// Write SILK line
	document.write('<tr>');
	document.write('    <td>');
	document.write('Silk');
	document.write('</td>');
	document.write('<td align="right" name="silk_price_pt">');
	printCurrency(g_silk_price);
	document.write('</td>');
	document.write('<td align="right">');
	document.write(p_silk_quant);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_item(2);" class="menu"><img src="images/buy_btn.gif" alt="Buy Silk goods" /></a>');
	document.write('</td>');
	document.write('</tr>');
	
	// Write ARMS line
	document.write('<tr>');
	document.write('    <td>');
	document.write('Arms');
	document.write('</td>');
	document.write('<td align="right" name="arm_price_pt">');
	printCurrency(g_arm_price);
	document.write('</td>');
	document.write('<td align="right">');
	document.write(p_arm_quant);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_item(3);" class="menu"><img src="images/buy_btn.gif" alt="Buy Armament goods" /></a>');
	document.write('</td>');
	document.write('</tr>');
	
	// Write RICE line
	document.write('<tr>');
	document.write('    <td>');
	document.write('Rice');
	document.write('</td>');
	document.write('<td align="right" name="rice_price_pt">');
	printCurrency(g_rice_price);
	document.write('</td>');
	document.write('<td align="right">');
	document.write(p_rice_quant);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_item(4);" class="menu"><img src="images/buy_btn.gif" alt="Buy Rice goods" /></a>');
	document.write('</td>');
	document.write('</tr>');
	
	// Write GENERAL line
	document.write('<tr>');
	document.write('    <td>');
	document.write('General');
	document.write('</td>');
	document.write('<td align="right" name="gen_price_pt">');
	printCurrency(g_gen_price);
	document.write('</td>');
	document.write('<td align="right">');
	document.write(p_gen_quant);
	document.write('</td>');
	document.write('<td>');
	document.write('<a href="JavaScript:select_item(5);" class="menu"><img src="images/buy_btn.gif" alt="Buy General goods" /></a>');
	document.write('</td>');
	document.write('</tr>');
	
	document.write('</table>');
}


// FUNCTION: showComments
// PURPOSE:  To show comments on the current market
function showComments()
{
	// Comment on various prices to guide the buyer - limit about 35 char
	if (g_jade_price < g_min_jade_price)  	// Typically when price is less than 10% of range
	{
		showAMessage('Jade is a bargain', 'Better buy Jade', 'Buy Jade now', 'Best buy on Jade', 'Jade on sale');	
	}
	else if ((g_jade_price > g_max_jade_price) && (c_jade_quant > 0))
	{
		showAMessage('Jade is astronomical!', 'Time to sell Jade!', 'Jade is high!', 'Jade is hot!', 'Sell Jade now!');
	}
	document.write('<br />');
	
	if (g_silk_price < g_min_silk_price)  	// Typically when price is less than 10% of range
	{	
		showAMessage('Silk is a way low', 'State is dumping Silk', 'Silk is a bargain', 'Time to stock up on Silk', 'Great price on Silk');
	}
	else if ((g_silk_price > g_max_silk_price) && (c_silk_quant > 0))
	{
		showAMessage('Everyone wearing Silk!', 'Silk is hot!', 'Silk an all time high!', 'Sell all Silk!', 'Silk is astronomical!');
	}
	document.write('<br />');
	
	if (g_arm_price < g_min_arm_price)  	// Typically when price is less than 10% of range
	{	
		showAMessage('Arms are cheap', 'Rebels dumping Arms', 'Arms are not in demand', 'Arms are a bargain', 'Arms are oversupply');
	}
	else if ((g_arm_price > g_max_arm_price) && (c_arm_quant > 0))
	{
		showAMessage('War must be starting!', 'Arms are in demand!', 'War rumors abound!', 'War is underway in China!', 'Iron shortage!');
	}
	document.write('<br />');
	
	if (g_rice_price < g_min_rice_price)  	// Typically when price is less than 10% of range
	{	
		showAMessage('Feed your sailors', 'Rice in oversupply', 'Rice is dirt cheap', 'State is dumping rice', 'Low demand for Rice');
	}
	else if ((g_rice_price > g_max_rice_price) && (c_rice_quant > 0))
	{
		showAMessage('Famine underway in China!', 'People are starving!', 'Everyone is hungry!', 'Sailors are starving!', 'Rice is hot!');
	}
	document.write('<br />');
	
	if (g_gen_price < g_min_gen_price)  	// Typically when price is less than 10% of range
	{	
		showAMessage('State dumping cargo', 'Fill the hold', 'Stock up on cargo', 'General cargo oversupply', 'General cargo a bargain');
	}
	else if ((g_gen_price > g_max_gen_price) && (c_gen_quant > 0))
	{
		showAMessage('General cargo in demand!', 'Empty the hold!', 'Sell general cargo!', 'Great time to sell cargo', 'Get rid of cargo');
	}
	document.write('<br />');

}


// FUNCTION: showCondition
// PURPOSE:  To show the overall market condition
function showCondition()
{
	// Evaluate an heuristic formula to determine the strength of the market
	var market_strength = g_jade_price/4975*0.4 + g_silk_price/527*0.3 + g_arm_price/80*0.15 + g_rice_price/57*0.1 + g_gen_price/15*0.05										;
	
	if (market_strength > 1.817)
	{	
		document.write('Strong as an Elephant!');
	}
	else if (market_strength > 1.058)
	{
		document.write('Unpredictable like a Panda!');
	}
	else 
	{
		document.write('Hungry like a Tiger!');
	}
}


// FUNCTION: showAMessage
// PURPOSE:  To show one of five possible messages over the course of an hour
function showAMessage(msg1, msg2, msg3, msg4, msg5)
{
	// Vary by time
	var now = new Date();
	var msg_time = Math.round(now.getMinutes() / 10);
	
	switch (msg_time)
	{
		case 1:
			document.write(msg1);
			break;
		case 2:
			document.write(msg2);
			break;
		case 3:
			document.write(msg3);
			break;
		case 4:
			document.write(msg4);
			break;
		case 5:
			document.write(msg5);
			break;
		default:
			document.write(msg1);
			break;
	}
}


// FUNCTION: showOceanCondition
// PURPOSE:  To show current conditions on the high seas
function showOceanCondition()
{
	// Selected at random from the current minutes past the hour
	var now = new Date();
	var ocean_hour = Math.round(now.getMinutes() / 10);
	
	// Select the ocean state based on the ocean hour
	switch (ocean_hour)
	{
		case 5:
			if (Math.random() > 0.5)	// Half the time show the Cyclone
			{
				document.write('Weather report calls for ' + g_ocean_state[5]);
			}
			else
			{
				document.write('Weather report calls for ' + g_ocean_state[4]);
			}
			break;
			
		default:
			document.write('Weather report calls for ' + g_ocean_state[ocean_hour]);
			break;
	}
	
}


// FUNCTION: showTravelComments
// PURPOSE:  To show general travel advisories
function showTravelComments()
{
	// Evaluate and comment on Current Travel Conditions
 	var advisory = Math.round(g_battlereadiness - Math.tan(g_pirate_proximity*g_pirate_proximity+Math.random()) - g_pirate_hostility + 4.0);
	
	// DEBUG: alert('Travel advisory is ' + advisory);
		
	switch (advisory)
	{
		case 1:
			document.write('Pirates have been seen nearby.');
			break;
			
		case 2:
			document.write('Pirates recently attacked that port.');
			break;
			
		case 3:
			document.write('Crew is restless, fearing a fight.');
			break;
			
		case 4:
			document.write('Onboard soldiers are performing drills.');
			break;
			
		case 5:
			document.write('Onboard soldiers are restless for action.');
			break;
			
		case 6:
			document.write('Navigator is having trouble seeing the stars.');
			break;
			
		default:
			document.write('Night watch reports nothing unusual.');
			break;
	}
}


// FUNCTION: showDebt
// PURPOSE:  To show debt payment plans
function showDebt()
{
	var payment = "1.00";
	
	// Update the inventory
	updateInventory();
	
    // Check for ZERO debt	
	if (c_debt < 1.00)
	{
		document.write('Honorable Wu thanks you for coming by to visit him!');
		c_payment = g_payment_counter_start;
		return;
	}	
	
	// Evaluate and comment on Current Debt
	if (c_debt <= c_cash)
	{	
		c_payment = Math.floor(0.25 * c_cash);
		if (c_payment > c_debt) c_payment = c_debt;
		payment = stringCurrency(c_payment);
		document.write('Honorable Wu suggests a payment of ' + payment + ' as a token of good faith.');
	}
	else if (c_debt < p_inventory)
	{
		c_payment = Math.floor(0.50 * p_inventory);
		if (c_payment > c_debt) c_payment = c_debt;
		payment = stringCurrency(c_payment);
		document.write('Wu suggests that you sell ' + payment + ' from your vast inventory and come back!');
	}
	else if (c_debt > 0)
	{
		c_payment = g_payment_counter_start;
		document.write('Wu humbly suggests that you seek out excellent markets and come back!');
	}
	else
	{
		document.write('Honorable Wu thanks you for coming by to visit him!');
		c_payment = 0.00;
	}

	// Preset payment value if positive
	if (c_debt > 0.00)
	{
		var prepayment = formatCurrency(c_payment, 2);
		document.repayable.paid.value = prepayment;
	}
}


// FUNCTION: showCurrencyLeading
// PURPOSE:  To show the appropriate currency sign
function showCurrencyLeading()
{
	// Evaluate and comment on Current Ocean Conditions
	switch (g_currency)
	{
		case 1:
			document.write(g_currency_lead);
			break;
			
		default:
			break;
	}
}


// FUNCTION: showCurrencyFollowing
// PURPOSE:  To show the appropriate currency sign
function showCurrencyFollowing()
{
	// Evaluate and comment on Current Ocean Conditions
	switch (g_currency)
	{
		case 1:
			break;
			
		default:
			document.write(g_currency_follow);
			break;
	}
}


// FUNCTION: pay_debt
// PURPOSE:  To pay your debt to Wu
function pay_debt()
{
	var payable = document.repayable.paid.value;
	var amt = payable.replace(",", "");

	// DEBUG: alert('Agreed to pay WU ' + amt);

	// Wu expects at least 10 percent of what you owe him
	if (amt < g_min_debt_payment * c_debt / 100.00) 
	{
		alert('Wu begs you to reconsider a payment that could be interpreted as an insult.');
		return;
	}
		
	// Wu does not expect you to overpay him
	if (amt > c_debt) 
	{
		alert('Wu thanks you for your generousity, but he does not accept tips.');
		return;
	}
		
	if (amt < c_cash)
	{
		// Pay off Wu
		c_cash = c_cash - amt;
		c_debt = c_debt - amt;
	}
	else
	{
		alert('Spies of Wu reported that you do not have that much cash available!');
		return;
	}

	// Save the changes
	document.holding.i_cash.value=c_cash;
	document.holding.i_debt.value=c_debt;
	saveUser();

	// Now go to the home window
	window.location = "home.htm";
	
}


// FUNCTION: count_down_wu
// PURPOSE:  To count down until your next payment to Wu is due
function count_down_wu()
{
	// If we owe Wu anything
	if (c_debt > 1.00)
	{
		// Increase the debt due to interest charges
		c_debt = c_debt * (1.00 + g_wu_interest_rate);		// Excessive by design!
		
		// Decrease amount of last payment as a count down timer for paying Wu again - i.e. by 100.00
		c_payment = (c_payment - g_expected_payment) > 0 ? c_payment - g_expected_payment : 0.00;
	
		// If we have reached 100, then show a warning for one time only this game
		if (c_payment <= g_expected_payment) 
		{
			// Display reminder only part of the time
			if (Math.random() > 0.8)
			{
				alert('Honorable Wu has sent a delegation to visit you. They remind you that timely payments are expected from his borrowers. They demand that you go see the Honorable Wu.');
			}
			return;
		}
		
		// If we have reached zero, then force the user to visit wu
		if ((c_debt > g_min_debt_payment) && (c_payment < g_min_debt_payment))
		{
			alert('Honorable Wu is disappointed with you. You have failed to make enough payments to satisfy him.');
			
			if (Math.random() > 0.80)
			{
				alert('Wu has taken your fleet in lieu of payment. You are ruined!');
				c_ship = 0;
				lose_inventory();
				updateUser();
				window.load = "quit.htm";
				return;	
			}
			else
			{
				alert('Wu has sent his warships to escort you home, so you can explain yourself!');
				c_locus = 7;
				updateUser();
				// DEBUG: alert('Now going to see Wu');
				window.load = "wu.htm";
				return;
			}
		
		}
		
  	}
	else
	{
		// Wipe out any remainder
		c_debt = 0.00;	
	}
	
	// Save the changes
	document.holding.i_payment.value=c_payment;
	document.holding.i_debt.value=c_debt;
	updateUser();

}


// FUNCTION: showBtnOption
// PURPOSE:  To show optional buttons on screen based on Port of Call
// NOTE:     Wu is only available in home port of Hong Kong
//           Expand is only available in Shanghai and Batavia
//           Armory is only available in Taipei and Pusan
function showBtnOption()
{
	switch (c_locus)
	{
		case 4:	// Pusan
			// Place Armory button on screen
			document.write('<a href="armory.htm" class="menu"><img src="images/armory_btn.gif" alt="Visit armory" /></a>');
			document.write('&nbsp;');
			break;
			
		case 5: // Shanghai
			// Place Expand button on screen
			document.write('<a href="expand.htm" class="menu"><img src="images/expand_btn.gif" alt="Expand fleet" /></a>');
			document.write('&nbsp;');
			break;
			
		case 6: // Taipei
			// Place Armory button on screen
			document.write('<a href="armory.htm" class="menu"><img src="images/armory_btn.gif" alt="Visit armory" /></a>');
			document.write('&nbsp;');
			break;
			
		case 7: // Hong Kong
			// Place Wu button on screen
			document.write('<a href="wu.htm" class="menu"><img src="images/wu_btn.gif" alt="Visit WU the Moneylender" /></a>');
			document.write('&nbsp;');
			break;
			
		case 8:	// Batavia
			// Place Expand button on screen
			document.write('<a href="expand.htm" class="menu"><img src="images/expand_btn.gif" alt="Expand fleet" /></a>');
			document.write('&nbsp;');
			break;
		
		default:	// Do nothing
			break;
		
	}
}


// FUNCTION: showTravelPatience
// PURPOSE:  To show travel patience advisory
function showTravelPatience()
{
	// Selected at random from the current minutes past the hour
	var now = new Date();
	var ocean_hour = Math.round(now.getMinutes() / 10);
	
	// Advise the user to be patient with the travel process
	switch (ocean_hour)
	{
		case 1:
			document.write('<em>It sometimes takes a little while.</em>');
			break;
			
		case 2:
			document.write('<em>You can not rush the wind. It blows when it wants to.</em>');
			break;
			
		case 3:
			document.write('<em>Sailing farther takes longer.</em>');
			break;
			
		case 4:
			document.write('<em>Ships depend on the wind, not the clock.</em>');
			break;
			
		default:
			document.write('<em>Sailing is tough business, so be patient...</em>');
			break;
	}
}


// FUNCTION: order_ship
// PURPOSE: To place an order and receive additional ships
function order_ship()
{
	// Ships typically cost 1000.00 each
	var cost=g_ship_price;
	
	// Can we buy them?
	var commissioned = parseInt(document.ship_order.order_quantity.value);
	// DEBUG: alert('About to buy ' + commissioned + ' ships at ' + cost);
	
	if (c_cash > commissioned * cost)
	{
		c_cash = c_cash - commissioned * cost;
		c_ship = c_ship + commissioned;
		c_tonnage = c_tonnage + commissioned * 50;
	}
	else
	{
		alert('You do not have enough cash for that many ships at this time!');
		return;
	}

	// Save the changes
	document.holding.i_cash.value=c_cash;
	document.holding.i_ship.value=c_ship;
	document.holding.i_tonnage.value=c_tonnage;
	// saveUser();

	// Now go to the home window
	window.location = "home.htm";

}


// FUNCTION: order_cannon
// PURPOSE: To place an order and receive additional cannon
function order_cannon()
{
	// Cannon typically cost 500.00 each
	var cost = g_cannon_price;
	
	// Identify how many have been ordered
	var gunnery = parseInt(document.cannon_order.order_quantity.value);
	// DEBUG: alert('About to buy ' + gunnery + ' more cannon at ' + cost + ' for ' + c_tonnage + ' cargo space.');
	
	// Do we have room for them?
	if ((gunnery + c_gun) > Math.floor(c_tonnage / 10 ))
	{
		alert('You have to have more ships to carry that much cannon!');
		return;
	}

	// Can we afford to buy them?
	if (c_cash > gunnery * cost)
	{
		c_cash = c_cash - gunnery * cost;
		c_gun = c_gun + gunnery;
	}
	else
	{
		alert('You do not have enough cash for that many cannon at this time!');
		return;
	}

	// Save the changes
	document.holding.i_cash.value=c_cash;
	document.holding.i_gun.value=c_gun;
	// updateUser();

	// Now go to the home window
	window.location = "home.htm";
}


// FUNCTION: setDestination
// PURPOSE:  To set the current destination
function setDestination(where)
{
	// Change the location
	c_last_locus = c_locus;
	switch (where)
	{
		case 0:
			c_place = g_destination[0];	// Pacific Ocean
			c_locus = where;
			break;
			
		case 1:
			c_place = g_destination[1];	// Tokyo
			c_locus = where;
			break;
			
		case 2:
			c_place = g_destination[2]; // Yokohama
			c_locus = where;
			break;
			
		case 3:
			c_place = g_destination[3]; // Kyota
			c_locus = where;
			break;
			
		case 4:
			c_place = g_destination[4]; // Pusan
			c_locus = where;
			break;
			
		case 5:
			c_place = g_destination[5]; // Shanghai
			c_locus = where;
			break;
			
		case 6:
			c_place = g_destination[6]; // Taipei
			c_locus = where;
			break;
			
		case 7:
			c_place = g_destination[7]; // Hong Kong
			c_locus = where;
			break;
			
		case 8:
			c_place = g_destination[8]; // Batavia
			c_locus = where;
			break;
			
		case 9:
			c_place = g_destination[9]; // Manila
			c_locus = where;
			break;

		case 10:
			c_place = g_destination[10]; // Bangkok
			c_locus = where;
			break;

		default:
			c_place = g_destination[0]; // Pacific Ocean
			c_locus = where;
			break;
	}

	// Save the changes to our port location
	document.holding.i_place.value=c_place;
	document.holding.i_locus.value=c_locus;
	document.holding.i_last_locus.value=c_last_locus;
	saveUser();

}


// FUNCTION: set_sail
// PURPOSE: To set sail for a new port
function set_sail()
{
	// DEBUG: alert('Now setting sail from ' + c_place + '(' + c_locus + ') in the Pacific');
	
	// Identify the port selected from the drop down list
	var new_port = document.harbormaster.destination.selectedIndex;
	if (new_port >= 1)
	{
		// Set new destination
		setDestination(new_port);	// Sets c_place, c_locus, c_last_locus
		
		// Identify the new locus and port name
		var port_name = document.harbormaster.destination.options[new_port].text;
		// DEBUG: alert('New port selection is ' + port_name + ':' + new_port + ' from ' + c_last_locus);
	
		// Handle case where the new port is the same as the existing port
		if (c_last_locus == c_locus)
		{
			// Just return to current port
			updateUser();
			window.location = "home.htm";
		}
		
		// Go sailing to the new port
		updateUser();
		window.location = "sailing.htm?dst=" + c_place;

	}
	else
	{
		// Nothing selected
		alert('You need to select a different port!');
        window.location.reload();
		
	}
}


// FUNCTION: sailing_to
// PURPOSE: To set sail for a specific port as named
function sailing_to(dst)
{
	// DEBUG: alert('Now sailing from ' + c_place + '(' + c_locus + ') to ' + dst);
	
	// Identify the port selected from the argument given
	var new_port = 7;	// By default, go to Hong Kong
	// Lookup port based on dst;
	for (port=1; port<g_destination.length; port++)
	{
		if (dst == g_destination[port])
		{
			new_port = port;
			break;
		}
	}
	
	if (new_port >= 1)
	{
		// Set new destination
		setDestination(new_port);	// Sets c_place, c_locus, c_last_locus
		
		// Identify the new locus and port name
		var port_name = g_destination[new_port];
		// DEBUG: alert('New port selection is ' + port_name + ':' + new_port + ' from ' + c_last_locus);
	
		// Handle case where the new port is the same as the existing port
		if (c_last_locus == c_locus)
		{
			// Just return to current port
			updateUser();
			window.location = "home.htm";
		}
		
		// Go sailing to the new port
		updateUser();
		window.location = "sailing.htm?dst=" + c_place;

	}
	else
	{
		// Nothing selected
		alert('You need to select a different port!');
        window.location.reload();
		
	}
}


// FUNCTION: showAllPrices
// PURPOSE:  To show the current market prices in a pop up window
function showAllPrices()
{
	// Show current prices for commodities
	// DEBUG
	alert('Prices set to: {Jade..Gen} {' + g_jade_price + ', ' + g_silk_price + ', ' + 
		g_arm_price + ', ' + g_rice_price + ', ' + g_gen_price + '}');
}
			


// FUNCTION: setPrices
// PURPOSE:  To set the market prices for various goods
// CALCULATE: The following calculations are used to produce variance
//     JADE: $A3*$A3*COS($A3/0.9+0.3)+5000; MIN: 1543.162, MAX: 7986.871, AVG: 4974.938
//     SILK: 20/LOG($A3/5+0.3)+500; MIN: 62.913, MAX: 983.177, AVG: 527.488
//     ARMS: COS($A3)*COS($A3)*50+55; MIN: 55.001, MAX: 105.000, AVG: 80.116
//     RICE: 60/SQRT($A3+0.1)+30*SIN($A3/0.5)+40; MIN: 18.346, MAX: 229.737, AVG: 56.901
//     GEN:  TAN(-A5)+9.5; MIN: 1.169, MAX: 235.451, AVG: 15.232
// 			
function setPrices()
{
	// Determine the current second
	var now = new Date();
	var sec = now.getSeconds();
	
	// Set the prices arbitrarily to something else
	switch (c_locus)
	{
		case 1:	// Tokyo has high prices for Jade
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+7000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+500;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+55.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+40.0;
			g_gen_price = Math.tan(-1.00*sec)+9.5;
			break;
	
		case 2:	// Yokohama has high prices for Silk
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+5000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+900;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+55.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+40.0;
			g_gen_price = Math.tan(-1.00*sec)+9.5;
			break;
	
		case 3:	// Kyota has high prices for General Cargo
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+5000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+500;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+55.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+40.0;
			g_gen_price = Math.tan(-1.00*sec)+19.5;
			break;
	
		case 4:	// Pusan has high prices for Arms
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+5000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+500;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+95.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+40.0;
			g_gen_price = Math.tan(-1.00*sec)+9.5;
			break;
	
		case 5:	// Shanghai has low prices for Silk
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+5000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+200;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+55.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+40.0;
			g_gen_price = Math.tan(-1.00*sec)+9.5;
			break;
	
		case 6:	// Taipei has low prices for General Cargo
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+5000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+500;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+55.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+40.0;
			g_gen_price = Math.tan(-1.00*sec)+4.5;
			break;
	
		case 7:	// Hong Kong has low prices for Rice		
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+5000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+500;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+55.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+20.0;
			g_gen_price = Math.tan(-1.00*sec)+9.5;
			break;
			
		case 8:	// Batavia has low prices for Arms
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+5000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+500;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+15.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+40.0;
			g_gen_price = Math.tan(-1.00*sec)+9.5;
			break;
	
		case 9:	// Manila has high prices for Rice
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+5000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+500;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+55.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+90.0;
			g_gen_price = Math.tan(-1.00*sec)+9.5;
			break;
	
		case 10:	// Bangkok has low prices for Jade
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+1000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+500;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+55.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+40.0;
			g_gen_price = Math.tan(-1.00*sec)+9.5;
			break;
	
		default:	// For any new ports added		
			g_jade_price = sec * sec * Math.cos(sec/0.9+0.3)+5000.00;
			g_silk_price = 20.0/Math.log(sec/5+0.3)+500;
			g_arm_price = Math.cos(sec)*Math.cos(sec)*50.00+55.00;
			g_rice_price = 60.0/Math.sqrt(sec + 0.1)+30.0*Math.sin(sec/0.5)+40.0;
			g_gen_price = Math.tan(-1.00*sec)+9.5;
			break;
			
	}
	
	// Prices can not go below one:
	g_jade_price = g_jade_price < 1.00 ? g_min_jade_price + 776.34 : g_jade_price;
	g_silk_price = g_silk_price < 1.00 ? g_min_silk_price + 55.61 : g_silk_price;
	g_arm_price = g_arm_price < 1.00 ? g_min_arm_price + 4.14: g_arm_price;
	g_rice_price = g_rice_price < 1.00 ? g_min_rice_price + 0.98 : g_rice_price;
	g_gen_price = g_gen_price < 1.00 ? g_min_gen_price + 0.95 : g_gen_price;
			
	// Show current prices for commodities
	// DEBUG
	// alert('Prices set to: {Jade..Gen} {' + g_jade_price + ', ' + g_silk_price + ', ' + 
	// 	g_arm_price + ', ' + g_rice_price + ', ' + g_gen_price + '}');
}
			

// FUNCTION: showSightGlass
// PURPOSE: To manipulate the sight glass view
function showSightGlass()
{
	// image is 260 x 263
	
	// sightglass.src = 'images/at_sea_1.jpg';


}


// FUNCTION: showVendor
// PURPOSE:  To show a dummy vendor for the Purchase or Sales Order
function showVendor()
{
	// Select a news comment at random based on the time of day
	var now = new Date();
	var now_hr = now.getHours();
	var now_sec = now.getSeconds();
	var where = c_place.replace("_", " ");
	
	// DEBUG: alert('Current vendor is number ' + now_sec + ' at ' + now_hr + ' Harbor Village');
	
	switch (now_sec)
	{
		case 0:
			document.write('Wang Chang Imports<br />' + now_hr + ' Harbor Village<br />');
			document.write(where + '<br />');   
			break;
			
		case 5:
			document.write('Chen Shu Imports<br />' + now_hr + ' Harbor Road<br />');
			document.write(where + '<br />');   
			break;
			
		case 10:
			document.write('Li Wei Imports<br />' + now_hr + ' Harbor Village<br />');
			document.write(where + '<br />');   
			break;
			
		case 15:
			document.write('Zhang Chang Imports<br />' + now_hr + ' Harbor Village<br />');
			document.write(where + '<br />');   
			break;
			
		case 20:
			document.write('Liu Wong Imports<br />' + now_hr + ' Harbor Bay Road<br />');
			document.write(where + '<br />');   
			break;
			
		case 25:
			document.write('Yang Ze Imports<br />' + now_hr + ' Harbor Village<br />');
			document.write(where + '<br />');   
			break;
			
		case 30:
			document.write('Huang Mong Imports<br />' + now_hr + ' Harbor Road<br />');
			document.write(where + '<br />');   
			break;
			
		case 35:
			document.write('Wu Lu Imports<br />' + now_hr + ' Harbor Village<br />');
			document.write(where + '<br />');   
			break;
			
		case 40:
			document.write('Lin Chee Imports<br />' + now_hr + ' Harbor Village<br />');
			document.write(where + '<br />');   
			break;
			
		case 45:
			document.write('Zhou Su Imports<br />' + now_hr + ' Harbor Road<br />');
			document.write(where + '<br />');   
			break;
			
		case 50:
			document.write('Ye Chang Imports<br />' + now_hr + ' Harbor Village<br />');
			document.write(where + '<br />');   
			break;
			
		case 55:
			document.write('Zhao Zuu Imports<br />' + now_hr + ' Harbor Village<br />');
			document.write(where + '<br />');   
			break;
			
		default:
			document.write('Xu Gao Imports<br />' + now_hr + ' Harbor Bay Road<br />');
			document.write(where + '<br />');   
			break;		
	}
	
}


// FUNCTION: showShipTo
// PURPOSE:  To show the address of the Ship for buying or selling
function showShipTo()
{
	// Select a berth based on the time of day
	var now = new Date();
	var now_min = Math.floor(now.getMinutes()/3)+1;
		
	// Display the address
	var where = c_place.replace("_", " ");
	document.write(c_hong + '<br />' + 'Berth ' + now_min + '<br />');
	document.write(where + '<br />');   
}


// FUNCTION: showDescription
// PURPOSE:  To show the description for the currently selected good
function showDescription()
{
	// Display description based on selection
	switch (c_selection)
	{
		case 1:
			document.write('Exquisite&nbsp;jade&nbsp;artwork' + '<br />');
			break;
			
		case 2:
			document.write('Fine&nbsp;silk&nbsp;cloth' + '<br />');
			break;
			
		case 3:
			document.write('Tough&nbsp;general&nbsp;armaments' + '<br />');
			break;
			
		case 4:
			document.write('Freshly&nbsp;harvested&nbsp;rice' + '<br />');
			break;
			
		case 5:
			document.write('Packed&nbsp;general&nbsp;cargo' + '<br />');
			break;
			
		default:
			document.write('unspecified&nbsp;cargo' + '<br />');
			break;
	}

}


// FUNCTION: showPrice
// PURPOSE:  To show the price for the currently selected good
function showPrice()
{
	// Print the current price
	printCurrency(c_price);
}


// FUNCTION: showTotalPrice
// PURPOSE:  To show the price for the currently selected good
function showTotalPrice()
{
	// Use current quantity and price if non zero
	if (c_quant > 0)
	{
		printCurrency(c_quant * c_price);
	}
	else
	{
		// Just print the price
		printCurrency(c_price);
	}
}


// FUNCTION: updateExtendedPrice
// PURPOSE:  To update the price for the currently selected good
// 									<div id="price_pt">
// 									<div id="total_price_pt">
// 									<span class="right_statement" id="carry_down_total">
function updateExtendedPrice()
{
	// Determine how many
	c_quant = parseInt(document.transaction.units.value);
	
	// Determine selection
	switch (c_selection)
	{
		case 1:
			document.price_pt.value = stringCurrency(g_jade_price);
			document.total_price_pt.value = stringCurrency(c_quant * g_jade_price);
			document.carry_down_total.value = stringCurrency(c_quant * g_jade_price);
			break;
			
		case 2:
			document.price_pt.value = stringCurrency(g_silk_price);
			document.total_price_pt.value = stringCurrency(c_quant * g_silk_price);
			document.carry_down_total.value = stringCurrency(c_quant * g_silk_price);
			break;
			
		case 3:
			document.price_pt.value = stringCurrency(g_arm_price);
			document.total_price_pt.value = stringCurrency(c_quant * g_arm_price);
			document.carry_down_total.value = stringCurrency(c_quant * g_arm_price);
			break;
			
		case 4:
			document.price_pt.value = stringCurrency(g_rice_price);
			document.total_price_pt.value = stringCurrency(c_quant * g_rice_price);
			document.carry_down_total.value = stringCurrency(c_quant * g_rice_price);
			break;
			
		case 5:
			document.price_pt.value = stringCurrency(g_gen_price);
			document.total_price_pt.value = stringCurrency(c_quant * g_gen_price);
			document.carry_down_total.value = stringCurrency(c_quant * g_gen_price);
			break;
			
		default:
			document.price_pt.value = stringCurrency(g_gen_price);
			document.total_price_pt.value = stringCurrency(c_quant * g_gen_price);
			document.carry_down_total.value = stringCurrency(c_quant * g_gen_price);
			break;
	}

	// Reload the page
	window.reload;
}


// FUNCTION: updateCalc
// PURPOSE:  To show the price for the currently selected good
// NOTE:     Rereads quantity selected for purchase or sale, 
//           then adjusts the price total as appropriate.
function updateCalc()
{
	// Determine how many
	c_quant = parseInt(document.transaction.units.value);
	
	// Determine selection
	// ISSUE: These values do not seem to update on the screen when this runs. Why?
	// DEBUG: alert('Changed quantity to ' + c_quant + ' for item ' + c_selection + ' at price ' + c_price);

	// Update the extended price on the screen
	updateExtendedPrice();
	
	// Reload the page
	window.reload;
	
}



// FUNCTION: evaluatePurchase
// PURPOSE:  To evaluate the purchase data for this buy request
// NOTE:     This expects the form element transaction.units to be extant.
function evaluatePurchase()
{
	// Set the recommended units to purchase
	if (c_quant > 0)
	{
		document.transaction.quant.value = c_quant;
		document.transaction.units.value = c_quant;
	}
	
	// DEBUG: alert('Scheduled to buy ' + c_quant + ' item w/id ' + c_selection + ' at price ' + c_price);
}


// FUNCTION: select_item(good)
// PURPOSE:  To select an item in the market for purchase
function select_item(good)
{
	// Recalculate maximum quantities you can purchase
	affordability();
	
	// Assign the selection for persistence
	c_selection = good;
	
	switch(c_selection)
	{
		case 1:
			c_price = g_jade_price;
			c_quant = p_jade_quant;
			break;
			
		case 2:
			c_price = g_silk_price;
			c_quant = p_silk_quant;
			break;
			
		case 3:
			c_price = g_arm_price;
			c_quant = p_arm_quant;
			break;
			
		case 4:
			c_price = g_rice_price;
			c_quant = p_rice_quant;
			break;
			
		case 5:
			c_price = g_gen_price;
			c_quant = p_gen_quant;
			break;
			
		default:
			c_price = g_gen_price;
			c_quant = p_gen_quant;
			break;
	}
	
	// Save the values in the form
	document.holding.i_selection.value=c_selection;
	document.holding.i_price.value=c_price;
	document.holding.i_quant.value=c_quant;
	
	// Save the selection
	updateUser();
	
	// DEBUG: alert('User has chosen to buy ' + c_selection + ' at ' + c_price + ' - recommend getting ' + c_quant);
	
	// Go to the buy window
	window.location = "buy.htm?item=" + c_selection;
	
}


// FUNCTION: buy_cargo
// PURPOSE:  To purchase the specified cargo
// NOTE:     This expects the element purchase.units to be extant
function buy_cargo()
{
	// Determine parameters of the sale
	var how_many = 1;
	c_cargo = c_jade_quant + c_silk_quant + c_arm_quant + c_rice_quant + c_gen_quant;
	var left_in_hold = c_tonnage - c_cargo;

	// Identify how many units the user is buying - can be changed in the form		
	how_many = parseInt(document.transaction.units.value);
    if (how_many > 0) c_quant = how_many;
	
	// Do we have room for these?
	if (left_in_hold < how_many)
	{
		alert('Comprador reports that we do not have that much room left!');
		window.load = 'home.htm';
		return;
	}
	
	// DEBUG: alert('About to purchase ' + c_quant + ' of item ' + c_selection + ' at price $' + c_price + '.');

	// Make the purchase if we have sufficient funds
	if (c_quant * c_price < c_cash)
	{
		// Adjust our cash
		c_cash = c_cash - c_quant * c_price;
		switch(c_selection)
		{
			case 1:
				c_jade_quant = c_jade_quant + c_quant;
				break;
				
			case 2:
				c_silk_quant = c_silk_quant + c_quant;
				break;
				
			case 3:
				c_arm_quant = c_arm_quant + c_quant;
				break;
				
			case 4:
				c_rice_quant = c_rice_quant + c_quant;
				break;
				
			case 5:
				c_gen_quant = c_gen_quant + c_quant;
				break;
				
			default:	// Can not buy air, so put the money back
				c_cash = c_cash + c_quant * c_price;
				break;
		}

		// Complete the sale and update the inventory
		updateInventory();
		// DEBUG: ('You purchased ' + c_quant + ' units and now have ' + c_cash + ' left.');
		
		// Save and go home
		updateUser();
		window.location = "home.htm";		
	}
	else
	{
		alert('You do not have that much cash available.');
	}
	
}


// FUNCTION: evaluateSale
// PURPOSE:  To evaluate the sale data for this sale request
// NOTE:     This expects the form element transaction.units to be extant.
function evaluateSale()
{
	// Set the recommended units to purchase
	// if c_quant > 0 {...}
	document.transaction.quant.value = c_quant;
	document.transaction.units.value = c_quant;
	// 								<form name="transaction" action="" method="POST">
	//									<input name="units" value="1" align="right" alt="Number of units to purchase" size="5">
	
	// DEBUG: alert('Scheduled to sell ' + c_quant + ' item w/id ' + c_selection + ' at current market price of ' + c_price);
}


// FUNCTION: select_sale(good)
// PURPOSE:  To select an item in the market for sale
function select_sale(good)
{
	// Recalculate maximum quantities you can purchase
	availability();
	
	// Assign the selection for affordability
	c_selection = good;
	
	switch(c_selection)
	{
		case 1:
			c_price = g_jade_price;
			c_quant = p_jade_quant;
			break;
			
		case 2:
			c_price = g_silk_price;
			c_quant = p_silk_quant;
			break;
			
		case 3:
			c_price = g_arm_price;
			c_quant = p_arm_quant;
			break;
			
		case 4:
			c_price = g_rice_price;
			c_quant = p_rice_quant;
			break;
			
		case 5:
			c_price = g_gen_price;
			c_quant = p_gen_quant;
			break;
			
		default:
			c_price = g_gen_price;
			c_quant = p_gen_quant;
			break;
	}
	
	// Save the values in the form
	document.holding.i_selection.value=c_selection;
	document.holding.i_price.value=c_price;
	document.holding.i_quant.value=c_quant;
	
	// Save the selection
	updateUser();
	
	// DEBUG: alert('User has chosen to sell ' + c_selection + ' at ' + c_price + ' - recommend selling ' + c_quant);
	
	// Go to the buy window
	window.location = "sell.htm?item=" + c_selection;
	
}


// FUNCTION: sell_cargo
// PURPOSE:  To sell the specified cargo
function sell_cargo()
{
	var how_many = 1;
	c_cargo = c_jade_quant + c_silk_quant + c_arm_quant + c_rice_quant + c_gen_quant;

	// Identify how many units the user is selling		
	how_many = parseInt(document.transaction.units.value);
    if (how_many > c_cargo)
	{
		alert('Comprador reports that we do not have that much available!');
		window.load = 'home.htm';
		return;
	}
	else
	{
		c_quant = how_many;
	}
	
	// DEBUG: alert('You indicated that you want to sell ' + c_quant + ' items of ' + c_selection + ' at price $' + c_price + '.');

	// Make the sale if we have anything to sell
	if (c_quant * c_price > 0.00)
	{
		// Adjust our cash
		c_cash = c_cash + c_quant * c_price;
		switch(c_selection)
		{
			case 1:
				if (c_jade_quant >= c_quant) 
				{
					c_jade_quant = c_jade_quant - c_quant;
				}
				else
				{
					alert('You do not have that much jade available!');
					window.location = "home.htm";		
					return;		
				}
				break;
				
			case 2:
				if (c_silk_quant >= c_quant) 
				{
					c_silk_quant = c_silk_quant - c_quant;
				}
				else
				{
					alert('You do not have that much silk available!');
					window.location = "home.htm";		
					return;		
				}
				break;
				
			case 3:
				if (c_arm_quant >= c_quant) 
				{
					c_arm_quant = c_arm_quant - c_quant;
				}
				else
				{
					alert('You do not have that many arms available!');
					window.location = "home.htm";		
					return;		
				}
				break;
				
			case 4:
				if (c_rice_quant >= c_quant) 
				{
					c_rice_quant = c_rice_quant - c_quant;
				}
				else
				{
					alert('You do not have that much rice available!');
					window.location = "home.htm";		
					return;		
				}
				break;
				
			case 5:
				if (c_gen_quant >= c_quant) 
				{
					c_gen_quant = c_gen_quant - c_quant;
				}
				else
				{
					alert('You do not have that much general cargo available!');
					window.location = "home.htm";
					return;		
				}
				break;
				
			default:	// Can not buy air, so put the money back
				c_cash = c_cash - c_quant * c_price;
				break;
		}

		// Complete the sale and update the inventory
		updateInventory();
		// DEBUG: alert('You sold ' + c_quant + ' units and now have ' + c_cash + ' available.');
		
		// Save and go home
		updateUser();
		window.location = "home.htm";		
	}
	else
	{
		alert('Comprador: You have to enter a valid quantity to sell!');
	}
	

}


// FUNCTION: lose_inventory
// PURPOSE:  To handle the case where we lose inventory because of pirates or storm
// NOTE:     This does NOT UPDATE the cookie. Calling function should
function lose_inventory()
{
	// Wipe out current inventory
	c_jade_quant = 0;
	c_silk_quant = 0;
	c_arm_quant = 0;
	c_rice_quant = 0;
	c_gen_quant = 0;
	
	// Update inventory calculations
	updateInventory();
	
}


// FUNCTION: lose_cash
// PURPOSE:  To handle the case where we lose cash because of pirates or storm
// NOTE:     This does NOT UPDATE the cookie. Calling function should
function lose_cash()
{
	// Also lose some cash as appropriate
	if (c_cash > 100000.00)
	{
		// Lose all cash but our reserve is a single piece of Jade
		c_cash = 0.00;
		c_jade_quant = 1;
	}
	else if (c_cash > 5000.00)
	{
		// Just lose 50 percent of it
		c_cash = Math.floor(c_cash / 2);
	}
	else
	{
		// Lose nothing - you are already poor
		c_cash = c_cash - 0.00;
	}

	// Update inventory calculations
	updateInventory();
	
}


// FUNCTION: showQuote
// PURPOSE:  To evaluate the performance of the player and encourage them to play again
function showQuote()
{
	// Update the inventory
	updateInventory();
	
	// Based on final totals for the game
	c_total = c_cash + p_inventory - c_debt;

	// Classify and report
	if (c_total > 500000)
	{
		document.write('Yes, I sold him goods many times. I was always glad to see him come by, for I knew that ');
		document.write('I could wrangle extra profits from him. He never haggled the price. He always took the ');
		document.write('goods at the price that I had marked them for. I wish that he&acute;d come to my shop more ');
		document.write('often; I would have made more profit.');
	}
	else if (c_total > 5000)
	{
		document.write('I dealt with him on a regular basis when he came to the market. I found him to be ');
		document.write('both honest and fair, with a sharp eye for a bargain. And he never haggled with ');
		document.write('me over the price. Also, he would always pay in gold coin, which I liked. I ');
		document.write('respected him and he respected me, so we had many business dealings together. ');
		document.write('I would hope to see him in business again in the near future.');
	}
	else if (c_total > 500)
	{
		document.write('He never seemed to make much profit, but times were tough on everybody. I usually ');
		document.write('had to insist that payment be made at the time the goods were delivered. I never ');
		document.write('took a chance on missing payment. But he was an honest comprador and I respected ');
		document.write('him for it. I would thus give him a good deal in the marketplace whenever I could. ');
		document.write('I don&acute;t know what happened, but I hope to have business dealings with him ');
		document.write('again in the future.');
	}
	else
	{
		document.write('From what I could tell he had a reputation for poor quality in merchandise. I ');
		document.write('don&acute;t think it was his fault. I heard they had a navigator on board who ');
		document.write('did&acute;t always know how to read the stars right. So they spent a lot of ');
		document.write('time sailing around in circles! And food goods spoil when you leave them onboard a ');
		document.write('ship for too long. Once you get a reputation for poor quality, people get reluctant ');
		document.write('to do business with you. Perhaps you&acute;ll get a better navigator next time.');
	}

}


// FUNCTION: showEvaluation
// PURPOSE:  To evaluate the performance of the player and encourage them to play again
function showEvaluation()
{
	// Update the inventory
	updateInventory();
	
	// Based on final totals for the game
	c_total = c_cash + p_inventory - c_debt;

	// Classify and report
	if (c_total > 500000)
	{
		document.write('You were a superb player, and you will be honored in the history of the company. ');
		document.write('In spite of the misfortunes that may have come your way, you always seemed to ');
		document.write('come out on top. And you never lost hope in finding a better price at another ');
		document.write('port of call. The navigator was amazed that you always seemed to find the best ');
		document.write('markets. The crew will receive a bonus, guaranteeing that they will sail with ');
		document.write('you again. Some have already asked when you will be forming another company. ');
		document.write('What should I tell them?');
	}
	else if (c_total > 5000)
	{
		document.write('Congratulations! You ran a good company, and managed a good profit. Although most ');
		document.write('of your deals were profitable, there were some exceptions. You will want to try ');
		document.write('harder next time. One tip is to pay off your debt early in the game, then you can ');
		document.write('rake in more profits later. The navigator reports that you did not always know the ');
		document.write('best port to go to, but you never made him sail around in circles either. For that ');
		document.write('he is thankful. The soldiers found you to be an excellent leader, and several have ');
		document.write('asked to be your personal guard in the future. Most of the crew liked you. At least, ');
		document.write('they never talked of mutiny under your command. Perhaps you will want to play again.');
	}
	else if (c_ship > 1)
	{
		document.write('Well, you didn&acute;t make much profit, but it was a tough year. However, ');
		document.write('you did build your hong and paid your sailors well. You have earned a good reputation ');
		document.write('and most merchants respect you. Your soldiers are loyal, and your navigator says ');
		document.write('that he will sail with you again. In fact, all of the remaining crew would be willing ');
		document.write('to sail with you again in the near future.');
	}
	else
	{
		document.write('However, you did run a tight ship, and most of the sailors who served on your ship ');
		document.write('obeyed your orders. The soldiers fought bravely when the pirates attacked. And the ');
		document.write('comprador was an honorable man. He never stole your goods or sold them under the ');
		document.write('table. Most of the crew stated that they would sail with ');
		document.write('you again in the future.');
	}

}



////////////////////////////////////////////////////   END ORIGINAL CODE    //////////////////////////////////////


//  End


