var left_margin_px=80
var top_margin_px=10

var crosshair_px=30

// width of graph area divided by (x_highval-x_lowval)
var x_pix_per_value=80./10000
// height of graph area divided by (y_highweight-y_lowval)
var y_pix_per_value=32./100

var graph_height=256

var x_lowval=40000
var y_lowval=1500
var y_highweight=2200

// if using total moment-arm, set to 1
// if using CG, set to 0
var is_moment=1
function set_graph_height(x)
{
	graph_height=x
}
function set_x_lowval(x)
{
	x_lowval=x
}
function set_y_lowval(x)
{
	y_lowval=x
}
function set_y_highweight(x)
{
	y_highweight=x
}
function set_x_pix_per_value(pix_per_step,step)
{
	x_pix_per_value=pix_per_step/step
}
function set_y_pix_per_value(pix_per_step,step)
{
	y_pix_per_value=pix_per_step/step
}
function set_is_moment(x)
{
	is_moment=x
}

function WB_Plot(weight, moment)
{
	x_val=moment
	if(is_moment==0)
	{
		x_val=moment/weight
	}

	// Left-margin on the graph is 65 pixels...
	var x = Math.round(left_margin_px + ((moment - x_lowval) * x_pix_per_value))-crosshair_px/2
	var y = graph_height+top_margin_px - Math.round(((weight - y_lowval) * y_pix_per_value)) - crosshair_px/2;
	document.images.crossHairImage.style.left = x + 'px';
	document.images.crossHairImage.style.top  = y + 'px';
	document.images.crossHairImage.style.visibility = "visible";
}

function WB_Calculate(fields)
{
	var totalWeight=0
	var totalMoment=0
	for (fieldname in fields)
	{
		var field=document.getElementById(fieldname+"Weight")
		if(field)
		{
			if(isNaN(parseFloat(field.value))==false)
			{
				totalWeight+=parseFloat(field.value);
				totalMoment+=parseFloat(field.value) * parseFloat(fields[fieldname])
				if(is_moment)
				{
					document.getElementById(fieldname+"Moment").value=Math.round(parseFloat(field.value) * parseFloat(fields[fieldname]))
				}
			}
			else if(is_moment)
			{
				document.getElementById(fieldname+"Moment").value=""
			}
		}
	}
	document.getElementById("totalWeight").value = totalWeight
	document.getElementById("weightMargin").value= y_highweight-totalWeight
	if(is_moment)
	{
		document.getElementById("totalMoment").value = Math.round(totalMoment)
		WB_Plot(Number(totalWeight), parseFloat(totalMoment));
	}
	else
	{
		document.getElementById("CG").value = Math.round(totalMoment/totalWeight*100)/100
		WB_Plot(Number(totalWeight), parseFloat(totalMoment/totalWeight));
	}
	if(y_highweight<totalWeight)
	{
		alert("Danger! Weight exceeds maximum allowable by " + (totalWeight-y_highweight) + "!") 
	}
	// Show the crosshair on the graph...
}

// fields is an associative array
// aircraftArm, frontSeatArm, rearSeatArm, baggageArm, fuelArm
// the value in each case is 
function WB_Reset(fields)
{
	for (fieldname in fields)
	{
		document.getElementById(fieldname+"Lever").value=fields[fieldname]
	}

	// Calculate based on empty values...
	WB_Calculate(fields);
}

