//Make sure the terms/conditions checkbox is checked. Otherwise, don't let the user 
//submit the form.
function check_terms_selectbox(jqueryFormObj) {
	
	var checked = jqueryFormObj.find("input[name=agree]").attr("checked");
	
	//If the checkbox was checked, allow the form to be submitted.
	if (checked) {
		return true;
	
	//Otherwise, display an error message and do not submit the form.
	} else {
		alert("Please read the Terms & Conditions and agree to them.");
		return false;
	}
	
}

var interval = null;

//Toggle 3-D Secure content.
function toggle3DSecure() {
	
	//If the post-auth content is displayed, that means the auth is complete.
	var postAuthContent = $("iframe#paypal-wpp-3ds").contents().find("#secure3d-postauth").html();
	if (postAuthContent) {	
		clearInterval(interval);
		
		//Remove the iframe.
		$("iframe#paypal-wpp-3ds").remove();
		
		//Replace the pre-auth content with the post-auth contents.
		$("div#secure3d-preauth").replaceWith(postAuthContent);
		
		
	//If the post-auth content is not displayed, that means the auth is not complete.
	} else {
		
	}
}

//Paypal express checkout and paypal direct payments need different fields.
//Toggle between the fields.
$(document).ready(function() {
	
	if ($("#paypal-wpp-3ds").length) {
		toggle3DSecure();
		$("#secure3d-auth-btn").click( function() {
			
			//Remove the button so it can only be clicked once.
			$(this).attr("disabled", "disabled");
			
			//Check every so often to see if the transaction is authorized.
			interval = setInterval(function() {
				toggle3DSecure();
			}, 500);
		});
	}

	//Only proceed if we are on the checkout patment page.
	if ($("div#payment-fields").length > 0) {
		
		//Only proceed if the paypal_wpp payment module is installed.
		if ($("input[value='paypal_wpp']").length > 0) {
			
			//Select the paypal_wpp radio button by default, if it exists.
			$("input[value='paypal_wpp']").attr("checked", true); 
		
			togglePaymentFields();
			$("input[name='payment']").change( function() {
				togglePaymentFields();
			});
		}
	}
	
	function togglePaymentFields() {
		
		//When the PayPal Direct Payment radio button is selected,
		//show the fields for this payment type.
		if ($("input[name='payment']:checked").val() == "paypal_wpp") {
			$("div#payment-fields").css("display", "block");
			
		//When any other radio button is selected,
		//hide the PayPal Direct Payment fields.
		} else {
			$("div#payment-fields").css("display", "none");
		}
	}
	
});