$(document).ready(function(){
	$("#bmi-result").hide();
	$('#height2').hide();
	$('#weight2').hide();

	$('#imperial-height').click(function(){
		$('#height2').hide();
		$('#height1').show();
		$.post("includes/to_metric.php",{
			value: $("#cms").val(),
			action: "height-metric"
		}, function(xml) {
			feet = parseInt($("height",xml).text() / 12);
			inches = parseInt($("height",xml).text() - (feet * 12));
			if (feet > 0)
				$("#feet").val(feet);
			if (inches > 0)
				$("#inches").val(inches);
		});
	});
	$('#metric-height').click(function(){
		$('#height1').hide();
		$('#height2').show();
		$.post("includes/to_metric.php",{
			value: parseInt($("#feet").val() * 12) + parseInt($("#inches").val()),
			action: "height-imperial"
		}, function(xml) {
			if ($("height",xml).text() > 0)
				$("#cms").val($("height",xml).text());
		});
	});

	$('#imperial-weight').click(function(){
		$('#weight2').hide();
		$('#weight1').show();
		$.post("includes/to_metric.php",{
			value: $("#kgs").val(),
			action: "weight-metric"
		}, function(xml) {
			stone = parseInt($("weight",xml).text() / 14);
			pounds = parseInt($("weight",xml).text() - (stone * 14));
			if (stone > 0)
				$("#stone").val(stone);
			if (pounds > 0)
				$("#pounds").val(pounds);
		});
	});
	$('#metric-weight').click(function(){
		$('#weight1').hide();
		$('#weight2').show();
		$.post("includes/to_metric.php",{
			value: parseInt($("#stone").val() * 14) + parseInt($("#pounds").val()),
			action: "weight-imperial"
		}, function(xml) {
			if ($("weight",xml).text() > 0)
				$("#kgs").val($("weight",xml).text());
		});
	});
	
	$("form#bmi-form").submit(function(){
		$.post("includes/bmi_calculation.php",{
			heightm: $("#cms").val(),
			weightm: $("#kgs").val(),
			heighti: parseInt($("#feet").val() * 12) + parseInt($("#inches").val()),
			weighti: parseInt($("#stone").val() * 14) + parseInt($("#pounds").val())
		}, function(xml) {
			$("#form-fields").hide();
			$("#bmi-result").show();
			$("#bmi-value").text($("bmi",xml).text());
		});
		return false;
	});

	$("#bmi-button2").click(function(){
		$("#form-fields").show();
		$("#bmi-result").hide();
	});
});