<?php 
	$gc_page = $_REQUEST['mode'] == 'gift_card' ? 1 : 0;
	$payment_page = $_REQUEST['mode'] == 'page_book' ? 1 : 0;
?>
	
	<input type="hidden" name="tour_card_token" id="tour_card_token" value="" />
	<input type="hidden" name="payment_id" id="payment_id" value="" />

	<script>
		var form_symbol = '$';
		var form_decimals = '2';
		var form_separator = ',';

		// MONEY FORMATTING
		const currency = '<?php echo $company->currency_symbol; ?>';

		Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
			var n = this,
			decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? form_decimals : decPlaces,
			decSeparator = decSeparator == undefined ? "." : decSeparator,
			thouSeparator = thouSeparator == undefined ? form_separator : thouSeparator,
			sign = n < 0 ? "-" : "",
			i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
			j = (j = i.length) > 3 ? j % 3 : 0;

			var dec;
			var out = sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator);
			if(decPlaces) dec = Math.abs(n - i).toFixed(decPlaces).slice(2);
			if(dec) out += decSeparator + dec;
			return out;
		};
		jQuery(document).ready(function() {
			jQuery('#tour_card_token').val('');
		});
	</script>

	<div class="form-group" id="payment_methods">
		<?php
		$card_fa_logos = array(
			'visa' => 'fa-cc-visa',
			'mastercard' => 'fa-cc-mastercard',
			'american express' => 'fa-cc-amex',
			'discover' => 'fa-cc-discover'
		);
		$pmc = 1; // payment method counter 1

		foreach ($site->getPaymentMethods() as $pay) {
			if ($pay['name'] == 'Credit Cards') {
				$set_name = $pay['name'];
		?>

				<div class="rezgo-input-radio">
					<input type="radio" name="payment_method" id="payment_method_credit" class="rezgo-payment-method required" value="Credit Cards">

					<label for="payment_method_credit" class="payment-label">

						<div id="icon-container" class="icon-container">
							<?php foreach ($site->getPaymentCards() as $card) { ?>
								<i class="fab <?php echo esc_attr($card_fa_logos[$card]); ?>"></i>
							<?php } ?>
						</div>

					</label>
				</div>

			<?php
			} else if ($pay['name'] == 'PayPal Checkout') {
			?>

				<div class="rezgo-input-radio" id="paypal-url">
					<input type="radio" name="payment_method" id="payment_method_<?php echo esc_attr($pmc); ?>" class="rezgo-payment-method required" value="<?php echo $pay['name']; ?>" />
					<label class="non-cc-method" for="payment_method_<?php echo esc_attr($pmc); ?>"><img src="<?php echo $site->path; ?>/img/logos/paypal.png" style="height:25px; width:auto;"></label>
				</div>

			<?php
			} else if ($payment_page) {

				$set_name = $pay['name']; ?>
				<div class="rezgo-input-radio">
					<input type="radio" name="payment_method" id="payment_method_<?php echo esc_attr($pmc); ?>" class="rezgo-payment-method required" value="<?php echo $pay['name']; ?>" />
					<label class="non-cc-method" for="payment_method_<?php echo esc_attr($pmc); ?>"><?php echo $set_name; ?></label>
				</div>

		<?php

			}

			$pmc++;
		} // end foreach($site->getPaymentMethods()
		?>

		<!-- show only when payment is not required -->
		<div class="rezgo-input-radio no-payment" style="display:none;">
			<input type="radio" name="payment_method" id="no_payment_required" class="rezgo-payment-method required" value="None">

			<label for="no_payment_required">No payment required</label>
		</div>

	</div><!-- // #payment_methods -->

	<div id="payment_data">

		<?php $pmdc = 1; // payment method counter 1 
		?>

		<script>
			// create stripe initial error state because we use this to validate the form
			var stripe_error = 0;
		</script>

		<?php foreach ($site->getPaymentMethods() as $pay) { ?>
	
			<?php if ($pay['name'] == 'Credit Cards') { ?>

				<!-- TIPS -->
				<?php
				if ($tips_enabled) {
					require 'tips.php';
				}
				?>

				<!-- TICKET GUARDIAN -->
				<?php if ($payment_page) { ?>

					<script>
						//tg item prices for quote
						tg_booking_prices = split_total.slice(0);

						let tg_loading = 0;
						let tg_initial_load = 0;

						// filter out empty elements
						let tg_items = [];
						for (let i = 0; i < tg_booking_prices.length; i++) {
							if (tg_booking_prices[i]) {
								tg_items.push(tg_booking_prices[i]);
							}
						}

						function configureTg() {
							tg_loading = 1;
							tg('configure', {
								apiKey: '<?php echo REZGO_TICKGUARDIAN_PK; ?>',
								currency: '<?php echo $tg_display_currency; ?>',
								costsOfItems: tg_items,
								<?php if (REZGO_TICKGUARDIAN_TEST) { ?>
									sandbox: true,
								<?php } ?>
								loadedCb: function() {
									tg_loading = 0;
									tg_initial_load = 1;
									// console.log('update callback');
								},
								optInCb: function() {
									var quoteToken = tg.get("token");
									// console.log('opted in callback');
									jQuery("#tour_tg_insurance_coverage").val(quoteToken);
									jQuery('#tour_tg_insurance_coverage').attr('disabled', false);
								},
								optOutCb: function() {
									var quoteToken = tg.get("token");
									// console.log('opted out callback');
									jQuery("#tour_tg_insurance_coverage").val('');
									jQuery('#tour_tg_insurance_coverage').attr('disabled', true);
								},
								onErrorCb: function(object) {
									console.log(object);
								}
							});
						}
					</script>

					<div id="tg-wrapper" style="display:none;">
						<br>
						<div id="tg-placeholder"></div>
						<div class="tg-disabled-overlay" style="display:none;"></div>
						<div id="tg_error" class="tg-error msg error" style="display:none">
							<i class="fa fa-times" aria-hidden="true"></i>
							<span>You must accept or decline refund protection.</span>
						</div>
						<br>
						<br>
					</div>

					<input type="hidden" name="tour_tg_insurance_coverage" id="tour_tg_insurance_coverage">

					<div id="tg-no-longer-avail" style="display:none;">
						<span><i class="far fa-exclamation-circle"></i> &nbsp; Refund Protection is only available with Credit Card payment</span>
						<hr>
					</div>

				<?php } // if ($payment_page)
				?>

				<div id="payment_cards" class="payment_method_container" style="display:none;">
					<h4 class="payment-method-header">Credit Card Details</h4>

					<?php if (!$billing_address && $billing_country_required) { ?>
						<div class="form-group country-required-form-group">
							<div class="rezgo-form-row">
								<div class="col-12 rezgo-form-input">
									<label for="tour_country" class="control-label rezgo-form-label">Country</label>
									<select class="form-select required" name="tour_country" id="tour_country">
										<option value=""></option>
										<?php foreach ($site->getRegionList() as $iso => $name) { ?>
											<option value="<?php echo esc_attr($iso); ?>" <?php echo (($iso == $companyCountry) ? 'selected' : ''); ?>><?php echo ucwords(esc_html($name)); ?></option>
										<?php } ?>
									</select>
								</div>
							</div>
						</div>
					<?php } ?>

					<?php if ($gateway_id == 'stripe_connect') { ?>

						<!-- Stripe Elements -->
						<script src="https://js.stripe.com/v3/"></script>
						<style>
							/* From - https://stripe.com/docs/stripe-js */
							.StripeElement {
								box-sizing: border-box;
								height: 34px;
								padding: 8px 12px;
								border: 1px solid #CCC;
								border-radius: 4px;
								background-color: white;
								box-shadow: none;
								-webkit-transition: box-shadow 150ms ease;
								transition: box-shadow 150ms ease;
							}

							.StripeElement--focus {
								border-color: #66afe9;
								outline: 0;
								-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, .6);
								box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, .6);
							}

							.StripeElement--invalid {
								border-color: #fa755a;
							}

							.StripeElement--webkit-autofill {
								background-color: #fefde5 !important;
							}

							#stripe_cardholder_name {
								height: 34px;
							}

							#stripe_cardholder_name::placeholder {
								opacity: 1;
								color: #aab7c4;
								-webkit-font-smoothing: antialiased;
							}

							#stripe_cardholder_name_error {
								padding: 0 0 5px 0;
							}

							#stripe_cardholder_name,
							#card-element {
								font-family: 'Helvetica Neue', sans-serif;
								max-width: 400px;
							}

							.stripe-payment-title {
								font-size: 16px;
							}

							#card-element {
								margin-top: 5px;
							}

							#card-errors {
								padding: 5px 0;
								color: var(--error-color);
								font-size: 14px;
							}

							@media screen and (max-width: 650px) {
								#secureFrame {
									width: 100%;
									height: 400px;
								}
							}

							@media screen and (max-width: 500px) {

								#stripe_cardholder_name,
								#card-element {
									font-size: 13px;
									max-width: 350px;
								}
							}
						</style>
						<div class="form-row">

							<input id="stripe_cardholder_name" class="StripeElement form-control" name="stripe_cardholder_name" placeholder="Name on Card">
							<span id="stripe_cardholder_name_error" class="payment_method_error">Please enter the cardholder's name</span>

							<div id="card-element">
								<!-- Stripe Element will be inserted here. -->
							</div>

							<!-- Apple Pay  -->
							<div id="payment-request-button">
								<!-- A Stripe Element will be inserted here. -->
							</div>

							<!-- Used to display form errors. -->
							<div id="card-errors" role="alert"></div>

							<input type="hidden" name="client_secret" id="client_secret" value="" />

						</div>

						<script>

							var clientSecret = '';
							var paymentId = '';

							// Create a Stripe client.
							let stripe = Stripe('<?php echo $company->stripe_public_key; ?>', {stripeAccount: '<?php echo $company->public_gateway_token; ?>'});

							// Create an instance of Elements.
							var style = {
								base: {
									color: '#32325d',
									fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
									fontSmoothing: 'antialiased',
									fontSize: '14px',
									'::placeholder': {
										color: '#aab7c4'
									}
								},
								invalid: {
									color: '#a94442',
									iconColor: '#a94442'
								}
							};

							var cardHolder = jQuery('#stripe_cardholder_name');
							var cardInput = document.getElementById('card-element');

							var elements = stripe.elements();

							var card = elements.create('card', {
								style: style,
								hidePostalCode: true,
								disableLink: true,
							});

							// Add an instance of the card Element into the #card-element div.
							card.mount('#card-element');

							var displayError = document.getElementById('card-errors');

							// create stripe error state to handle form error submission
							stripe_error = 1;

							// Handle real-time validation errors from the card Element.
							card.addEventListener('change', function(event) {

								if (event.error) {
									displayError.textContent = event.error.message;
									stripe_error = 1;
									cardInput.style.borderColor = '#a94442';
								} else if (event.empty) {
									displayError.textContent = 'Please enter your Credit Card details';
									stripe_error = 1;
								} else {
									displayError.textContent = '';
									stripe_error = 0;
									cardInput.style.borderColor = '#ccc';
								}
							});

							cardHolder.change(function () {
								if (jQuery(this).val() == '') {
									jQuery('#stripe_cardholder_name_error').show();
									jQuery(this).css({'borderColor': '#a94442'});
									stripe_error = 1;
								} else {
									jQuery('#stripe_cardholder_name_error').hide();
									jQuery(this).css({'borderColor': '#ccc'});
									stripe_error = 0;
								}
							});
						</script>

					<?php } elseif ($gateway_id == 'tmt') { ?>

						<h4 class="payment-method-header">You will be asked for your credit card details when completing your booking</h4>

						<script src="https://payment.tmtprotects.com/tmt-payment-modal.3.6.1.js"></script>
						
					<?php } elseif ($gateway_id == 'square') { ?>

						<script type="text/javascript" src="https://<?php echo DEBUG_STATE_SQUARE === 1 ? 'sandbox.' : '' ?>web.squarecdn.com/v1/square.js"></script>

						<div class="form-row rezgo-booking-payment-body">
							<input id="square_cardholder_name" class="form-control SquareElement" name="square_cardholder_name" placeholder="Name on Card">
							<span id="square_cardholder_name_error" class="payment_method_error">Please enter the cardholder's name</span>

							<div id="card-element">
								<!-- Stripe Element will be inserted here. -->
							</div>
							<!-- Apple Pay  -->
							<div id="payment-request-button">
								<!-- A Stripe Element will be inserted here. -->
							</div>

							<!-- Used to display form errors. -->
							<div id="card-errors" role="alert"></div>

							<input type="hidden" name="client_secret" id="client_secret" value="" />

						</div>
						
						<style>
							/* From - https://stripe.com/docs/stripe-js */

							.rezgo-booking-payment-body {
								padding: 0 0 8px 0;
							}

							#square_cardholder_name {
								height: 48px;
								border-radius: 6px;
							}

							#square_cardholder_name:focus {
								border: 2px solid #00f;
								outline: none !important;
								box-shadow: none;
								-moz-box-shadow: none;
								-webkit-box-shadow: none;
							}


							#square_cardholder_name::placeholder {
								opacity: 1;
								color: #aab7c4;
								font-weight: 400;
							}

							#square_cardholder_name_error {
								padding: 0 0 5px 0;
							}

							#square_cardholder_name,
							#card-element {
								font-family: 'Helvetica Neue', sans-serif;
								max-width: 400px;
							}

							.square-payment-title {
								font-size: 16px;
							}

							#card-element {
								margin-top: 5px;
							}

							#card-errors {
								padding: 5px 0;
								color: var(--error-color);
								font-size: 14px;
							}

							.sq-card-message {
								display: none;
							}
                            .square_threeds_iframe {
                            top: auto !important;
                            bottom: 0 !important;
                            }

							@media screen and (max-width: 650px) {
								#secureFrame {
									width: 100%;
									height: 400px;
								}
							}

							@media screen and (max-width: 500px) {

								#square_cardholder_name,
								#card-element {
									font-size: 14px;
									width: 248px;
									max-width: 270px;
								}
							}
						</style>

						<script>
                            // console.log(overall_total);
							// let order_total = $("#expected").val() * 1;
							var cardHolder = jQuery('#square_cardholder_name');
							var cardInput = document.getElementById('card-element');
							var card;
							var square_error = 1;
							var square_invalid_error = 0;
							var app_id;
                            var location_id = "<?php echo DEBUG_STATE_SQUARE === 1 ? 'LFGY97FK51926' : 'LT4MS5Z8V99YC'; ?>";
							var ajax_success = false;

							function createSquareCard() {

								jQuery.ajax({
									url: '<?php echo admin_url('admin-ajax.php'); ?>' + '?action=rezgo&method=gateways_square&amount=' + overall_total + '&currency=<?php echo $currency_base; ?>',
									context: document.body,
									dataType: "json",
									data: {
										rezgoAction: 'square_card_init'
									},
									success: function (data) {
										app_id = data.app_id;
                                        location_id = data.location_id ? data.location_id : location_id;

										// Set the flag to true indicating AJAX call success
										ajax_success = true;
										addSquareContents();                                          
									}
								});

							}
							
							/************ Styles for Square Element **************/
							const style = {
								'.input-container.is-focus': {
									borderColor: '#006AFF',
								},
								'.input-container.is-error': {
									borderColor: 'rgb(169, 68, 66)',
								},
								input: {
									fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
									fontSize: '14px',
								},
								'input::placeholder': {
									color: '#808d9d',
								},
								'input.is-error': {
									color: 'rgb(169, 68, 66)',
								},

								'@media screen and (max-width: 500px)': {
									'input': {
										'fontSize': '14px',
									}
								}
							};

							/************ create square error state to handle form error submission *************/

							function displayErrors(error_message) {
								const error_div = document.getElementById('card-errors');
								error_div.textContent = error_message;
								error_div.style.visibility = 'visible';
								square_error = 1;
							}

							function clearPreviousError() {
								const error_div = document.getElementById('card-errors');
								error_div.textContent = '';
								error_div.style.visibility = 'hidden';
								square_invalid_error = 1;
								jQuery("#card-element").css('border', 'none');
							}

							/*************** Initialize square payment card ***************/
							function initializeCard(payments) {
								return payments.card({
									style: style
								}).then((card) => {

									return card.attach('#card-element').then(() => card);
								});
							}

							createSquareCard();

							/*************** Square payment card Init process ***************/
							document.addEventListener('DOMContentLoaded', function () {
								if (ajax_success) {
									addSquareContents();
								}
							});

							function addSquareContents() {
								let payments;

								if (!window.Square) {
									throw new Error('Square.js failed to load properly');
								}

								payments = window.Square.payments(app_id, location_id);

								initializeCard(payments).then((initializedCard) => {
									card = initializedCard;

									/************* Add event listener for error class added **************/
									card.addEventListener('errorClassAdded', (event) => {
										clearPreviousError();
										const errorMessage = jQuery('.sq-card-message.sq-visible').text();
										displayErrors(errorMessage);
										square_invalid_error = 1;
										square_error = 1;

									});

									card.addEventListener('focus', (event) => {
										jQuery("#card-element").css('border', 'none');  
									});

									/************* Add event listener for focus class removed **************/
									card.addEventListener('focusClassRemoved', (event) => {
										/*********  Clear any previous error messages *********/
										clearPreviousError();
										/********  Check for empty fields ********/
										if (event.detail.previousState.isEmpty) {
											displayErrors('Please fill out all required fields.');
											square_error = 1;
										} else {
											/************ Clear any previous error messages only if no square errors ***********/
											if (!event.detail.previousState.hasErrorClass) {
												clearPreviousError();
												square_error = 0;
											}
										}

									});

								}).catch((error) => {
									console.error('Initializing Card failed', error);
								});
							}

							cardHolder.change(function () {
								if (jQuery(this).val() == '') {
									jQuery('#square_cardholder_name_error').show();
									jQuery(this).css("border-color", "#a94442");
									square_error = 1;
								} else {
									jQuery('#square_cardholder_name_error').hide();
									jQuery(this).css("border-color", "#ccc");
									square_error = 0;
								}
							});
						</script>

					<?php } else { ?>

						<?php if (REZGO_WORDPRESS) { ?>
							<iframe scrolling="no" frameborder="0" name="tour_payment" id="tour_payment" src="<?php echo home_url(); ?>?rezgo=1&mode=booking_payment"></iframe>

						<?php } else { ?>
							
							<iframe scrolling="no" frameborder="0" name="tour_payment" id="tour_payment" src="<?php echo $site->base; ?>/booking_payment.php"></iframe>
						<?php } ?>

						<script type="text/javascript">
							iFrameResize({
								enablePublicMethods: true,
								scrolling: false
							}, '#tour_payment');
						</script>

					<?php } ?>

				</div> <!-- div payment_cards -->

			<?php } elseif ($pay['name'] == 'PayPal Checkout') { ?>

				<div id="payment_method_<?php echo $pmdc; ?>_box" class="payment_method_box" style="display:none;">

					<div id="payment_method_<?php echo $pmdc; ?>_container" class="payment_method_container">
						<h4 class="payment-method-header" id="paypal-button-header">Click to pay with PayPal</h4>
						<div id="paypal-button-container" style="max-width: 400px; margin-top:20px;"></div>

						<span id="paypal_error" class="payment_method_error">
							<br>Please proceed with PayPal before completing your booking
						</span>
					</div>

					<!-- used for validating that the user paid via paypal before submitting -->
					<input type="hidden" id="paypal_checkout_id" value="">

				</div>

				<script>
					var paypal_checkout = '';
					function updatePaypalCheckout(complete_booking_total) {
						jQuery.ajax({
							url: '<?php echo admin_url('admin-ajax.php'); ?>' + '?action=rezgo',
							context: document.body,
							dataType: "json",
							data: { 
								method: 'gateways_paypal',
								rezgoAction: 'paypal_get_url',
								amount: complete_booking_total,
							},
							complete: function(data) {

								data = JSON.parse(data.responseText);
								let script = document.createElement('script');
								script.onload = function() {
									paypal_checkout = data.checkout;
									paypalCheckoutRender();
								};
								script.src = data.url;
								script.setAttribute('data-partner-attribution-id', 'Rezgo_STP_PPCP');
								document.head.appendChild(script);
							}
						});
					}
					updatePaypalCheckout('<?php echo $complete_booking_total; ?>');
				</script>

			<?php } else { ?>

				<div id="payment_method_<?php echo esc_attr($pmdc); ?>_box" class="payment_method_box" style="display:none;">

					<?php if ($pay['add']) { ?>
						<div id="payment_method_<?php echo esc_attr($pmdc); ?>_container" class="payment_method_container">
							<h4 class="payment-method-header"><?php echo esc_html($pay['name']); ?></h4>
							<input type="text" id="payment_method_<?php echo esc_attr($pmdc); ?>_field" class="form-control payment_method_field" name="payment_method_add" placeholder="<?php echo esc_attr($pay['add']); ?>" value="" disabled="disabled" />
							<span id="payment_method_<?php echo esc_attr($pmdc); ?>_error" class="payment_method_error">Please enter a value</span>
						</div>
					<?php } ?>
				</div>

		<?php

			}

			$pmdc++;
		} // end foreach($site->getPaymentMethods() 
		?>
	</div><!-- // #payment_data -->

	<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="scaModal" aria-hidden="true" id="sca_modal" style="bottom:0 !important; top:auto !important;">
		<div class="modal-dialog modal-md" style="top: calc(100% - 700px);">
			<div class="modal-content">
				<div class="modal-header">
					<h4 class="modal-title" style="position:relative; top:3px; float:left;">Card Validation</h4>
					<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close" style="width:50px; text-decoration:none; background: 0; border: 0; right: 20px; position:absolute; padding: 0;">
						<span aria-hidden="true" style="font-size:32px;">&times;</span>
					</button>
					<div class="clearfix"></div>
				</div>
				<div class="modal-body" id="sca_modal_content" style="height:640px;">
					<iframe style="border:0; width:100%; height:100%;" name="sca_modal_frame" id="sca_modal_frame"></iframe>
				</div>
			</div>
		</div>
	</div>
	
	<script>

		var response; // needs to be global to work in timeout
		let scaModal = new bootstrap.Modal(document.getElementById('sca_modal'));

		var ca_states = <?php echo json_encode( $site->getRegionList('ca') ); ?>;
        var us_states = <?php echo json_encode( $site->getRegionList('us') ); ?>;
        var au_states = <?php echo json_encode( $site->getRegionList('au') ); ?>;

		let gc_page = <?php echo $gc_page; ?> 
		let payment_page = <?php echo $payment_page; ?> 
		let pr_page = 0; 

		let payment_action, payment_url;
		if (pr_page) {
			payment_url = 'payment_ajax';
			payment_action = 'add_payment';
		} else if (gc_page) {
			payment_url = 'gift_card_ajax';
			payment_action = 'addGiftCard';
		}

		function hideSelectPayment() {
            jQuery('.select-payment').hide();
            jQuery('#rezgo-gift-card-use-hr').css({
                'margin': '0px 0 35px',
                'border-color': 'transparent'
            });
        }

		function showSelectPayment() {
            jQuery('.select-payment').show();
            jQuery('#rezgo-gift-card-use-hr').css({
                'margin': '50px 0px 35px',
                'border-color': '#eee'
            });
        }

		function select_cc() {
            jQuery("input[name='payment_method']:is(#payment_method_credit)").prop('checked', true);
            jQuery('.non-cc-method').hide();
            jQuery('input[name="payment_method"]:not(#payment_method_credit)').hide();
            jQuery('input[name="payment_method"]:not(#payment_method_credit)').attr('disabled', true);
            toggleCard();
        }

        function reset_tg_state() {
            jQuery("#tour_tg_insurance_coverage").val('');
            jQuery('#tg_error').hide();
            reset_pm();
        }

        function reset_pm() {
            jQuery('.non-cc-method').show();
            jQuery('input[name="payment_method"]:not(#payment_method_credit)').show();
            jQuery('input[name="payment_method"]:not(#payment_method_credit)').attr('disabled', false);
        }

        function toggle_tg(payment_method) {
            if (payment_method == 'Credit Cards') {
                jQuery('#tg-wrapper').show();

                jQuery('#tg-placeholder').removeClass('disabled');
                jQuery('.tg-disabled-overlay').hide();

                jQuery('#tg-no-longer-avail').hide();
                jQuery('#tour_tg_insurance_coverage').attr('disabled', false);

				setTimeout(() => {
					// if tg was selected, reset the selection to allow user to reconfirm
                if (!tg_loading && tg_initial_load) {
						tg.clear();
						configureTg();
					}
				}, 250);

            } else {
                jQuery('#tg-placeholder').addClass('disabled');
                jQuery('.tg-disabled-overlay').show();

                // only show message if user previously selected 'yes' to coverage
                if (jQuery('#tour_tg_insurance_coverage').val() == 'true' && overall_total > 0) {
                    jQuery('#tg-wrapper').show();
                    jQuery('#tg-no-longer-avail').show();
                } else {
                    jQuery('#tg-wrapper').hide();
                    jQuery('#tg-no-longer-avail').hide();
                }
                jQuery('#tour_tg_insurance_coverage').attr('disabled', true);
                reset_tg_state();
            }
        }
		
		function toggleCard() {

       		jQuery('.payment_method_container').show();

            <?php if ($tg_enabled) { ?>
                let payment_method_tg = jQuery('input[name=payment_method]:checked').val();
                toggle_tg(payment_method_tg);
            <?php } ?>

            <?php if ($tips_enabled) { ?>
                let payment_method_tips = jQuery('input[name=payment_method]:checked').val();
                toggle_tips(payment_method_tips);
            <?php } ?>

            let animateSpeed = 250;
			setTimeout(() => {
           		jQuery('.rezgo-billing-wrp').fadeIn(animateSpeed);
			}, 150);

            //reset stripe_error to allow form to be submitted
            stripe_error = 0;
            square_error = 0;

            jQuery('#payment_cards').hide();

            jQuery('.payment_method_box').hide();
            jQuery('.payment_method_field').attr('disabled', 'disabled');

            jQuery('#terms_other').hide();
            jQuery('#terms_credit_card').hide();

            jQuery(this).addClass('selected');

			<?php if (!$billing_address && $billing_country_required) { ?>
				jQuery('#tour_country').attr('disabled', true);
			<?php } ?>

            if (jQuery('input[name=payment_method]:checked').val() == 'Credit Cards') {

               <?php if ($tg_enabled) { ?>
                    if (!tg_loading) {
                        configureTg();
                    }
                <?php } ?>

                <?php if ($gateway_id == 'stripe_connect') { ?>
                    // re enable stripe_error
                    stripe_error = 1;
                <?php }else if ($gateway_id == 'square') { ?>
                    square_error = 1;
                <?php } ?>

                jQuery('#payment_cards').show();

                jQuery('#terms_credit_card').show();

				<?php if (!$billing_address && $billing_country_required) { ?>
					jQuery('#tour_country').attr('disabled', false);
				<?php } ?>

            } else if (jQuery('input[name=payment_method]:checked').val() == 'PayPal') {

                jQuery('#terms_other').show();

            } else if (jQuery('input[name=payment_method]:checked').val() == 'PayPal Checkout') {

                jQuery('#terms_other').show();

                let id = jQuery('input[name=payment_method]:checked').attr('id');

                jQuery('#' + id + '_box').fadeIn(animateSpeed);
                jQuery('#' + id + '_field').attr('disabled', false);

            } else if (jQuery('input[name=payment_method]:checked').val() == 'None') {

                jQuery('#terms_other').show();

                var id = jQuery('input[name=payment_method]:checked').attr('id');
                jQuery('#' + id + '_box').fadeIn(animateSpeed);
                jQuery('#' + id + '_field').attr('disabled', false);

                jQuery('#rezgo-complete-payment').html('Complete Booking');

            } else {

                jQuery('#terms_other').show();

                let id = jQuery('input[name=payment_method]:checked').attr('id');

                jQuery('#' + id + '_box').fadeIn(animateSpeed);
                jQuery('#' + id + '_field').attr('disabled', false);

            }

        }

        let payment_count = jQuery("input[name='payment_method']").length;
		// no_payment_method is counted towards 'payment_count'
		if (payment_count === 2) {
            jQuery("input[name='payment_method']").eq(0).prop("checked", true);
            hideSelectPayment();
            toggleCard();
        }

		jQuery('.rezgo-payment-method').click(function() {
			toggleCard();
		});

		function paypalCheckoutRender() {

			paypal.Buttons({
				style: {
					label: 'checkout'
				},
				fundingSource: paypal.FUNDING.PAYPAL,
				createOrder: function() { return paypal_checkout; },
				onApprove: function(data, actions) {

					jQuery('#payment_id').val(data.orderID);

					// used to flag this account as "added" for checkout
					// if we use payment_id, it might get caught from a stripe card input
					jQuery('#paypal_checkout_id').val(1);
					
					return actions.order.get().then(function(details) {

						console.log('order lookup response');

						jQuery('#paypal-button-header').hide();
						jQuery('#paypal-button-container').hide()
						
						setTimeout(function() {
							jQuery('#paypal-button-header').html('<span style="color:#003087;">Paying with <img src="<?php echo $site->path; ?>/img/logos/paypal.png" style="height:25px; width:auto; position:relative; top:-5px; left:5px;"></span>').fadeIn();
							jQuery('#paypal-button-container')
								.html('<label>' + details.payer.name.given_name + ' ' + details.payer.name.surname + '<br>' + details.payer.email_address + '</label><br><br><p>Your PayPal account will be charged when you complete your payment.</p>')
								.css('max-width', '100%').delay(500).fadeIn();	
						}, 500);
						
						let country = details.purchase_units[0].shipping.address.country_code;
						country = country.toLowerCase();
						
						if(details.payer.name.given_name) jQuery('#tour_first_name').val(details.payer.name.given_name);
						if(details.payer.name.surname) jQuery('#tour_last_name').val(details.payer.name.surname);
						
						if(details.purchase_units[0].shipping.address.address_line_1) jQuery('#tour_address_1').val(details.purchase_units[0].shipping.address.address_line_1);
						if(details.purchase_units[0].shipping.address.address_line_2) jQuery('#tour_address_2').val(details.purchase_units[0].shipping.address.address_line_2);
						
						if(details.purchase_units[0].shipping.address.admin_area_2) jQuery('#tour_city').val(details.purchase_units[0].shipping.address.admin_area_2);
						if(details.purchase_units[0].shipping.address.postal_code) jQuery('#tour_postal_code').val(details.purchase_units[0].shipping.address.postal_code);
						
						if(details.purchase_units[0].shipping.address.admin_area_1) jQuery('#tour_stateprov').val(details.purchase_units[0].shipping.address.admin_area_1).trigger('change');
						if(country) jQuery('#tour_country').val(country);
						
						jQuery('#paypal_error').hide();

						validate_form();
						
					});
					
				}
			}).render('#paypal-button-container');
			
		}

		// FORM SUBMIT functions
		function error_payment() {
			jQuery('#rezgo-book-errors').show();

			setTimeout(function(){
				jQuery('#rezgo-book-errors').hide();
			}, 8000);
		}

		function reset_payment(error_message) {
			jQuery('#rezgo-complete-payment').removeAttr('disabled');
			payment_wait(false);
			jQuery('#rezgo-book-message-body').html(error_message);
			jQuery('#rezgo-book-message-body').addClass('alert alert-warning');
		}

		function creditConfirm(token) {
			// the credit card transaction was completed, give us the token
			jQuery('#tour_card_token').val(token);
		}

		function payment_wait(wait) {
			if (wait) {
				jQuery('#rezgo-book-message-wait').show();
			} else {
				jQuery('#rezgo-book-message-body').html('');
				jQuery('#rezgo-book-message-wait').hide();
			}
		}

		// SCA passthrough data
    let passthrough = '';

    // show the sca challenge window if the gateway requires it
    function sca_window(mode, url, data, pass) {

		if(pass) passthrough = pass;

		if(mode == 'direct') {
			
			jQuery('.sca-direct-area').remove();
			jQuery('body').append('<div class="sca-direct-area">' + data + '</div>');
			
		}

		if(mode == 'iframe') {
			
			scaModal.show();
			setTimeout(() => {
				window.parent.scrollTo({ top:document.body.scrollHeight, left:0, behavior: "instant"} );
			}, 600);

			let content = data ? JSON.parse(data) : null;
			
			if(content) {
				
				// post content to 3DS frame
				let form = '<form action="' + url + '" method="post" target="sca_modal_frame" id="sca_post">';

				jQuery.each(content, function(index, value) {
					form += '<input type="hidden" name="' + index + '" value="' + value + '">';
				});
				
				form += '</form>';

				jQuery('body').append(form);
			
				jQuery('#sca_post').submit().remove();
				
			} else {
				
				// no post content, load directly into frame
				// this is needed to avoid frame-ancestors restrictions on some gateways like stripe
				jQuery('#sca_modal_frame').attr('src', url);
				
			}
			
		}

	}

    // called by the sca challenge window callback URL
    function sca_callback(code) {

        if(!code) return false;

        jQuery('#sca_modal').modal('hide');

        if(passthrough) {
            let data = JSON.parse(code); // parse data sent back from 3DS
            data.pass = passthrough; // add the passthrough data to the array
            code = JSON.stringify(data);
        }

        jQuery('#tour_card_token').val(code);
        jQuery('#payment_id').val(1); // needed to trigger the validate step on commit

        jQuery('#rezgo-book-message-body').html('Please wait one moment ...');
        jQuery('#rezgo-complete-payment').attr('disabled','disabled');
        jQuery('#rezgo-book-message').fadeIn();
        payment_wait(true);

		if (payment_page) {
			<?php if (REZGO_CAPTCHA_PUB_KEY) { ?>
				grecaptcha_submit();
			<?php } else { ?>
				regular_submit();
			<?php } ?>

		} else if (pr_page) {

			jQuery('#rezgo-payment-form').ajaxSubmit({
				url: '<?php echo admin_url('admin-ajax.php'); ?>' + '?action=rezgo',
				data: {
					method: payment_url,
					rezgoAction: payment_action
				},
				success: delay_response,
				error: function () {
					var body = 'Sorry, the system has suffered an error that it can not recover from.<br />Please try again later.<br />';
					jQuery('#rezgo-book-message-body').html(body);
					jQuery('#rezgo-book-message-body').addClass('alert alert-warning');
				}
			});

		} else if (gc_page) {

			// Submit the card token request and wait for a response
			jQuery('#rezgo-gift-payment').contents().find('#payment').submit();

			check_card_token();
		}

    }

	function validate_form() {
		<?php if ($tips_enabled) { ?>
			if (!custom_tip_valid && jQuery('#rezgo-custom-tip').hasClass('error')) {
				return;
			}
		<?php } ?>

		return jQuery('#rezgo-payment-form').valid();
	}

    function submit_payment() {

		if (gc_page) { 
			<?php if($site->exists(REZGO_CAPTCHA_PUB_KEY)) { ?>	
			verifyRecaptcha();
			<?php } ?>
		}
    
        let validate_check = validate_form();
        let payment_method = jQuery('input:radio[name=payment_method]:checked').val();
    
        jQuery('#rezgo-complete-payment').attr('disabled','disabled');
        jQuery('#rezgo-book-message-body').removeClass('alert alert-warning');
        jQuery('#rezgo-book-message-body').html('');
        jQuery('#rezgo-book-terms').fadeIn();

        // if we set a card token via a SCA challenge, clear it for a potential new one
        if(passthrough) {
            jQuery('#tour_card_token').val('');
            jQuery('#payment_id').val('');
        }
    
        // only activate on actual form submission, check payment info
        if(overall_total > 0) {

            var force_error = 0;

			
			<?php if ($analytics_ga4) { ?>
				// gtag add_payment_info
				gtag("event", "add_payment_info", {
					currency: "<?php echo esc_html($company->currency_base); ?>",
					value: parseFloat(<?php echo $cart_subtotal_analytics; ?>),
					payment_type: payment_method,
					<?php echo isset($_COOKIE['rezgo_promo']) ? 'coupon: ' .'"'.esc_html($_COOKIE['rezgo_promo'] ?? $site->cart_trigger_code).'"' . ',': ''; ?>
					items: [
						<?php $tag_index = 1;
						foreach ($cart as $ga4_item) { 
								$new_ga4_price = $ga4_item->package ? $ga4_item->package_item_after_discount : $ga4_item->sub_total;
							?>
							{
								item_id: "<?php echo esc_html($ga4_item->uid); ?>",
								item_name: "<?php echo esc_html(htmlentities(trim($ga4_item->item) . ' - ' . trim($ga4_item->option))); ?>",
								price: Number(parseFloat(<?php echo esc_html((float) ($new_ga4_price / $ga4_item->pax)); ?>).toFixed(2)),
								quantity: <?php echo esc_html($ga4_item->pax); ?>,
								<?php echo isset($_COOKIE['rezgo_promo']) ? 'coupon: ' .'"'.esc_html($_COOKIE['rezgo_promo'] ?? $site->cart_trigger_code).'"' . ',': ''; ?>
								index: <?php echo $tag_index; ?>,
							},
						<?php $tag_index++; } unset($tag_index); ?>
					]
				});
			<?php } ?>

			<?php if ($analytics_gtm){ ?>
				// tag manager add_payment_info
				window.dataLayer = window.dataLayer || []; // Check the dataLayer is exists and an array
				window.dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
				window.dataLayer.push({
					event: "add_payment_info",
					ecommerce: {
						currency: "<?php echo esc_html($company->currency_base); ?>",
						value: parseFloat(<?php echo $cart_subtotal_analytics; ?>),
						payment_type: payment_method,
						<?php echo isset($_COOKIE['rezgo_promo']) ? 'coupon: ' .'"'.esc_html($_COOKIE['rezgo_promo'] ?? $site->cart_trigger_code).'"' . ',': ''; ?>
						items: [
							<?php $tag_index = 1;
							foreach ($cart as $gtm_item) { 
								$new_gtm_price = $gtm_item->package ? $gtm_item->package_item_after_discount : $gtm_item->sub_total;
							?>
							{
								item_id: "<?php echo esc_html($gtm_item->uid); ?>",
								item_name: "<?php echo esc_html(htmlentities(trim($gtm_item->item) . ' - ' . trim($gtm_item->option))); ?>",
								price: Number(parseFloat(<?php echo esc_html((float) ($new_gtm_price / $gtm_item->pax)); ?>).toFixed(2)),
								quantity: <?php echo esc_html($gtm_item->pax); ?>,
								<?php echo isset($_COOKIE['rezgo_promo']) ? 'coupon: ' .'"'.esc_html($_COOKIE['rezgo_promo'] ?? $site->cart_trigger_code).'"' . ',': ''; ?>
								index: <?php echo $tag_index; ?>,
							},
							<?php $tag_index++; } unset($tag_index); ?>
						]
					}
				});
			<?php } ?>

			if (payment_method == 'Credit Cards') {

				<?php if ($tg_enabled) { ?>

					if (!tg.isFormComplete()) {
						jQuery('#tg_error').show();
						force_error = 1;
					} else {
						jQuery('#tg_error').hide();
					}

				<?php } ?>

				<?php if ($gateway_id == 'stripe_connect') { ?>

					// catch empty fields on stripe
					if (jQuery('#card-element').hasClass('StripeElement--empty')) {
						jQuery('#card-element').css('border-color', '#a94442');
						jQuery('#card-errors').text('Please enter your Credit Card details');
						stripe_error = 1;
					}
					if (jQuery('#stripe_cardholder_name').val() == '') {
						jQuery(this).css({
							'borderColor': '#a94442'
						});
						jQuery('#stripe_cardholder_name_error').show();
						stripe_error = 1;
					}
				<?php } elseif ($gateway_id == 'square') { ?>
					let tokenized_square_card = false;
					if (cardHolder.val() == '') {

						jQuery('#square_cardholder_name').css("border-color", "#a94442");
						jQuery('#square_cardholder_name_error').show();
						square_error = 1;
					} else if(!validate_check){
                        jQuery('#rezgo-complete-payment').removeAttr('disabled');
			            return error_payment();
                    } else {
						try {
							let sq_billing_details = {};
							if (payment_page) {
								sq_billing_details = {
									givenName: '<?php echo $lead_passenger['first_name'] ?: 'First'; ?>',
                                    familyName: '<?php echo $lead_passenger['last_name'] ?: 'Last'; ?>',
                                    email: '<?php echo $lead_passenger['email'] ?: 'email@address.com'; ?>',
								}
							} else if(gc_page) {
								sq_billing_details = {
									givenName: jQuery('#billing_first_name').val() ? jQuery('#billing_first_name').val() : 'First',
                                    familyName: jQuery('#billing_last_name').val() ? jQuery('#billing_last_name').val() : 'Last',
                                    email: jQuery('#billing_email').val() ? jQuery('#billing_email').val() : 'email@address.com',
								}
							}

                            const verification_details = {
                                amount: Number(overall_total).toFixed(2),
                                currencyCode: '<?php echo $currency_base; ?>',
                                intent: 'CHARGE',
                                customerInitiated: true,
                                sellerKeyedIn: false,
                                billingContact: sq_billing_details
                            };

                            card.tokenize(verification_details).then(token_result => {
								jQuery('#tour_card_token').val();
								// console.log(token_result);
								if (token_result.status === 'OK') {
									jQuery('#tour_card_token').val(token_result.token);
									console.log(square_error);
									tokenized_square_card = true;

								} else {

									let error_message = `Tokenization failed with status: ${token_result.status}`;
									if (token_result.errors) {
										error_message += ` and errors: ${JSON.stringify(
											token_result.errors
										)}`;
									}
									square_error = 1;
									console.log(error_message);
									reset_payment(error_message);
								}
							}).catch(error => {
								// console.log("An error occurred during tokenization:", error);
								reset_payment("Payment Declined");
								square_error = 1;
							});
						} catch (error) {
							// console.log("Something went wrong during Tokenization");
							square_error = 1;
						}
					}
					if(!tokenized_square_card && square_error){
						jQuery('#card-element').css("border-radius", "6px");
						jQuery('#card-element').css("border", "#a94442 solid 1px");
						displayErrors('Please fill out all required fields.');
					}
				<?php } elseif ($gateway_id == 'tmt') { ?>

				<?php } else { ?>

					if (!jQuery('#tour_payment').contents().find('#payment').valid()) {
						force_error = 1;
					}

				<?php } ?>

			} else if (payment_method == 'PayPal Checkout') {

				if (!jQuery('#paypal_checkout_id').val()) {
					force_error = 1;
					jQuery('#paypal_error').show();
				}

			} else {
				// other payment methods need their additional fields filled
				var id = jQuery('input:radio[name=payment_method]:checked').attr('id');
				if (jQuery('#' + id + '_field').length != 0 && !jQuery('#' + id + '_field').val()) {
					// this payment method has additional data that is empty
					force_error = 1;

					jQuery('#' + id + '_field').css('border-color', '#a94442');
					jQuery('#' + id + '_error').show();
				}
			}
		} else if (overall_total <= 0) {
			stripe_error = 0;
			square_error = 0;
		}

		if (force_error || !validate_check || stripe_error || square_error) {

			jQuery('#rezgo-complete-payment').removeAttr('disabled');
			return error_payment();

		} else {

			if (payment_method == 'Credit Cards' && overall_total > 0) {

				<?php if ($gateway_id == 'stripe_connect') { ?>

					let cardholder_name = jQuery('#stripe_cardholder_name').val();
					jQuery('#rezgo-book-message-body').html('Please wait one moment ...');
					jQuery('#rezgo-complete-payment').attr('disabled','disabled');
					jQuery('#rezgo-book-message').fadeIn();
					payment_wait(true);
					
					if(stripe_error != 1) {
	
						card.update({
							value: { postalCode: jQuery('#tour_postal_code').val() }
						});
	
						jQuery('#rezgo-book-message-body').html('Please wait one moment ...');
		
						jQuery('#rezgo-book-terms').fadeOut().promise().done(function () {
							jQuery('#rezgo-book-message').fadeIn();
						});
		
						// clear the existing credit card token, just in case one has been set from a previous attempt
						jQuery('#tour_card_token').val('');
		
						stripe.createPaymentMethod({
							type: 'card',
							card: card,
							billing_details: {
								name: jQuery('#stripe_cardholder_name').val(),
							},
						}).then((result) => {
							
							if (result.error) {
								console.log(result);

								card.clear();
								reset_payment(result.error.message);

							} else {

								jQuery('#tour_card_token').val(result.paymentMethod.id);

								if (payment_page) {
									<?php if (REZGO_CAPTCHA_PUB_KEY) { ?>
										grecaptcha_submit();
									<?php } else { ?>
										regular_submit();
									<?php } ?>
								} else if (gc_page || pr_page) {
									check_card_token();
								}
							}

						}).catch((error) => {

							console.error(error);

							card.clear();
							reset_payment(error);

						});
						
					}
					
				<?php } elseif ($gateway_id == 'tmt') { ?>

					jQuery('#rezgo-complete-payment').removeAttr('disabled');

					<?php if (REZGO_LITE_CONTAINER) {
						$local_referrer = parse_url($_SERVER['HTTP_REFERER']);
						$local_referring_host = $local_referrer['host'];

						$path = "'" . (string) $local_referring_host . "," . (string) $site->referrer . "'";
					} ?>

					<?php
						$booked_for_date =  date("Y-m-d", max($booking_dates));

						$booking_items = implode(" | ", $booking_items);
						$booking_items = substr($booking_items, 0, 1020);
					?>
					
					function initTmt(overall_total, recaptcha=0, token='') {
						jQuery.ajax('<?php echo admin_url('admin-ajax.php'); ?>' + '?action=rezgo&method=gateways_tmt&amount='+ overall_total +'&recaptcha_response=' + token).done(function(result) {
							
							if(!result) {
								jQuery('#rezgo-book-message').show();
								response = '{"status":3, "message":"There was an error processing your payment"}';
								show_response();
							} else {

								let tmt_data = JSON.parse(result);

								const tmtPaymentModal = new parent.tmtPaymentModalSdk({
									path: tmt_data.path,
									<?php if (REZGO_LITE_CONTAINER) echo "origin: " . $path . ","; ?>
									environment: tmt_data.account_mode,
									transactionType: 'authorize',
									data: {
										// Booking Data
										booking_id: "0",
										channels: tmt_data.channel,
										date: "<?php echo esc_html($booked_for_date); ?>",
										currencies: decodeURIComponent('<?php echo rawurlencode((string) $company->currency_base); ?>'),
										total: (overall_total * 100),
										description: "Rezgo Order: <?php echo esc_html($booking_items); ?>",
										// Authentication
										booking_auth: tmt_data.auth_string,
										// Lead Traveller
										firstname: '<?php echo $lead_passenger['first_name'] ?: 'First'; ?>',
										surname: '<?php echo $lead_passenger['last_name'] ?: 'Last'; ?>',
										email: '<?php echo $lead_passenger['email'] ?: 'email@address.com'; ?>',
										country: '<?php echo strtoupper($company->country); ?>',
										// Payment details
										payee_name:'<?php echo $lead_passenger['first_name'] ?: 'First'; ?>',
										payee_email: '<?php echo $lead_passenger['email'] ?: 'email@address.com'; ?>',
										payee_address: jQuery('#tour_address_1').val() ? jQuery('#tour_address_1').val() : 'Address',
										payee_city: jQuery('#tour_city').val() ? jQuery('#tour_city').val() : 'City',
										payee_country: jQuery('#tour_country').val().toUpperCase(),
										payee_postcode: jQuery('#tour_postal_code').val() ? jQuery('#tour_postal_code').val() : '0000'
									}
								});
						
								let lock = 0;
								
								// successful transaction
								tmtPaymentModal.on("transaction_logged", function(data) {
									if (lock == 1) return;
									lock = 1;
									
									jQuery('#rezgo-book-message-body').html('Please wait one moment ...');
									jQuery('#rezgo-complete-payment').attr('disabled', 'disabled');
									jQuery('#rezgo-book-message').fadeIn();

									payment_wait(true);

									tmtPaymentModal.closeModal();

									jQuery('#tour_card_token').val(data.id);
									jQuery('#payment_id').val(1); // tmt doesn't need this value, but it is needed to trigger the validate API
									
									<?php if (REZGO_CAPTCHA_PUB_KEY) { ?>
										grecaptcha_submit();
									<?php } else { ?>
										regular_submit();
									<?php } ?>
								});
				
								tmtPaymentModal.on("transaction_failed", function (data) {

									if(lock == 1) return;
									lock = 1;
									
									tmtPaymentModal.closeModal();

									jQuery('#rezgo-book-message').show();
									
									response = '{"status":3, "message":"Payment Declined"}';
									show_response();
								});
							}	
                       });
					}

					<?php if (REZGO_CAPTCHA_PUB_KEY) { ?>
						grecaptcha.execute('<?php echo REZGO_CAPTCHA_PUB_KEY; ?>', {action: 'submit'}).then(function(token) {
							initTmt(overall_total, 1, token);
                        });
					<?php } else { ?>
						initTmt(overall_total, 0);
					<?php } ?>

				<?php } else { ?>

					payment_wait(true);
	
					jQuery('#rezgo-book-message-body').html('Please wait one moment ...');
	
					jQuery('#rezgo-book-terms').fadeOut().promise().done(function () {
						jQuery('#rezgo-book-message').fadeIn();
					});
	
					// clear the existing credit card token, just in case one has been set from a previous attempt
					jQuery('#tour_card_token').val('');
	
					// submit the card token request and wait for a response
					jQuery('#tour_payment').contents().find('#payment').submit();
	
					// wait until the card token is set before continuing (with throttling)
					function check_card_token() {
						var card_token = jQuery('#tour_card_token').val();
	
						if (card_token == '') {
							// card token has not been set yet, wait and try again
							setTimeout(function () {
								check_card_token();
							}, 200);
						} else {

							// the field is present? submit normally
							if (payment_page) { 
								<?php if (REZGO_CAPTCHA_PUB_KEY) { ?>
									grecaptcha_submit();
								<?php } else { ?>
									regular_submit();
								<?php } ?>

							} else if (pr_page || gc_page) {

								jQuery('#rezgo-payment-form').ajaxSubmit({
									url: '<?php echo admin_url('admin-ajax.php'); ?>' + '?action=rezgo',
									data: {
										method: payment_url,
										rezgoAction: payment_action
									},
									success: delay_response,
									error: function() {
										var body = 'Sorry, the system has suffered an error that it can not recover from.<br />Please try again later.<br />';
										reset_payment(body);
									}
								});
							}
						}
					}
	
					check_card_token();
	
				<?php } ?>
			
			} else {

				payment_wait(true);

				jQuery('#rezgo-book-message').show();
				jQuery('#rezgo-book-message-body').html('Please wait one moment ...');

				// not a credit card payment (or $0) and everything checked out, submit normally
				if (payment_page) { 
					<?php if (REZGO_CAPTCHA_PUB_KEY) { ?>
						grecaptcha_submit();
					<?php } else { ?>
						regular_submit();
					<?php } ?>
				} else if (pr_page || gc_page) {

					jQuery('#rezgo-payment-form').ajaxSubmit({
						url: '<?php echo admin_url('admin-ajax.php'); ?>' + '?action=rezgo',
						data: {
							method: payment_url,
							rezgoAction: payment_action
						},
						success: delay_response,
						error: function() {
							var body = 'Sorry, the system has suffered an error that it can not recover from.<br />Please try again later.<br />';
							reset_payment(body);
						}
					});
				}
			}

			// return false to prevent normal browser submit and page navigation
			return false;
		}
    }

	function check_card_token() {
		let card_token = jQuery('#tour_card_token').val();
		let action, url;
		
		if(card_token == '') {
			// card token has not been set yet, wait and try again
			setTimeout(function () {
				check_card_token();
			}, 200);
		} else {
			// the field is present? submit normally
			// alert('3DS flow token : ' + jQuery('#tour_card_token').val() );

			console.log(payment_url);
			console.log(payment_action);
			
			jQuery('#rezgo-payment-form').ajaxSubmit({
				url: '<?php echo admin_url('admin-ajax.php'); ?>' + '?action=rezgo',
				data: {
					method: payment_url,
					rezgoAction: payment_action
				},
				success: delay_response,
				error: function() {
					var body = 'Sorry, the system has suffered an error that it can not recover from.<br />Please try again later.<br />';
					reset_payment(body);
				}
			});
		}
	}

	// this function delays the output so we see the loading graphic
	function delay_response(responseText) {
		response = responseText;
		if(response.debug) {
			//console.log(response);
		} else {
			setTimeout(function () {
				show_response();
			}, 800);
		}
	}

	// Validation Setup
	jQuery.validator.setDefaults({
		highlight: function(element) {
			if (jQuery(element).attr("type") == "checkbox") {
				jQuery(element).closest('.rezgo-form-checkbox').addClass('has-error');
			} else if (jQuery(element).attr("name")=="waiver") {
				jQuery(element).parent().find('.error').show();
			} else if (jQuery(element).attr("type") == "radio") {
				jQuery(element).closest('.rezgo-input-radio').addClass('has-error');
			} else {
				jQuery(element).closest('.rezgo-form-input').addClass('has-error');
			}

			jQuery(element).closest('.form-group').addClass('has-error');
		},
		unhighlight: function(element) {
			if ( jQuery(element).attr("type") == "checkbox" ) {
				jQuery(element).closest('.rezgo-form-checkbox').removeClass('has-error');
			} else if (jQuery(element).attr("type") == "radio") {
				jQuery(element).closest('.rezgo-input-radio').addClass('has-error');
			} else {
				jQuery(element).closest('.rezgo-form-input').removeClass('has-error');
			}

			jQuery(element).closest('.form-group').removeClass('has-error');
		},
		focusInvalid: false,
		errorElement: 'span',
		errorClass: 'help-block',
		errorPlacement: function(error, element) {
			if (jQuery(element).attr("name") == "name" || jQuery(element).attr("name") == "pan" || jQuery(element).attr("name") == "cvv" || jQuery(element).attr("name") == "waiver") {
				error.hide();
			} else if (jQuery(element).attr("type") == "radio") {
				error.insertAfter(element.parent().parent());
			} else if (jQuery(element).attr("name") == "agree_terms") {
				error.insertAfter(element.parent().parent());
			} else if (jQuery(element).attr("type") == "checkbox") {
				error.insertAfter(element.siblings('.rezgo-form-comment'));
			} else {
				error.insertAfter(element);
			}
		}
	});

	jQuery.validator.addMethod("validate_domain", function(value, element) {
		if (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)) {
			return true;
		} else {
			return false;
		}
	}, "Enter a valid email address");

</script>