// JavaScript Document
var reps = [0, 1, .95, .93, .90, .87, .85, .83, .8, .77, .75, .7, .67, .65, .6, .55];
var wholenumber = /^[0-9]+$/;
var number = /^[0-9]{0,3}\.?[0-9]*$/;

$(document).ready( function(){	
	$("input[name='reps']").change(function() {
		if (okay()) {
			fillchart();
		} else {
			emptychart();
		}
	});
	
	$("input[name='lift']").change(function() {
		if (okay()) {
			fillchart();
		} else {
			emptychart();	
		}
	});
	
	$("input[name='weight']").change(function() {
		//this value is okay
		if ($(this).val() != "" & number.test($("input[name='weight']").val())) {
			//the calculating fields are all okay
			if (okay()) {
				var numreps = 	$("input[name='reps']").val();
				var lift =  $("input[name='lift']").val();
				var weight = $("input[name='weight']").val();
				
				var onerepmax = lift / reps[numreps];
				
				$("#strength").text(Math.round(onerepmax/weight*100));
			} else {
				//clear calculated field
				$("#strength").html("&nbsp;");
			}
		} else {
			//clear field and the calculated field
			$("input[name='weight']").val("");
			$("#strength").html("&nbsp;");
		}
	});
});

function okay() {
	var okay = true;
	if (!wholenumber.test($("input[name='reps']").val()) | $("input[name='reps']").val() == "") {
		$("input[name='reps']").val("");
		okay = false;
	}
	if (!wholenumber.test($("input[name='lift']").val()) | $("input[name='lift']").val() == "") {
		$("input[name='lift']").val("");
		okay = false;
	} 
	if ($("input[name='reps']").val() > 15 | $("input[name='reps']").val() < 1  | $("input[name='reps']").val() == "") {
		$("input[name='reps']").val("");
		okay = false;
	}
	//check for age and sex and upload information
	return okay;
}

function fillchart() {
	var numreps = 	$("input[name='reps']").val();
	var lift =  $("input[name='lift']").val();
	
	var onerepmax = lift / reps[numreps];
	
	$("#onerepmax").text(Math.round(onerepmax));
	if (numreps < 16 & numreps > 0) {
		$("table td.recommended span").each(function () {
			var percent = $(this).parent().prev().html() / 100;
			var weight = Math.round(percent * onerepmax);
			$(this).html(weight);
		});
	}
	
	if ($("input[name='weight']").val() != "") {
		var weight = $("input[name='weight']").val();
		$("#strength").text(Math.round(onerepmax/weight*100));
	}
}

function emptychart() {
	$("table td.recommended span").each(function () {
		$(this).html("&nbsp;");
	});
	$("#onerepmax").html("&nbsp;");
	$("#strength").html("&nbsp;");
}
