// ----------------------------------------------------------- //
// Populates the ratio textboxes for the selected transmission //
// ----------------------------------------------------------- //
function GetRatios()
{
	// Clear the existing values
	for ( var i=1; i<=6; i++ )
	{
	    var txt = document.getElementById("txtGear" + i);
		txt.value = "";
	}
	
	// Check a transmission has been selected
	var ctrlTrans = document.getElementById("ctl00_cphMain_ddlTransmissions");
	if ( ctrlTrans.value == "0" ) return;
	
	// Build the URL for the AJAX request
	var url = "?AjaxAction=getratios&TransmissionID=" + ctrlTrans.value;
	
	// Make the AJAX call
	request.GetNoCache( url, function(result)
	{
		if ( result.readyState != ReadyState.Complete )
		{
			return;
		}
			
		if ( result.status == HttpStatus.OK && result.responseText != "" )
		{
			// The result was successful and returned data
			var vals = result.responseText.split("|");
			
			if ( vals.length < 2 )
			{
				// An error message was returned
				window.alert( result.responseText );
			}
			else
			{
				// Clear the existing list of speeds
				ClearSpeeds();

				// Loop through the list of returned ratios and populate the textboxes
				for ( var i=0; i<vals.length; i++ )
				{
				    var txt = document.getElementById("txtGear" + (i + 1));
					txt.value = vals[i];
				}
				
				// Calculate the speeds for the gear ratios
				CalculateGear( true );
			}
		}
		else
		{
			// Handle the failure condition
			window.alert( "There was an unknown error" );
		}
	}
	)
}

// ------------------------------------------------------ //
// Calculates the wheel dimensions for the specified tyre //
// ------------------------------------------------------ //
function CalculateWheel(tyreNo)
{
	// Determine if we're calculating for one or two wheels
	var calcSecond = false;
	if ( tyreNo == 0 )
	{
		tyreNo = 1;
		calcSecond = true;
	}
	
	// Get control references
	var ctrlDiameter = document.getElementById("ctl00_cphMain_ddlRimDiameter" + tyreNo);
	var ctrlWidth = document.getElementById("ctl00_cphMain_ddlTyreWidth" + tyreNo);
	var ctrlProfile = document.getElementById("ctl00_cphMain_ddlTyreProfile" + tyreNo);
	
	// Build the URL for the AJAX request
	var url = "?AjaxAction=calcwheel&Diameter=" + ctrlDiameter.value;
	url += "&Width=" + ctrlWidth.value;
	url += "&Profile=" + ctrlProfile.value;
	
	// Make the AJAX call
	request.GetNoCache( url, function(result)
	{
		if ( result.readyState != ReadyState.Complete )
		{
			return;
		}
			
		if ( result.status == HttpStatus.OK && result.responseText != "" )
		{
			// The result was successful and returned data
			var vals = result.responseText.split("|");
			
			if ( vals.length < 2 )
			{
				// An error message was returned
				window.alert( result.responseText );
			}
			else
			{
				// Clear the existing list of speeds
				ClearSpeeds();
				
				// Display the rolling disameter
				var spnRD = document.getElementById( "spnRollingDiameter" + tyreNo );
				spnRD.innerHTML = vals[0] + " mm";
				
				// Display the rolling circumference
				var spnRC = document.getElementById( "spnRollingCircumference" + tyreNo );
				spnRC.innerHTML = vals[1] + " mm";
				var txtTC = document.getElementById("txtTyreCircumference" + tyreNo);
				txtTC.value = vals[1];
				
				// Make a second AJAX call if we're calculating for both wheels
				if ( calcSecond ) CalculateWheel( 2 );
				CalculateWheelDiff();
			}
		}
		else
		{
			// Handle the failure condition
			window.alert( "There was an unknown error" );
		}
	}
	)
}

// ------------------------------------------------------- //
// Calculates the difference in dimensions for both wheels //
// ------------------------------------------------------- //
function CalculateWheelDiff()
{
	// Get control references
	var spnRD1 = document.getElementById( "spnRollingDiameter1" );
	var spnRD2 = document.getElementById( "spnRollingDiameter2" );
	var spnRC1 = document.getElementById( "spnRollingCircumference1" );
	var spnRC2 = document.getElementById( "spnRollingCircumference2" );
	var spnRDD = document.getElementById( "spnRollingDiameterDiff" );
	var spnRCD = document.getElementById( "spnRollingCircumferenceDiff" );
	
	// Check if we have calculated values for both wheels
	if ( spnRD1.innerHTML == "" || spnRD2.innerHTML == "" || spnRC1.innerHTML == "" || spnRC2.innerHTML == "" )
	{
		spnRDD.innerHTML = "";
		spnRCD.innerHTML = "";
		return;
	}

	// Calculate the differences
	var RDDiff = parseFloat( spnRD2.innerHTML ) - parseInt( spnRD1.innerHTML );
	var RCDiff = parseFloat( spnRC2.innerHTML ) - parseInt( spnRC1.innerHTML );
	
	var prefix = "";
	var pct = 0;
	
	// Display the difference in diameter
	spnRDD.innerHTML = "";
	if ( RDDiff >= -1 && RDDiff <= 1 )
	{
		spnRDD.innerHTML = "nil";
	}
	else
	{
		prefix = RDDiff > 0 ? "+" : "";
		pct = RDDiff / parseFloat( spnRD2.innerHTML ) * 100;
		spnRDD.innerHTML = prefix + RDDiff.toFixed(2) + " mm, " + prefix + pct.toFixed(2) + "%";
	}
	
	// Display the difference in circumference
	spnRCD.innerHTML = "";
	if ( RCDiff >= -1 && RCDiff <= 1 )
	{
		spnRCD.innerHTML = "nil";
	}
	else
	{
		prefix = RCDiff > 0 ? "+" : "";
		pct = RCDiff / parseFloat( spnRC2.innerHTML ) * 100;
		spnRCD.innerHTML = prefix + RCDiff.toFixed(2) + " mm, " + prefix + pct.toFixed(2) + "%";
	}
}

// ---------------------------------------- //
// Calculates the speed for each gear ratio //
// ---------------------------------------- //
function CalculateGear(silent)
{
	// Get control references
    var ctrlCirc1 = document.getElementById("txtTyreCircumference1");
    var ctrlCirc2 = document.getElementById("txtTyreCircumference2");
    var ctrlFD1 = document.getElementById("ctl00_cphMain_txtFinalDrive1");
    var ctrlFD2 = document.getElementById("ctl00_cphMain_txtFinalDrive2");
	var ctrlKMH = document.getElementById( "rbnKMH" );
	var ctrlMPH = document.getElementById( "rbnMPH" );

	// Check the tyre circumference has been entered
	if ( !IsFloat( ctrlCirc1.value ) )
	{
		if ( !silent ) window.alert( "You must enter the tyre circumference as a number" );
		return;
	}

	// Check the final drive ratio has been entered
	if ( !IsFloat( ctrlFD1.value ) )
	{
		if ( !silent ) window.alert( "You must enter the final drive ratio as a number" );
		return;
	}
	
	// Determine if we're calculating for the second tyre
	var showNo2 = true;
	if ( !IsFloat( ctrlCirc2.value ) || !IsFloat( ctrlFD2.value ) ) showNo2 = false;
	
	// Clear the existing list of speeds
	ClearSpeeds();

	// Build the URL for the AJAX request
	var url = "?AjaxAction=calcgear&RatioList=" + GetDelimitedRatioList();
	url += "&Circumference1=" + ctrlCirc1.value;
	url += "&FinalDrive1=" + ctrlFD1.value;

	if ( ctrlKMH.checked )
		url += "&Unit=KMH";
	else if ( ctrlMPH.checked )
		url += "&Unit=MPH";
	else
		url += "&Unit=RPM";

	if ( showNo2 )
	{
		url += "&Circumference2=" + ctrlCirc2.value;
		url += "&FinalDrive2=" + ctrlFD2.value;
	}
	
	// Make the AJAX call
	request.GetNoCache( url, function(result)
	{
		if ( result.readyState != ReadyState.Complete )
		{
			return;
		}
			
		if ( result.status == HttpStatus.OK && result.responseText != "" )
		{
			// The result was successful and returned data
			var vals = result.responseText.split("||");
			
			// Populate the list of values for tyre #1
			DisplayResult( vals[0], 1 );
			
			if ( vals.length > 1 )
			{
				// Populate the list of values for tyre #2
				DisplayResult( vals[1], 2 );
				
				// Display the value differences
				DisplayResultDiff();
			}
		}
		else
		{
			// Handle the failure condition
			window.alert( "There was an unknown error" );
		}
	}
	)
}

// ------------------------------------------- //
// Displays the result list for the given tyre //
// ------------------------------------------- //
function DisplayResult(list, tyreNo)
{
	var ctrlRPM = document.getElementById( "rbnRPM" );
	if ( ctrlRPM.checked )
		PopulateRPMs( list, tyreNo );
	else
		PopulateSpeeds( list, tyreNo );
}

// ------------------------------------------------------------ //
// Displays a list of calculated engine RPMs for the given tyre //
// ------------------------------------------------------------ //
function PopulateRPMs(list, tyreNo)
{
	// Convert the delimited list to an array
	var vals = list.split("|");
	
	if ( vals.length < 2 )
	{
		// An error message has been returned
		window.alert( list );
	}
	else
	{
		// Loop through the array
		for ( var i=0; i<vals.length; i++ )
		{
			// Store the value in a hidden field
			var hdn = document.getElementById( "hdnGear" + tyreNo + "" + (i+1) );
			hdn.value = vals[i];
		}
		
		// Calculate the speeds if a valid RPM value has been entered
		//var txt = document.getElementById( "txtSpeed" );
		//if ( IsInt( txt.value ) ) 
		CalculateRPMs( tyreNo );
	}
}

// ------------------------------------------------------- //
// Displays a list of calculated speeds for the given tyre //
// ------------------------------------------------------- //
function PopulateSpeeds(list, tyreNo)
{
	// Convert the delimited list to an array
	var vals = list.split("|");
	
	if ( vals.length < 2 )
	{
		// An error message has been returned
		window.alert( list );
	}
	else
	{
		// Loop through the array
		for ( var i=0; i<vals.length; i++ )
		{
			// Store the value in a hidden field
			var hdn = document.getElementById( "hdnGear" + tyreNo + "" + (i+1) );
			hdn.value = vals[i];
		}
		
		// Calculate the speeds if a valid RPM value has been entered
		//var txt = document.getElementById( "txtRPM" );
		//if ( IsInt( txt.value ) )
		CalculateSpeeds( tyreNo );
	}
}

// --------------------------------------------- //
// Displays the result differences for each gear //
// --------------------------------------------- //
function DisplayResultDiff()
{
	// Loop through the list of gears
	for ( var i=1; i<=6; i++ )
	{
		// Get control references
		var spnGear1 = document.getElementById( "spnGear1" + i );
		var spnGear2 = document.getElementById( "spnGear2" + i );
		var spnDiff = document.getElementById( "spnGearDiff" + i );
		
		// Clear the existing value
		spnDiff.innerHTML = "";
		
		// Check a value exists for both tyres
		if ( spnGear1.innerHTML != "" && spnGear2.innerHTML != "" )
		{
			// Calculate and display the value difference
			var diff = parseFloat( spnGear2.innerHTML ) - parseFloat( spnGear1.innerHTML );
			if ( diff > 0 ) spnDiff.innerHTML = "+";
			spnDiff.innerHTML += diff.toFixed(2);
		}
	}
}

// ------------------------------------------------------------------ //
// Event handler - new value selected in the engine RPM dropdown list //
// ------------------------------------------------------------------ //
function RPMSelected()
{
	// Get control references
	var txt = document.getElementById( "txtRPM" );
	var ddl = document.getElementById( "ddlRPM" );
	
	// Set textbox value to dropdown value
	txt.value = ddl.value;
	
	// Reset dropdown selection
	ddl.selectedIndex = 0;
	
	// Re-calculate gear ratios
	CalculateGear( true );
}

// ------------------------------------------------------------------- //
// Calculates the speed for the given tyre and the selected engine RPM //
// ------------------------------------------------------------------- //
function CalculateSpeeds(tyreNo)
{
	// Check an RPM value has been entered
	var txt = document.getElementById( "txtRPM" );
	if ( !IsInt( txt.value ) )
	{
		window.alert( "You must enter the RPM as an integer" );
		return;
	}
	
	// Determine the multiplication factor
	var factor = parseFloat( txt.value ) / 1000;
	
	// Loop through the list of gears
	for ( var i=1; i<=6; i++ )
	{
		// Get control references
		var hdn = document.getElementById( "hdnGear" + tyreNo + "" + i );
		var spn = document.getElementById( "spnGear" + tyreNo + "" + i );
		
		// Calculate and display the speed for this gear ratio
		if ( hdn.value == null || hdn.value == "" || hdn.value == 0 )
		{
			spn.innerHTML = "";
		}
		else
		{
			spn.innerHTML = (parseFloat(hdn.value) * factor).toFixed(2);
		}
	}
}

// ------------------------------------------------------------------------ //
// Calculates the engine RPM for the given tyre and the selected road speed //
// ------------------------------------------------------------------------ //
function CalculateRPMs(tyreNo)
{
	// Check an RPM value has been entered
	var txt = document.getElementById( "txtSpeed" );
	if ( !IsInt( txt.value ) )
	{
		window.alert( "You must enter the road speed as an integer" );
		return;
	}
	
	// Determine the multiplication factor
	var factor = parseFloat( txt.value ) / 100;
	
	// Loop through the list of gears
	for ( var i=1; i<=6; i++ )
	{
		// Get control references
		var hdn = document.getElementById( "hdnGear" + tyreNo + "" + i );
		var spn = document.getElementById( "spnGear" + tyreNo + "" + i );
		
		// Calculate and display the speed for this gear ratio
		if ( hdn.value == null || hdn.value == "" || hdn.value == 0 )
		{
			spn.innerHTML = "";
		}
		else
		{
			spn.innerHTML = (parseFloat(hdn.value) * factor).toFixed(2);
		}
	}
}

// --------------------------------------- //
// Clears the list of speeds for each gear //
// --------------------------------------- //
function ClearSpeeds()
{
	// Loop through the tyres
	for ( var t=1; t<=2; t++ )
	{
		// Loop through the gears
		for ( var i=1; i<=6; i++ )
		{
			// Hidden field
			var hdn = document.getElementById( "hdnGear" + t + "" + i );
			hdn.value = "";
			
			// Calculated speed
			var spn = document.getElementById( "spnGear" + t + "" + i );
			spn.innerHTML = "";
			
			// Speed difference
			var diff = document.getElementById( "spnGearDiff" + i );
			diff.innerHTML = "";
		}
	}
}

// ------------------------------------------------------------------------------- //
// Displays a dynamically generated graph of calculated speeds for each gear ratio //
// ------------------------------------------------------------------------------- //
function DisplayGraph(url, tyreNo)
{
	// Get control references
	var ctrlRPM = document.getElementById( "txtRPM" );
	var ctrlSpeed = document.getElementById( "txtSpeed" );
	var ctrlCirc1 = document.getElementById( "txtTyreCircumference1" );
	var ctrlFD1 = document.getElementById("ctl00_cphMain_txtFinalDrive1");
	var ctrlCirc2 = document.getElementById( "txtTyreCircumference2" );
	var ctrlFD2 = document.getElementById("ctl00_cphMain_txtFinalDrive2");
	var ctrlKMH = document.getElementById( "rbnKMH" );
	var ctrlMPH = document.getElementById( "rbnMPH" );

	// Check format of user input
	if ( !IsInt( ctrlRPM.value ) )
	{
		window.alert( "You must enter the RPM as an integer" );
		return;
	}
	
	// Build the URL for the AJAX request
	url += "?RatioList=" + GetDelimitedRatioList();
	url += "&Redline=" + ctrlRPM.value;
	if ( ctrlMPH.checked )
	{
		url += "&Unit=MPH&XValStart=1000&XValEnd=" + ctrlRPM.value;
	}
	else if ( ctrlKMH.checked )
	{
		url += "&Unit=KMH&XValStart=1000&XValEnd=" + ctrlRPM.value;
	}
	else
	{
		if ( !IsInt( ctrlSpeed.value ) )
		{
			window.alert( "You must enter the road speed as an integer" );
			return;
		}
		url += "&Unit=RPM&XValStart=0&XValEnd=" + ctrlSpeed.value;
	}
	
	// Tyre #1
	if ( tyreNo == 0 || tyreNo == 1 )
	{
		// Check a valid circumference has been entered
		if ( !IsFloat( ctrlCirc1.value ) )
		{
			window.alert( "You must enter the tyre #1 circumference as a number" );
			return;
		}

		// Check a valid final drive ratio has been entered
		if ( !IsFloat( ctrlFD1.value ) )
		{
			window.alert( "You must enter the final drive ratio #1 as a number" );
			return;
		}
		
		// Append the values to the URL
		url += "&Circumference1=" + ctrlCirc1.value;
		url += "&FinalDrive1=" + ctrlFD1.value;
	}
	
	// Tyre #2
	if ( tyreNo == 0 || tyreNo == 2 )
	{
		// Check a valid circumference has been entered
		if ( !IsFloat( ctrlCirc2.value ) )
		{
			window.alert( "You must enter the tyre #2 circumference as a number" );
			return;
		}

		// Check a valid final drive ratio has been entered
		if ( !IsFloat( ctrlFD2.value ) )
		{
			window.alert( "You must enter the final drive ratio #2 as a number" );
			return;
		}
		
		// Append the values to the URL
		url += "&Circumference2=" + ctrlCirc2.value;
		url += "&FinalDrive2=" + ctrlFD2.value;
	}
	
	// Open a new window with the generated URL
	var features = "width=660,height=500,location=no,menubar=no,resizable=no,status=no,toolbar=no";
	var win = window.open( url, "GearingGraphWindow", features );
	win.focus();
}

// ------------------------------------------------------------------------------- //
// Displays a Silverlight generated graph of calculated speeds for each gear ratio //
// ------------------------------------------------------------------------------- //
function DisplayGraphSL(url)
{
    // Get control references
    var ctrlRPM = document.getElementById("txtRPM");
    var ctrlSpeed = document.getElementById("txtSpeed");
    var ctrlCirc1 = document.getElementById("txtTyreCircumference1");
    var ctrlFD1 = document.getElementById("ctl00_cphMain_txtFinalDrive1");
    var ctrlCirc2 = document.getElementById("txtTyreCircumference2");
    var ctrlFD2 = document.getElementById("ctl00_cphMain_txtFinalDrive2");
    var ctrlKMH = document.getElementById("rbnKMH");
    var ctrlMPH = document.getElementById("rbnMPH");
    var ctrlTrans = document.getElementById("ctl00_cphMain_ddlTransmissions");

    // Build the querystring
    if (ctrlMPH.checked)
    {
        url += "?type=Speed&uom=MPH";
    }
    else if (ctrlKMH.checked)
    {
        url += "?type=Speed&uom=KMH";
    }
    else
    {
        url += "?type=RPM&uom=KM%2FH";
    }
    
    url += "&maxrpm=" + ctrlRPM.value;
    url += "&maxspeed=" + ctrlSpeed.value;

    if (ctrlTrans.selectedIndex > 0) {
        url += "&transcode=" + ctrlTrans.options[ctrlTrans.selectedIndex].text;
    }

    // Tyre #1
    url += "&circ1=" + ctrlCirc1.value;
    url += "&fd1=" + ctrlFD1.value;

    // Tyre #2
    if (ctrlCirc2.value != "" && ctrlFD2.value != "")
    {
        url += "&circ2=" + ctrlCirc2.value;
        url += "&fd2=" + ctrlFD2.value;
    }
    
    var features = "width=800,height=500,location=no,menubar=no,resizable=no,status=no,toolbar=no";
	var win = window.open(url, "GearingGraphWindowSL", features);
	win.focus();
}

function DisplaySpeedo(url, tyreNo)
{
	// Get control references
    var ctrlCirc1 = document.getElementById("txtTyreCircumference1");
	var ctrlFD1 = document.getElementById("ctl00_cphMain_txtFinalDrive1");
	var ctrlCirc2 = document.getElementById("txtTyreCircumference2");
	var ctrlFD2 = document.getElementById("ctl00_cphMain_txtFinalDrive2");

	// Tyre #1
	if ( tyreNo == 1 )
	{
		// Check a valid circumference has been entered
		if ( !IsFloat( ctrlCirc1.value ) )
		{
			window.alert( "You must enter the tyre #1 circumference as a number" );
			return;
		}

		// Check a valid final drive ratio has been entered
		if ( !IsFloat( ctrlFD1.value ) )
		{
			window.alert( "You must enter the final drive ratio #1 as a number" );
			return;
		}
		
		// Append the values to the URL
		url += "?Circumference=" + ctrlCirc1.value;
		url += "&FinalDrive=" + ctrlFD1.value;
	}
	
	// Tyre #2
	if ( tyreNo == 2 )
	{
		// Check a valid circumference has been entered
		if ( !IsFloat( ctrlCirc2.value ) )
		{
			window.alert( "You must enter the tyre #2 circumference as a number" );
			return;
		}

		// Check a valid final drive ratio has been entered
		if ( !IsFloat( ctrlFD2.value ) )
		{
			window.alert( "You must enter the final drive ratio #2 as a number" );
			return;
		}
		
		// Append the values to the URL
		url += "?Circumference=" + ctrlCirc2.value;
		url += "&FinalDrive=" + ctrlFD2.value;
	}

	// Open a new window with the generated URL
	var features = "width=500,height=300,location=no,menubar=no,resizable=no,status=no,toolbar=no";
	var win = window.open( url, "_blank", features );
	win.focus();
}

// --------------------------------------------------------------- //
// Builds a delimited list of gear ratios from the ratio textboxes //
// --------------------------------------------------------------- //
function GetDelimitedRatioList()
{
	var ratioList = "";
	
	// Loop through the gears
	for ( var i=1; i<=6; i++ )
	{
		if ( ratioList != "" ) ratioList += "|";
		
		var txt = document.getElementById( "txtGear" + i );
		if ( txt.value == "" )
			ratioList += "0";
		else
			ratioList += txt.value;
	}
	
	return ratioList;
}

// --------------------------------------------------------- //
// Event handler - new Model selected from the dropdown list //
// --------------------------------------------------------- //
function ModelSelected()
{
	// Build the URL for the AJAX request
    var ctrlModel = document.getElementById("ctl00_cphMain_ddlModel");
	var url = "?AjaxAction=getchassis&ModelID=" + ctrlModel.value;

	// Make the AJAX call
	request.GetNoCache( url, function(result)
	{
		if ( result.readyState != ReadyState.Complete )
		{
			return;
		}
			
		if ( result.status == HttpStatus.OK && result.responseText != "" )
		{
			// The result was successful and returned data
			var list = result.responseText.split("|");
			
			if ( list.length < 2 )
			{
				// An error message was returned
				window.alert( result.responseText );
			}
			else
			{
				// Clear the Wheel dropdown list
				var ctrlWheel = document.getElementById( "ddlWheel" );
				for ( var o=ctrlWheel.options.length; o>=0; o-- )
				{
					ctrlWheel.options[o] = null;
				}
				ctrlWheel.options.add( new Option( "[none]", "0" ) );

				// Clear the Chassis dropdown list
				var ctrlChassis = document.getElementById( "ddlChassis" );
				for ( var o=ctrlChassis.options.length; o>=0; o-- )
				{
					ctrlChassis.options[o] = null;
				}

				// Populate the Chassis dropdown list with the returned values
				for ( var i=0; i<list.length; i+=2 )
				{
					ctrlChassis.options[ctrlChassis.options.length] = new Option( list[i+1], list[i] );
				}
			}
		}
		else
		{
			// Handle the failure condition
			window.alert( "There was an unknown error" );
		}
	}
	)
}

// ----------------------------------------------------------- //
// Event handler - new Chassis selected from the dropdown list //
// ----------------------------------------------------------- //
function ChassisSelected()
{
	// Build the URL for the AJAX request
	var ctrlChassis = document.getElementById( "ddlChassis" );
	var url = "?AjaxAction=getwheels&ChassisID=" + ctrlChassis.value;

	// Make the AJAX call
	request.GetNoCache( url, function(result)
	{
		if ( result.readyState != ReadyState.Complete )
		{
			return;
		}
			
		if ( result.status == HttpStatus.OK && result.responseText != "" )
		{
			// The result was successful and returned data
			var list = result.responseText.split("|");
			
			if ( list.length < 2 )
			{
				// An error message was returned
				window.alert( result.responseText );
			}
			else
			{
				// Clear the Wheel dropdown list
				var ctrlWheel = document.getElementById( "ddlWheel" );
				for ( var o=ctrlWheel.options.length; o>=0; o-- )
				{
					ctrlWheel.options[o] = null;
				}

				// Populate the Wheel dropdown list with the returned values
				for ( var i=0; i<list.length; i+=2 )
				{
					ctrlWheel.options[ctrlWheel.options.length] = new Option( list[i+1], list[i] );
				}
			}
		}
		else
		{
			// Handle the failure condition
			window.alert( "There was an unknown error" );
		}
	}
	)
}

// --------------------------------------------------------- //
// Event handler - new Wheel selected from the dropdown list //
// --------------------------------------------------------- //
function WheelSelected()
{
	// Check the current value is in the expected form (WWWPPPDDD)
	var ctrlWheel = document.getElementById( "ddlWheel" );
	if ( ctrlWheel.value.length != 9 )
	{
		window.alert( "There was an error: " + ctrlWheel.value );
		return;
	}
	
	// Split the selected value into Width, Profile and Diameter values
	var tw = StripLeadingZero( ctrlWheel.value.substring( 0,3 ) );
	var tp = StripLeadingZero( ctrlWheel.value.substring( 3,6 ) );
	var rd = StripLeadingZero( ctrlWheel.value.substring( 6,9 ) );
	
	// Get control references
	var ctrlTW = document.getElementById("ctl00_cphMain_ddlTyreWidth1");
	var ctrlTP = document.getElementById("ctl00_cphMain_ddlTyreProfile1");
	var ctrlRD = document.getElementById("ctl00_cphMain_ddlRimDiameter1");
	
	// Populate the controls with the selected values
	ctrlTW.value = tw;
	ctrlTP.value = tp;
	ctrlRD.value = rd;
	
	// Re-calculate wheel dimensions
	CalculateWheel(1);
}

// ----------------------------------------------- //
// Strips leading zeroes from the specified string //
// ----------------------------------------------- //
function StripLeadingZero(str)
{
	var result = "";
	var leading = true;
	
	for ( var i=0; i<str.length; i++ )
	{
		var chr = str.substring( i, i+1 );
		if ( !leading || chr != "0" ) 
		{
			leading = false;
			result += chr;
		}
	}
	
	return result;
}

// ------------------------------------------------------------------------ //
// Re-calculates the speeds when a different unit is selected (km/h or MPH) //
// ------------------------------------------------------------------------ //
function UnitSelected()
{
	var ctrlKMH = document.getElementById( "rbnKMH" );
	var ctrlMPH = document.getElementById( "rbnMPH" );
	
	// Change the column headings
	for ( var i=1; i<=3; i++ )
	{
		var ctrlLabel = document.getElementById( "spnUnit" + i );
		if ( ctrlKMH.checked )
		{
			ctrlLabel.innerText = "km/h";
		}
		else if ( ctrlMPH.checked )
		{
			ctrlLabel.innerText = "MPH";
		}
		else
		{
			ctrlLabel.innerText = "RPM";
		}
	}
	
	// Re-calculate the speeds
	CalculateGear( true );
}
