$(document).ready(function() {
	// enable hidden elements
	$(".script-enable").css("display","block");
	$(".script-disable").css("display","none");
	// toggle sub_type_selected switch to ensure a sub type is actually picked (instead of using the defaults)
	$("#id_sub_type_selected").remove();
	$("#id_territory option[@value=3]").attr("selected","True");
	// turn table cells into buttons
	$("#pp-subtype table tr td").each(function() {
		id = $(this).children("span").attr("id");
		price = $(this).children("span").text();
		$(this).empty().append('<button id="' + id + '" type="button" onclick="document.myform.formVar.value=\'' + price + '\'; return false">' + price + '</button>');
		$(this).css("padding","0");
	});
	// display correct table depending on which term is selected
	$("#pp-subtype table").css("display","none");
	$("#pp-subtype table#prices-" + $("#id_years").val() + "year").css("display","block");
	// onclick handler: set proper price and form fields when button is clicked
	$("#pp-subtype table tr td button").bind("click", function() {
		// turn on sub_type_selected
		$("#id_years").after('<input type="hidden" id="id_sub_type_selected" name="sub_type_selected" value="on"/>');
		// select proper choices on hidden form fields
		id = $(this).attr("id");
		re_params = /r(\d+)_t(\d+)/i;
		matches_params = id.match(re_params);
		$("#id_recipient_type option[@selected]").removeAttr("selected");
		$("#id_territory option[@selected]").removeAttr("selected");
		$("#id_recipient_type option[@value=" + matches_params[1] + "]").attr("selected","True");
		$("#id_territory option[@value=" + matches_params[2] + "]").attr("selected","True");
		// light up correct button
		$("#pp-subtype table tr td button").removeClass("pp-sub-typeselect");
		$(this).addClass("pp-sub-typeselect");
		// set the correct price
		price = $(this).text();
		re_price = /([\d\.]+)/i;
		matches_price = price.match(re_price);
		$("#pp-finalcost").text("$" + matches_price[1] + " CAD");
	});
});