$(function() {

	function isUS() {
		return $("select#country option:selected").val() == "US";
	}

	$("#storeform").validate({
		rules: {
			cc_number: {
				required: true,
				maxlength: 16,
				minlength: 14,
				digits: true
			},
			cc_cvv: {
				required: true,
				maxlength: 4,
				minlength: 3,
				digits: true
			},
			state: {
				required: { depends: isUS }
			}
		}
	});

	var updatePrices = function() {
		var idBase = $("input.updatePrice:checked").attr("id") ? $("input.updatePrice:checked").attr("id") :
			$("input.updatePrice").attr("id"),
			priceStr = $("input#" + idBase + "_total").val(),
			isMonthly = priceStr.indexOf("month") >= 0,
			price = parseFloat(priceStr.substring(1, priceStr.indexOf(" "))),
			term = parseInt($("#payment_term").val()),
			totalStr = (term == 1 || isMonthly) ? priceStr :
				"$" + (price * term) + ".00 (" + priceStr + " for " + term + " years)";
		$("#payment_term_wrapper").toggle(!isMonthly);
		if (isMonthly) {
			$("#payment_term").val("1");
		}
		$("#peryearprice").text(priceStr);
		$("#totalprice").text(totalStr);
		$("ul.price_description").hide();
		$("ul." + idBase + "_description").show();
	};

	// bind onclick only if the input is defined
	if ($("input.updatePrice:checked").attr("id")) {
		$("input.updatePrice").click(updatePrices);
	}

	$("#payment_term").change(updatePrices);


	$("#agreement").dialog({width:800,height:400,modal:true,autoOpen:false,resizable:false,draggable:false,bgiframe:true});
	$("#viewAgreement").click(function() {
		$("#agreement").dialog("open");
		return false;
	});

	$("#viewPrivacPAAgreement").dialog({width:800,height:400,modal:true,autoOpen:false,resizable:false,draggable:false,bgiframe:true});
	$("#viewPrivacyPA").click(function() {
		$("#viewPrivacPAAgreement").dialog("open");
		return false;
	});

});

