PageSourceSearch

https://vtauto.org/wp-content/plugins/wp-easy-pay-premium/assets/f…?rand=1584060075&ver=7.1.2

js vtauto.org collected 2026-10-02 17:57:34 UTC 129,400 bytes, 3,813 lines download raw bytes

1let googlePay = {};
2let afterpay = {};
3let cashAppPay = {};
4let applePay = {};
5let recaptcha = '';
6window.wpepTurnstileWidgets = window.wpepTurnstileWidgets || {};
7window.wpepTurnstileReadyQueue = window.wpepTurnstileReadyQueue || [];
8
9/**
10 * Check whether the Turnstile container is actually visible to the user.
11 *
12 * @param {HTMLElement} container Turnstile container element.
13 * @return {boolean}
14 */
15window.wpepIsTurnstileContainerVisible = function (container) {
16	if (!container) {
17		return false;
18	}
19
20	var node = container;
21	while (node && node !== document.documentElement) {
22		var style = window.getComputedStyle(node);
23		if (style.display === 'none' || style.visibility === 'hidden') {
24			return false;
25		}
26		node = node.parentElement;
27	}
28
29	return container.getClientRects().length > 0;
30};
31
32/**
33 * Check whether Turnstile render API is ready.
34 *
35 * @return {boolean}
36 */
37window.wpepIsTurnstileApiReady = function () {
38	return typeof turnstile !== 'undefined' && typeof turnstile.render === 'function';
39};
40
41/**
42 * Ensure Turnstile api.js is available without loading duplicates.
43 *
44 * @param {Function} callback Callback when turnstile.render is available.
45 */
46window.wpepEnsureTurnstileApi = function (callback) {
47	if (window.wpepIsTurnstileApiReady()) {
48		callback();
49		return;
50	}
51
52	window.wpepTurnstileReadyQueue.push(callback);
53	if (window.wpepTurnstileScriptLoading) {
54		return;
55	}
56	window.wpepTurnstileScriptLoading = true;
57
58	var flushReadyQueue = function () {
59		var queue = window.wpepTurnstileReadyQueue || [];
60		window.wpepTurnstileReadyQueue = [];
61		for (var i = 0; i < queue.length; i++) {
62			if (typeof queue[i] === 'function') {
63				queue[i]();
64			}
65		}
66	};
67
68	var waitForTurnstile = function (attempts) {
69		if (window.wpepIsTurnstileApiReady()) {
70			window.wpepTurnstileScriptLoading = false;
71			flushReadyQueue();
72			return;
73		}
74		if (attempts <= 0) {
75			window.wpepTurnstileScriptLoading = false;
76			return;
77		}
78		setTimeout(function () {
79			waitForTurnstile(attempts - 1);
80		}, 200);
81	};
82
83	if (document.querySelector('script[src*="challenges.cloudflare.com/turnstile/v0/api.js"]')) {
84		waitForTurnstile(50);
85		return;
86	}
87
88	var script = document.createElement('script');
89	script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
90	script.setAttribute('data-cfasync', 'false');
91	script.onload = function () {
92		waitForTurnstile(20);
93	};
94	script.onerror = function () {
95		window.wpepTurnstileScriptLoading = false;
96	};
97	document.head.appendChild(script);
98};
99
100/**
101 * Render Cloudflare Turnstile explicitly for a WPEP form widget container.
102 *
103 * @param {number|string} currentFormId Form post ID.
104 */
105window.wpepInitTurnstile = function (currentFormId) {
106	if (typeof wpep_local_vars === 'undefined' || wpep_local_vars.captcha_provider !== 'turnstile') {
107		return;
108	}
109
110	var siteKey = wpep_local_vars.turnstile_site_key;
111	if (!siteKey) {
112		return;
113	}
114
115	var containerId = 'wpep-turnstile-' + currentFormId;
116	var container = document.getElementById(containerId);
117	if (!container || !window.wpepIsTurnstileContainerVisible(container)) {
118		return;
119	}
120
121	if (window.wpepTurnstileWidgets[currentFormId]) {
122		return;
123	}
124
125	if (container.querySelector('iframe, input[name="cf-turnstile-response"]')) {
126		window.wpepTurnstileWidgets[currentFormId] = true;
127		return;
128	}
129
130	window.wpepEnsureTurnstileApi(function () {
131		if (!window.wpepIsTurnstileApiReady() || window.wpepTurnstileWidgets[currentFormId]) {
132			return;
133		}
134
135		if (!window.wpepIsTurnstileContainerVisible(container)) {
136			return;
137		}
138
139		// Do not use turnstile.ready() — Formidable and other plugins load
140		// api.js with async/defer, which breaks turnstile.ready().
141		try {
142			window.wpepTurnstileWidgets[currentFormId] = turnstile.render('#' + containerId, {
143				sitekey: siteKey,
144				theme: 'light',
145			});
146		} catch (e) {
147			delete window.wpepTurnstileWidgets[currentFormId];
148		}
149	});
150};
151
152/**
153 * Retry Turnstile init until the widget container becomes visible (popup/wizard).
154 *
155 * @param {number|string} formId Form post ID.
156 * @param {number} attempt Current retry count.
157 */
158window.wpepScheduleTurnstileInit = function (formId, attempt) {
159	if (typeof wpep_local_vars === 'undefined' || wpep_local_vars.captcha_provider !== 'turnstile') {
160		return;
161	}
162
163	attempt = attempt || 0;
164	if (attempt > 30) {
165		return;
166	}
167
168	var container = document.getElementById('wpep-turnstile-' + formId);
169	if (!container) {
170		return;
171	}
172
173	window.wpepInitTurnstile(formId);
174
175	if (window.wpepTurnstileWidgets[formId] || container.querySelector('iframe')) {
176		return;
177	}
178
179	if (window.wpepIsTurnstileContainerVisible(container)) {
180		setTimeout(function () {
181			window.wpepScheduleTurnstileInit(formId, attempt + 1);
182		}, 250);
183		return;
184	}
185
186	setTimeout(function () {
187		window.wpepScheduleTurnstileInit(formId, attempt + 1);
188	}, 250);
189};
190
191const payments = initializePayments(wpep_local_vars.square_application_id, wpep_local_vars.square_location_id_in_use);
192
193function wpepGetPaymentNonce(current_form_id) {
194	var nonceField = jQuery('#theForm-' + current_form_id + ' input.wpep-payment-nonce-field');
195	if (!nonceField.length) {
196		nonceField = jQuery('form.wpep_payment_form[data-id="' + current_form_id + '"] input.wpep-payment-nonce-field');
197	}
198	if (nonceField.length) {
199		return nonceField.val();
200	}
201	if (typeof wpep_local_vars !== 'undefined') {
202		if (wpep_local_vars.wpep_payment_nonce) {
203			return wpep_local_vars.wpep_payment_nonce;
204		}
205		if (wpep_local_vars.wp_payment_nonce) {
206			return wpep_local_vars.wp_payment_nonce;
207		}
208	}
209	return '';
210}
211
212document.addEventListener('DOMContentLoaded', async function () {
213	jQuery('.loader').hide();
214	jQuery(document).on('click', '.form-wizard-next-btn', function () {
215		var formId = jQuery(this).parents('form').data('id');
216		window.wpepScheduleTurnstileInit(formId);
217	});
218	jQuery(document).on('click', '.wpep-popup-btn', function () {
219		window.wpepScheduleTurnstileInit(jQuery(this).data('btn-id'));
220	});
221	jQuery('#cash_app_pay_v1_element').bind('click', function (e) {
222		e.preventDefault();
223		e.stopImmediatePropagation();
224	});
225	jQuery('.wizard-section').css('visibility', 'visible');
226	jQuery('.parent-loader').remove();
227
228	var wpep_paymentForm = {};
229
230
231	if (jQuery('form.wpep_payment_form').length > 0) {
232		jQuery('form.wpep_payment_form').each(
233			async function () {
234				var current_form_id = jQuery(this).data('id');
235				var currency = jQuery(this).data('currency');
236				let card;
237
238				if (wpep_local_vars.captcha_provider === 'turnstile') {
239					window.wpepScheduleTurnstileInit(current_form_id);
240				}
241
242				calculate(current_form_id, currency);
243
244				jQuery('.qty').keyup(function () {
245					calculate(current_form_id, currency);
246				});
247
248				if (!window.Square) {
249					throw new Error('Square.js failed to load properly');
250				}
251
252				// Bind an event handler to the custom amount input field
253				jQuery('.other-' + current_form_id).click(function () {
254					let timeoutId;
255					jQuery('.other-' + current_form_id).on('input', function () {
256						var customAmount = jQuery(this).val();
257						clearTimeout(timeoutId);
258						timeoutId = setTimeout(function () {
259							jQuery('.loader').show();
260							jQuery(`#theForm-${current_form_id}`).find('input[name="one_unit_cost"]').val(customAmount);
261							jQuery('#wpep-selected-amount-' + current_form_id).val(customAmount).trigger('change');
262							jQuery('#wpep-single-form-' + current_form_id).click();
263						}, 500);
264					});
265				});
266				if (wpep_local_vars.applepay == 'on') {
267
268					var applePayButtonTarget = '';
269					jQuery('#wpep-selected-amount-' + current_form_id).val(jQuery('#amount_display_' + current_form_id).html());
270
271					applePay[current_form_id] = await displayApplePay(payments, current_form_id, currency, applePay, applePayButtonTarget);
272
273					let timeoutpayId;
274
275					function handleDOMChanges(app_btn) {
276						clearTimeout(timeoutpayId);
277						timeoutpayId = setTimeout(async function () {
278
279							jQuery('#wpep-selected-amount-' + current_form_id).val(jQuery('#amount_display_' + current_form_id).html());
280
281							try {
282
283								jQuery('#applePay-' + current_form_id).remove();
284								jQuery('#applePayfather-' + current_form_id).append('<div id="applePay-' + current_form_id + '" class="apple-pay-button tab-content-' + current_form_id + '"></div>');
285
286								var applePayButtonTarget = document.getElementById('applePay-' + current_form_id);
287								jQuery('#applePayfather-' + current_form_id).css('display', 'none');
288								applePay[current_form_id] = await displayApplePay(payments, current_form_id, currency, applePay, applePayButtonTarget);
289								//jQuery('#testing_apple').html('');
290								applePayButtonTarget.addEventListener('click', eventHandlerapple);
291
292								setTimeout(function () {
293									if (jQuery('#applePayfather-' + current_form_id).hasClass('current')) {
294										jQuery('#applePayfather-' + current_form_id).css('display', 'block');
295									}
296								}, 1200); // 2000 milliseconds = 2 seconds
297
298
299							} catch (e) {
300								console.error('Initializing Applepay failed', e);
301							}
302						}, 10);
303					}
304					// Use Mutation Observer to detect DOM changes
305					const observer = new MutationObserver(handleDOMChanges);
306					// Observe changes in the amount display element
307					const amountDisplayElement = document.getElementById('amount_display_' + current_form_id);
308					if (amountDisplayElement) {
309						observer.observe(amountDisplayElement, { subtree: true, childList: true });
310					}
311					applePayButtonTarget = document.getElementById('applePay-' + current_form_id);
312					applePayButtonTarget.addEventListener('click', eventHandlerapple);
313
314					async function eventHandlerapple(event) {
315
316						event.preventDefault();
317						event.stopImmediatePropagation();
318						try {
319							card = '';
320							var res = false;
321							res = paymentButtonClicked(event, card, current_form_id, currency);
322
323							if (res || wpep_local_vars.wpep_show_wizard == 'on') {
324								const result = await applePay[current_form_id].tokenize();
325								if (result.status === 'OK') {
326									await handlePaymentMethodSubmission(event, applePay, current_form_id, currency, result.token);
327								}
328							} else {
329								event.preventDefault();
330								event.stopImmediatePropagation();
331							}
332						} catch (e) {
333							console.error(e);
334						}
335					};
336				}
337				if (wpep_local_vars.gpay == 'on') {
338					setTimeout(function () {
339						googlePay[current_form_id] = displayGooglePay(payments, current_form_id, currency, googlePay);
340						var googlePayButtonTarget = document.getElementById('google-pay-button-' + current_form_id);
341						googlePayButtonTarget.addEventListener('click', eventHandler);
342
343						async function eventHandler(event) {
344							event.preventDefault();
345							event.stopImmediatePropagation();
346
347							try {
348
349								card = '';
350								var res = false;
351								res = paymentButtonClicked(event, card, current_form_id, currency);
352
353								if (res || wpep_local_vars.wpep_show_wizard == 'on') {
354									const result = await googlePay[current_form_id].tokenize();
355
356									if (result.status === 'OK') {
357										await handlePaymentMethodSubmission(event, googlePay, current_form_id, currency, result.token);
358									}
359								} else {
360									event.preventDefault();
361									event.stopImmediatePropagation();
362								}
363							} catch (e) {
364								console.error(e);
365							}
366						};
367
368					}, 2000);
369				}
370
371				if (wpep_local_vars.afterpay == 'on') {
372
373					afterpay = displayAfterPay(payments, current_form_id, currency);
374
375					if (afterpay !== undefined) {
376						const afterpayButton = document.getElementById('afterpay-button-' + current_form_id);
377						// if(jQuery('#afterpay-'+current_form_id).is(':visible')){
378						afterpayButton.addEventListener('click', async function (event) {
379
380							card = '';
381							var res = false;
382							res = paymentButtonClicked(event, card, current_form_id, currency);
383							if (res || wpep_local_vars.wpep_show_wizard == 'on') {
384								await handlePaymentMethodSubmission(event, afterpay, current_form_id, currency, false);
385							} else {
386								event.preventDefault();
387								event.stopImmediatePropagation();
388							}
389						});
390						// }
391					}
392
393				}
394
395				if (wpep_local_vars.cashapp == 'on') {
396
397					cashAppPay = displayCashApp(payments, current_form_id, currency);
398
399					jQuery('#cash-app-pay-' + current_form_id).on('click', function (ee) {
400						card = '';
401						var res = paymentButtonClicked(event, card, current_form_id, currency);
402
403						if (res || wpep_local_vars.wpep_show_wizard == 'on') {
404							cashAppPay.addEventListener('ontokenization', function (event) {
405								const { tokenResult, error } = event.detail;
406								if (error) {
407									// developer handles error
408								} else if (tokenResult.status === 'OK') {
409									if (res || wpep_local_vars.wpep_show_wizard == 'on') {
410										jQuery("#theForm-" + current_form_id).append(jQuery('<div />').attr('class', 'wpepLoader').html('<div class="initial-load-animation"><div class="payment-image icomoonLib"><span class="icon-pay"></span></div><div class="loading-bar"><div class="blue-bar"></div></div></div>'));
411										handlePaymentMethodSubmission(event, cashAppPay, current_form_id, currency, tokenResult.token, 'cashapp');
412									}
413								}
414
415							});
416						} else {
417							ee.preventDefault();
418							ee.stopImmediatePropagation();
419						}
420
421
422					});
423				}
424				if (wpep_local_vars.giftcard == 'on') {
425
426					var giftcard;
427					jQuery(`ul.wpep_tabs-${current_form_id} li.tab-link`).on('click', async function () {
428						const selectedTab = jQuery(this).data('tab');
429
430						if (selectedTab === 'giftcard-' + current_form_id) {
431
432							giftcard = await displayGiftcard(payments, current_form_id, currency);
433
434							jQuery('.wpep-single-form-' + current_form_id).click(async function (event) {
435								event.preventDefault();
436								var res = paymentButtonClicked(event, giftcard, current_form_id, currency);
437								if (res || wpep_local_vars.wpep_show_wizard == 'on') {
438									await handlePaymentMethodSubmissiongftcpay(event, giftcard, current_form_id, currency, false);
439								}
440							});
441
442							jQuery('.wpep-wizard-form-' + current_form_id).click(async function (event) {
443								event.preventDefault();
444								var res = paymentButtonClicked(event, giftcard, current_form_id, currency);
445								if (res || wpep_local_vars.wpep_show_wizard == 'on') {
446									const result = await giftcard.tokenize();
447									if (result.status === 'OK') {
448										await handlePaymentMethodSubmissiongftcpay(event, giftcard, current_form_id, currency, result.token);
449									}
450								}
451							});
452
453						}
454						else {
455
456							if (giftcard) {
457								giftcard.detach();
458							}
459
460						}
461					});
462
463				}
464
465				async function initializeCard(payments, current_form_id) {
466					const card = await payments.card();
467					await card.attach('#card-container-' + current_form_id);
468					return card;
469				}
470
471
472
473				async function initializeACH(payments) {
474					let redirectURI = 'https://development-cloud.local/421-2/';
475					let transactionId = 'wpeasypay-01';
476					const ach = await payments.ach({ redirectURI, transactionId });
477					return ach;
478				}
479
480
481
482				try {
483
484					let ach;
485					const creditCardDisabled = wpep_local_vars.disable_credit_card === true
486						|| wpep_local_vars.disable_credit_card === 1
487						|| wpep_local_vars.disable_credit_card === '1';
488					jQuery('.loader').show();
489					if (!creditCardDisabled) {
490						card = await initializeCard(payments, current_form_id);
491						jQuery('.wpep-single-form-' + current_form_id).click(async function (event) {
492							event.preventDefault();
493							var current_form_id = jQuery(this).parents('form').data('id');
494							paymentButtonClicked(event, card, current_form_id, currency);
495						});
496
497						jQuery('.wpep-wizard-form-' + current_form_id).click(async function (event) {
498							event.preventDefault();
499							var current_form_id = jQuery(this).parents('form').data('id');
500							paymentButtonClicked(event, card, current_form_id, currency);
501						});
502					}
503					jQuery('.loader').hide();
504					if (wpep_local_vars.achDebit == 'on') {
505						ach = await initializeACH(payments);
506						const achButton = document.getElementById('ach-button-' + current_form_id);
507						if (achButton) {
508						achButton.addEventListener('click', async function (event) {
509							event.preventDefault();
510
511							card = '';
512
513							const paymentForm = document.getElementById('theForm-' + current_form_id);
514							const achOptions = getACHOptions(paymentForm, current_form_id);
515							ach.addEventListener(
516								`ontokenization`, function (event) {
517									const { tokenResult, error } = event.detail;
518									if (error) {
519										// add code here to handle errors
520									}
521									else if (tokenResult.status === `OK`) {
522										handlePaymentMethodSubmission(event, ach, current_form_id, currency, tokenResult.token, 'ach', achOptions);
523									}
524								}
525							);
526							var res = paymentButtonClicked(event, card, current_form_id, currency);
527							if (res || wpep_local_vars.wpep_show_wizard == 'on') {
528								await handlePaymentMethodSubmission(event, ach, current_form_id, currency, false, 'ach', achOptions);
529								// ACH with the `accountHolderName` as an option.
530							}
531						});
532						}
533					}
534
535
536				} catch (e) {
537
538					console.error('Initializing Card failed', e);
539					return;
540
541				}
542
543			}
544		);
545	}
546
547	function validateRecaptcha(current_form_id) {
548		// NEW: Check for new captcha provider system first
549		var captcha_provider = wpep_local_vars.captcha_provider || 'recaptcha';
550
551		// If none is selected, skip validation
552		if (captcha_provider === 'none' || !captcha_provider) {
553			return true;
554		}
555
556		// reCAPTCHA validation
557		if (captcha_provider === 'recaptcha') {
558			// Backward compatibility: also check old enable_recaptcha option
559			if (wpep_local_vars.enable_recaptcha === 'on' || captcha_provider === 'recaptcha') {
560				var recaptcha_val = (wpep_local_vars.recaptcha_version === 'v2')
561					? (typeof grecaptcha !== 'undefined' ? grecaptcha.getResponse() : '')
562					: jQuery('#g-recaptcha-response').val();
563
564				if (!recaptcha_val || recaptcha_val.length === 0) {
565					jQuery("#theForm-" + current_form_id + " .paymentsBlocks-" + current_form_id)
566						.prepend('<div class="wpep-alert wpep-alert-danger wpep-alert-dismissable"><a href="#" data-dismiss="alert" class="wpep-alert-close">×</a>Please verify that you are not a robot.</div>');
567					jQuery('.wpepLoader').remove();
568					return false;
569				}
570				recaptcha = recaptcha_val; // Update global variable
571				return recaptcha_val;
572			}
573		}
574
575		// hCaptcha validation
576		if (captcha_provider === 'hcaptcha') {
577			var hcaptcha_response = '';
578			if (typeof hcaptcha !== 'undefined') {
579				hcaptcha_response = hcaptcha.getResponse();
580			} else {
581				// Try to get from hidden input if available
582				hcaptcha_response = jQuery('textarea[name="h-captcha-response"]').val() || '';
583			}
584
585			if (!hcaptcha_response || hcaptcha_response.length === 0) {
586				jQuery("#theForm-" + current_form_id + " .paymentsBlocks-" + current_form_id)
587					.prepend('<div class="wpep-alert wpep-alert-danger wpep-alert-dismissable"><a href="#" data-dismiss="alert" class="wpep-alert-close">×</a>Please verify that you are not a robot.</div>');
588				jQuery('.wpepLoader').remove();
589				return false;
590			}
591			recaptcha = hcaptcha_response; // Update global variable
592			return hcaptcha_response;
593		}
594
595		// Turnstile validation — token must belong to this WPEP form only.
596		if (captcha_provider === 'turnstile') {
597			var turnstile_response = jQuery("#theForm-" + current_form_id).find('input[name="cf-turnstile-response"]').val() || '';
598
599			if (!turnstile_response || turnstile_response.length === 0) {
600				jQuery("#theForm-" + current_form_id + " .paymentsBlocks-" + current_form_id)
601					.prepend('<div class="wpep-alert wpep-alert-danger wpep-alert-dismissable"><a href="#" data-dismiss="alert" class="wpep-alert-close">×</a>Please verify that you are not a robot.</div>');
602				jQuery('.wpepLoader').remove();
603				return false;
604			}
605			recaptcha = turnstile_response; // Update global variable
606			return true; // Return true for success
607		}
608
609		// OLD: Backward compatibility for old enable_recaptcha option
610		if (wpep_local_vars.enable_recaptcha === 'on') {
611			var recaptcha_val = (wpep_local_vars.recaptcha_version === 'v2')
612				? (typeof grecaptcha !== 'undefined' ? grecaptcha.getResponse() : '')
613				: jQuery('#g-recaptcha-response').val();
614
615			if (!recaptcha_val || recaptcha_val.length === 0) {
616				jQuery("#theForm-" + current_form_id + " .paymentsBlocks-" + current_form_id)
617					.prepend('<div class="wpep-alert wpep-alert-danger wpep-alert-dismissable"><a href="#" data-dismiss="alert" class="wpep-alert-close">×</a>Please verify that you are not a robot.</div>');
618				jQuery('.wpepLoader').remove();
619				return false;
620			}
621			recaptcha = recaptcha_val; // Update global variable
622			return true; // Return true for success
623		}
624
625		return true;
626	}
627
628	jQuery('#terminialpay-button').on('click', function (e) {
629		e.preventDefault();
630		card = '';
631		var current_form_id = jQuery(this).parents('form').data('id');
632		var first_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-first-name-field']").val();
633		var last_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-last-name-field']").val();
634		var email = jQuery("#theForm-" + current_form_id + " input[name='wpep-email-field']").val();
635
636		currency = jQuery('.wpep_payment_form').data('currency');
637		var res = paymentButtonClicked(event, card, current_form_id, currency);
638
639		if (!validateRecaptcha(current_form_id)) {
640			return;
641		}
642
643		if (res) {
644			var amount = jQuery('#amount_display_' + current_form_id).text();
645			amount = amount.trim();
646			amount = amount.replace(wpep_local_vars.wpep_currency_symbol, "");
647			var adata = {
648				action: 'wpep_pay_pos_terminal',
649				id: current_form_id,
650				first_name: first_name,
651				last_name: last_name,
652				last_name: email,
653				amount: amount,
654			}
655			jQuery.ajax({
656				url: wpep_local_vars.ajax_url,
657				type: "POST",
658				dataType: "json",
659				data: adata,
660				success: function (response) {
661					jQuery('#terminialpay-button').prop('disabled', true);
662					jQuery('#terminialpay-button').prop('disabled', true).css('cursor', 'not-allowed');
663					jQuery('.loader').show();
664					var aj_status = 0;
665					var refreshId = setInterval(function () {
666						aj_status = aj_status + 1;
667						var formData = {
668							action: 'wpep_check_pay_terminal',
669							checkout_id: response.checkout.id,
670							t_status: response.checkout.status,
671							id: current_form_id,
672						}
673						jQuery.ajax({
674							url: wpep_local_vars.ajax_url,
675							'type': 'GET',
676							'data': formData,
677							'success': function (response) {
678								var response_json = JSON.parse(response);
679
680								if (response_json.result_info.checkout.status == 'COMPLETED') {
681									clearInterval(refreshId);
682
683									jQuery(`#theForm-${current_form_id}`).append(`<input type="hidden" id="wpep-checkout-id-${current_form_id}" name="wpep-checkout-id-${current_form_id}" value="${response_json.result_info.checkout.id}" />`);
684
685									var token = 'cnon:customer-card-id-ok';
686									createPayment(token, current_form_id, currency, false, false, recaptcha);
687
688									// completepym(refreshId);
689								} else {
690									console.error('Card id error: ', response_json.result_info.checkout.status);
691									this.disabled = false;
692									aj_status = 0;
693								}
694							},
695						})
696					}, 5000)
697				}
698			});
699		}
700	});
701	function getBillingContact(form, current_form_id) {
702		return {
703			givenName: jQuery("#theForm-" + current_form_id + " input[name='wpep-first-name-field']").val(),
704			familyName: jQuery("#theForm-" + current_form_id + " input[name='wpep-last-name-field']").val(),
705		};
706	}
707
708	function getACHOptions(form, current_form_id) {
709		var amount = jQuery('#amount_display_' + current_form_id).text();
710		if (wpep_local_vars.currencySymbolType == 'code') {
711			amount = amount.trim();
712			amount = amount.split(' ');
713			amount = amount[0];
714			amount = amount.replace(wpep_local_vars.wpep_square_currency_new + " ", "");
715		} else {
716			amount = amount.trim();
717			amount = amount.split(' ');
718			amount = amount[0];
719			amount = amount.replace(wpep_local_vars.wpep_currency_symbol, "");
720		}
721		amount = parseFloat(amount.replace(",", ""));
722		const billingContact = getBillingContact(form, current_form_id);
723		const accountHolderName = `${billingContact.givenName} ${billingContact.familyName}`;
724		return {
725			accountHolderName,
726			intent: 'CHARGE',
727			total: {
728				amount: amount * 100,
729				currencyCode: wpep_local_vars.wpep_square_currency_new
730			},
731		};
732	}
733
734
735	function send_payment_request(data, current_form_id) {
736		jQuery.post(
737			wpep_local_vars.ajax_url,
738			data,
739			function (response) {
740
741				var json_response = JSON.parse(response);
742
743				if ('success' == json_response.status) {
744
745					var form_id = current_form_id;
746					var current = jQuery('form[data-id="' + form_id + '"]');
747					var next = jQuery('form[data-id="' + form_id + '"]');
748					var currentActiveStep = current.find('.form-wizard-steps .active');
749					next.find('.wizard-fieldset').removeClass("show", "400");
750					currentActiveStep.removeClass('active').addClass('activated').next().addClass('active', "400");
751					next.find('.wizard-fieldset.orderCompleted').addClass("show wpep-ptb-150", "400");
752					next.find('.wpep-popup').addClass('completed');
753					next.find('.wizard-fieldset.orderCompleted').siblings().remove();
754
755					jQuery('html, body').animate(
756						{
757							scrollTop: jQuery("#theForm-" + form_id).offset().top - 50
758						},
759						800,
760						function () {
761							window.location.hash = '#';
762						}
763					);
764					if (current.data('redirection') == 'http://Yes' || current.data('redirection') == 'Yes') {
765						var counter = parseInt(current.data('delay'));
766
767						current.find('#counter').text(counter);
768
769						if (current.data('redirectionurl') != '') {
770
771							setInterval(
772								function () {
773									counter--;
774									if (counter >= 0) {
775										span = document.getElementById("counter-" + form_id);
776										span.innerHTML = counter;
777									}
778
779									if (counter === 0) {
780										window.location.href = current.data('redirectionurl');
781										clearInterval(counter);
782									}
783
784								},
785								1000
786							);
787
788						} else {
789
790							setInterval(
791								function () {
792									counter--;
793									if (counter >= 0) {
794										span = document.getElementById("counter-" + form_id);
795										span.innerHTML = counter;
796									}
797
798									if (counter === 0) {
799										location.reload();
800										clearInterval(counter);
801									}
802
803								},
804								1000
805							);
806						}
807					} else {
808						current.find('small.counterText').remove();
809					}
810
811				} else {
812
813					var json_response = JSON.parse(response);
814
815					jQuery("#theForm-" + current_form_id + " .paymentsBlocks-" + current_form_id).prepend('<div class="wpep-alert wpep-alert-danger wpep-alert-dismissable"><a href="#" data-dismiss="alert" class="wpep-alert-close">×</a>' + json_response.detail + '</div>');
816					jQuery('html, body').animate(
817						{
818							scrollTop: jQuery("#theForm-" + current_form_id + " .paymentsBlocks-" + current_form_id).offset().top
819						},
820						800,
821						function () {
822							window.location.hash = '#';
823						}
824					);
825
826				}
827			}
828		).done(
829			function () {
830				jQuery('.wpepLoader').remove();
831			}
832		);
833
834	}
835
836	// Call this function to send a payment token, buyer name, and other details
837	// to the project server code so that a payment can be created with 
838	// Payments API
839	async function createPayment(token, current_form_id, currency, cof, verifyToken = false, recaptcha) {
840		var first_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-first-name-field']").val();
841		var last_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-last-name-field']").val();
842		var email = jQuery("#theForm-" + current_form_id + " input[name='wpep-email-field']").val();
843		var currencies = ['CAD', 'USD', 'EUR', 'JPY', 'AUD', 'GBP'];
844		var currency_symbols = ['C$', 'A$', '¥', '£', '€', '$'];
845		var amount = jQuery('#amount_display_' + current_form_id).text();
846		if (jQuery.inArray(currency, currencies) !== -1) {
847			if (wpep_local_vars.currencySymbolType == 'code') {
848				amount = amount.trim();
849				amount = amount.split(' ');
850				amount = amount[0];
851				amount = amount.replace(currency + " ", "");
852			} else {
853				amount = amount.trim();
854				amount = amount.split(' ');
855				amount = amount[0];
856				amount = amount.replace(wpep_local_vars.wpep_currency_symbol, "");
857			}
858		}
859
860		var payment_type = jQuery('#wpep_payment_form_type_' + current_form_id).val();
861		var payment_source = jQuery('.tab-content-' + current_form_id + '.current').attr('id');
862		var form_values = [];
863		var selectedCheckbox = [];
864		var checkLabel = '';
865
866
867		if (jQuery('#theForm-' + current_form_id).find('input[type="checkbox"]').length > 0) {
868			var checkboxName = jQuery('#theForm-' + current_form_id + ' input[type="checkbox"]').attr('name');
869			if (checkboxName != undefined) {
870				jQuery('form[data-id="' + current_form_id + '"] input[name="' + checkboxName + '"]').each(
871					function () {
872						checkLabel = jQuery(this).data('main-label');
873						if (jQuery(this).is(':checked')) {
874							selectedCheckbox.push(jQuery(this).val());
875						}
876					}
877				);
878			}
879
880		}
881
882		form_values.push(
883			{
884				label: checkLabel,
885				value: selectedCheckbox.join(", ")
886			});
887
888		var product_label = [];
889		var product_price = [];
890		var product_qty = [];
891		var product_cost = [];
892		var product_id = [];
893		if (jQuery('.product_label').length > 0) {
894			jQuery('.product_label').each(
895				function (key, value) {
896					var item_display = jQuery(this).closest('.wpItem').css('display') == 'none' ? 'no' : 'yes';
897					if ('yes' == item_display) {
898						product_label.push(jQuery(value).text());
899					}
900				}
901			);
902			jQuery('.price').each(
903				function (key, value) {
904
905					var item_display = jQuery(this).closest('.wpItem').css('display') == 'none' ? 'no' : 'yes';
906
907					if ('yes' == item_display) {
908						product_price.push(jQuery(value).val());
909					}
910				}
911			);
912			jQuery('.qty').each(
913				function (key, value) {
914					var item_display = jQuery(this).closest('.wpItem').css('display') == 'none' ? 'no' : 'yes';
915
916					if ('yes' == item_display) {
917						if ('' !== jQuery(value).val()) {
918							product_qty.push(jQuery(value).val());
919						}
920					}
921				}
922			);
923			jQuery('.cost').each(
924				function (key, value) {
925					var item_display = jQuery(this).closest('.wpItem').css('display') == 'none' ? 'no' : 'yes';
926					if ('yes' == item_display) {
927						product_cost.push(jQuery(value).val());
928					}
929				}
930			);
931			jQuery('.wpep_square_product_id').each(
932				function (key, value) {
933					var item_display = jQuery(this).closest('.wpItem').css('display') == 'none' ? 'no' : 'yes';
934					if ('yes' == item_display) {
935						product_id.push(jQuery(value).val());
936					}
937				}
938			);
939		} else if (jQuery('.subscriptionPlan').length > 0) {
940			if (jQuery('.radio_amount').length > 0) {
941				product_label.push(jQuery('input[name="radio-name"]:checked').attr("data-label"));
942				product_price.push(jQuery('input[name="radio-name"]:checked').val());
943				var p_price = jQuery('input[name="radio-name"]:checked').val() * jQuery('#wpep_quantity_' + current_form_id).val();
944				product_cost.push(p_price);
945				if (undefined != jQuery('#wpep_quantity_' + current_form_id).val()) {
946					product_qty.push(jQuery('#wpep_quantity_' + current_form_id).val());
947				} else {
948					product_qty.push(1);
949				}
950			}
951		} else if (jQuery('.paynowDrop').length > 0) {
952			if (jQuery('.custom-option').length > 0) {
953				jQuery('.custom-option').each(
954					function (key, value) {
955						if (jQuery(value).hasClass('selection')) {
956							product_label.push(jQuery(value).text());
957							var p_price = jQuery(value).attr("data-value") * jQuery('#wpep_quantity_' + current_form_id).val();
958							product_price.push(jQuery(value).attr("data-value"));
959							product_cost.push(p_price);
960							if (undefined != jQuery('#wpep_quantity_' + current_form_id).val()) {
961								product_qty.push(jQuery('#wpep_quantity_' + current_form_id).val());
962							} else {
963								product_qty.push(1);
964							}
965						}
966					}
967				);
968			}
969		} else if (jQuery('.paymentSelect').length > 0) {
970			var cc;
971			if (wpep_local_vars.currencySymbolType == 'code') {
972				cc = wpep_local_vars.wpep_square_currency_new;
973			} else {
974				cc = wpep_local_vars.wpep_currency_symbol;
975			}
976			if (jQuery('.selection').length > 0) {
977				product_label.push('Custom Amount');
978				var p_price = jQuery("label[for='" + jQuery("input[name='doller']:checked").attr("id") + "']").text().trim()
979				var pp_price = p_price.replace('$', '');
980				var p_cost = parseFloat(pp_price) * parseFloat(jQuery('#wpep_quantity_' + current_form_id).val());
981
982				var otherAmountCost = jQuery('input#gross_total-' + current_form_id).val().replace(/,/g, "");
983
984				if (pp_price == 'Other' || pp_price == '') {
985					product_price.push(otherAmountCost);
986					product_cost.push(p_cost);
987				} else {
988					product_price.push(pp_price);
989					product_cost.push(p_cost);
990				}
991
992				if (undefined != jQuery('#wpep_quantity_' + current_form_id).val()) {
993					product_qty.push(jQuery('#wpep_quantity_' + current_form_id).val());
994				} else {
995					product_qty.push(1);
996				}
997			}
998		}
999		var products_data = {};
1000		jQuery.each(
1001			product_label,
1002			function (key, value) {
1003
1004				var tmp_product_data = {};
1005				tmp_product_data.label = product_label[key];
1006				tmp_product_data.quantity = product_qty[key];
1007				tmp_product_data.price = product_price[key];
1008				tmp_product_data.cost = product_cost[key];
1009				tmp_product_data.id = product_id[key];
1010
1011				products_data[key] = tmp_product_data;
1012
1013			}
1014		);
1015
1016		products_data = JSON.stringify(products_data);
1017
1018		if (jQuery('#theForm-' + current_form_id).find('.wpep-form-radio-btn').length > 0) {
1019			var radioName = jQuery('#theForm-' + current_form_id + ' .wpep-form-radio-btn').attr('name');
1020			if (radioName != undefined) {
1021				jQuery('form[data-id="' + current_form_id + '"] .wpep-form-radio-btn').each(
1022					function () {
1023
1024						if (jQuery(this).is(':checked')) {
1025							form_values.push(
1026								{
1027									label: jQuery(this).data('main-label'),
1028									value: jQuery(this).val()
1029								}
1030							);
1031						}
1032
1033					}
1034				);
1035			}
1036		}
1037
1038		form_values.push(
1039			{
1040				label: 'Line Items',
1041				value: products_data
1042			}
1043		);
1044
1045
1046		jQuery('.radio_amount').each(function () {
1047
1048			if (jQuery(this).is(':checked')) {
1049
1050				form_values.push(
1051					{
1052						label: jQuery(this).data('label'),
1053						value: jQuery(this).val()
1054					}
1055				);
1056
1057			}
1058
1059		});
1060
1061		jQuery('form[data-id="' + current_form_id + '"] input[type="date"]').each(
1062			function () {
1063
1064				if (jQuery(this).data('label') !== '' && typeof jQuery(this).data('label') !== 'undefined') {
1065					form_values.push(
1066						{
1067							label: jQuery(this).data('label'),
1068							value: jQuery(this).val()
1069						}
1070					);
1071				}
1072
1073			}
1074		);
1075
1076		jQuery('form[data-id="' + current_form_id + '"] input[type="number"]').each(
1077			function () {
1078				if (jQuery(this).data('label') !== '' && typeof jQuery(this).data('label') !== 'undefined') {
1079					form_values.push(
1080						{
1081							label: jQuery(this).data('label'),
1082							value: jQuery(this).val()
1083						}
1084					);
1085				}
1086			}
1087		);
1088
1089		jQuery('form[data-id="' + current_form_id + '"] select').each(
1090			function () {
1091
1092				var selMulti = jQuery.map(
1093					jQuery('form[data-id="' + current_form_id + '"] select option:selected'),
1094					function (el, i) {
1095						return jQuery(el).text();
1096					}
1097				);
1098
1099				if (jQuery(this).data('label') !== '' && typeof jQuery(this).data('label') !== 'undefined') {
1100					form_values.push(
1101						{
1102							label: jQuery(this).data('label'),
1103							value: selMulti.join(", ")
1104						}
1105					);
1106				}
1107
1108			}
1109		);
1110
1111		jQuery('form[data-id="' + current_form_id + '"] input[type="text"]').each(
1112			function () {
1113
1114				if (jQuery(this).data('label') !== '' && typeof jQuery(this).data('label') !== 'undefined') {
1115					form_values.push(
1116						{
1117							label: jQuery(this).data('label'),
1118							value: jQuery(this).val()
1119						}
1120					);
1121				}
1122			}
1123		);
1124
1125		jQuery('form[data-id="' + current_form_id + '"] textarea').each(
1126			function () {
1127
1128				if (jQuery(this).data('label') !== '' && typeof jQuery(this).data('label') !== 'undefined') {
1129					form_values.push(
1130						{
1131							label: jQuery(this).data('label'),
1132							value: jQuery(this).val()
1133						}
1134					);
1135				}
1136
1137			}
1138		);
1139
1140		jQuery('form[data-id="' + current_form_id + '"] input[type="email"]').each(
1141			function () {
1142
1143				if (jQuery(this).data('label') !== '' && typeof jQuery(this).data('label') !== 'undefined') {
1144					form_values.push(
1145						{
1146							label: jQuery(this).data('label'),
1147							value: jQuery(this).val()
1148						}
1149					);
1150				}
1151
1152			}
1153		);
1154
1155		jQuery('form[data-id="' + current_form_id + '"] input[type="tel"]').each(
1156			function () {
1157				if (jQuery(this).data('label') !== '' && typeof jQuery(this).data('label') !== 'undefined') {
1158					form_values.push(
1159						{
1160							label: jQuery(this).data('label'),
1161							value: jQuery(this).val()
1162						}
1163					);
1164				}
1165			}
1166		);
1167
1168		jQuery('form[data-id="' + current_form_id + '"] input[type="password"]').each(
1169			function () {
1170				if (jQuery(this).data('label') !== '' && typeof jQuery(this).data('label') !== 'undefined') {
1171					form_values.push(
1172						{
1173							label: jQuery(this).data('label'),
1174							value: jQuery(this).val()
1175						}
1176					);
1177				}
1178			}
1179		);
1180
1181		jQuery('form[data-id="' + current_form_id + '"] input[type="color"]').each(
1182			function () {
1183				if (jQuery(this).data('label') !== '' && typeof jQuery(this).data('label') !== 'undefined') {
1184					form_values.push(
1185						{
1186							label: jQuery(this).data('label'),
1187							value: jQuery(this).val()
1188						}
1189					);
1190				}
1191			}
1192		);
1193		var amount_display = jQuery('#amount_display_' + current_form_id).text();
1194		var amount_display_neat = amount_display.replace(/\s/g, '');
1195		form_values.push(
1196			{
1197				label: 'total_amount',
1198				value: amount_display_neat
1199			}
1200		);
1201
1202		var quantity_id = '#wpep_quantity_' + current_form_id;
1203		if (undefined != jQuery(quantity_id).val()) {
1204			form_values.push(
1205				{
1206					label: 'quantity',
1207					value: jQuery(quantity_id).val()
1208				}
1209			);
1210		}
1211		// check if discount applied or not
1212		if (jQuery(`#theForm-${current_form_id} input[name="wpep-discount"]`).length > 0) {
1213			var discount = jQuery(`#theForm-${current_form_id} input[name="wpep-discount"]`).val();
1214		} else {
1215			var discount = 0;
1216		}
1217		// var recaptcha = '';
1218		// if(wpep_local_vars.enable_recaptcha == 'on' && wpep_local_vars.recaptcha_version == 'v2'){
1219		// 	var recaptcha = grecaptcha.getResponse()
1220		// }
1221		// else if(wpep_local_vars.enable_recaptcha == 'on' && wpep_local_vars.recaptcha_version == 'v3'){
1222		// 	var recaptcha = jQuery('#wpep_recaptcha').val();
1223
1224		// }
1225
1226		wpepValidateFormSubmitButton();
1227
1228		var data = {
1229			'action': 'wpep_payment_request',
1230			'nonce': token,
1231			'first_name': first_name,
1232			'last_name': last_name,
1233			'email': email,
1234			'discount': discount,
1235			'amount': amount,
1236			'save_card': jQuery('#saveCardLater').is(':checked'),
1237			'save_customer_id': jQuery('#wpep_square_customer_id').val(),
1238			'payment_type': payment_type,
1239			'payment_source': payment_source,
1240			'payment_tcheckoutid': jQuery('#wpep-checkout-id-' + current_form_id).val(),
1241			'current_form_id': current_form_id,
1242			'form_values': form_values,
1243			'currency': currency,
1244			'card_on_file': cof,
1245			'buyer_verification': verifyToken,
1246			'wpep_payment_nonce': wpepGetPaymentNonce(current_form_id),
1247			'wp_payment_nonce': wpepGetPaymentNonce(current_form_id),
1248			'wp_payment_recapcha': recaptcha
1249		};
1250
1251		if (wpep_local_vars.wpep_square_amount_type == 'tabular_layout_for_square') {
1252			var square_product_validation = {
1253				'action': 'wpep_square_product_validation_request',
1254				'form_values': form_values,
1255				'form_id': current_form_id,
1256				'wpep_payment_nonce': wpepGetPaymentNonce(current_form_id),
1257				'wp_payment_nonce': wpepGetPaymentNonce(current_form_id),
1258			};
1259			jQuery.ajax({
1260				url: wpep_local_vars.ajax_url,
1261				type: 'post',
1262				data: square_product_validation,
1263				success: function (response) {
1264					var square_pro_validation = JSON.parse(response);
1265					if (square_pro_validation.status == 'success') {
1266						if (undefined !== jQuery('#wpep_file_upload_field')[0]) {
1267							var files = jQuery('#wpep_file_upload_field')[0].files;
1268
1269							if (undefined !== files && files.length > 0) {
1270								var fd = new FormData();
1271								for (var index = 0; index < files.length; index++) {
1272									fd.append('file[]', files[index]);
1273								}
1274								fd.append('file_upload', 'true');
1275								fd.append('action', 'wpep_file_upload');
1276								fd.append('wpep_payment_nonce', wpepGetPaymentNonce(current_form_id));
1277								fd.append('wp_payment_nonce', wpepGetPaymentNonce(current_form_id));
1278
1279								jQuery.ajax({
1280									url: wpep_local_vars.ajax_url,
1281									type: 'post',
1282									data: fd,
1283									contentType: false,
1284									processData: false,
1285									success: function (response) {
1286										var parsed_response = JSON.parse(response);
1287										if (parsed_response.hasOwnProperty('error')) {
1288											jQuery("#theForm-" + current_form_id + " .paymentsBlocks-" + current_form_id).prepend('<div class="wpep-alert wpep-alert-danger wpep-alert-dismissable"><a href="#" data-dismiss="alert" class="wpep-alert-close">×</a>' + parsed_response.error + '</div>');
1289											jQuery('.wpepLoader').remove();
1290
1291										} else {
1292											var uploadedUrls = parsed_response.uploaded_file_urls || [];
1293											if (uploadedUrls.length === 0 && parsed_response.uploaded_file_url) {
1294												uploadedUrls = [parsed_response.uploaded_file_url];
1295											}
1296											wpep_file_upload_url(uploadedUrls);
1297											saveFileUploadUrlToSession(uploadedUrls, data, current_form_id);
1298										}
1299									}
1300								});
1301							} else {
1302								send_payment_request(data, current_form_id);
1303							}
1304						} else {
1305							send_payment_request(data, current_form_id);
1306						}
1307					} else {
1308						jQuery.each(square_pro_validation.result, function (productId, details) {
1309							if (details.status == 'failed') {
1310								jQuery('#stock_' + productId).html('');
1311								if (details.stock == 0) {
1312									jQuery('#stock_' + productId).html('Out of stock');
1313								} else {
1314									jQuery('#stock_' + productId).html('Available stock count (' + details.stock + ')');
1315								}
1316								jQuery('#stock_' + productId).show();
1317							} else {
1318								jQuery('#stock_' + productId).html('');
1319								jQuery('#stock_' + productId).hide();
1320							}
1321						})
1322						jQuery('html, body').animate(
1323							{
1324								scrollTop: jQuery("#theForm-" + current_form_id + " .shopping-cart").offset().top
1325							},
1326							800,
1327							function () {
1328								window.location.hash = '#';
1329							}
1330						);
1331						jQuery('.wpepLoader').remove();
1332					}
1333				}
1334			});
1335		} else {
1336			if (undefined !== jQuery('#wpep_file_upload_field')[0]) {
1337				var files = jQuery('#wpep_file_upload_field')[0].files;
1338
1339				if (undefined !== files && files.length > 0) {
1340					var fd = new FormData();
1341					for (var index = 0; index < files.length; index++) {
1342						fd.append('file[]', files[index]);
1343					}
1344					fd.append('file_upload', 'true');
1345					fd.append('action', 'wpep_file_upload');
1346					fd.append('wpep_payment_nonce', wpepGetPaymentNonce(current_form_id));
1347					fd.append('wp_payment_nonce', wpepGetPaymentNonce(current_form_id));
1348
1349					jQuery.ajax({
1350						url: wpep_local_vars.ajax_url,
1351						type: 'post',
1352						data: fd,
1353						contentType: false,
1354						processData: false,
1355						success: function (response) {
1356							var parsed_response = JSON.parse(response);
1357							if (parsed_response.hasOwnProperty('error')) {
1358								jQuery("#theForm-" + current_form_id + " .paymentsBlocks-" + current_form_id).prepend('<div class="wpep-alert wpep-alert-danger wpep-alert-dismissable"><a href="#" data-dismiss="alert" class="wpep-alert-close">×</a>' + parsed_response.error + '</div>');
1359								jQuery('.wpepLoader').remove();
1360
1361							} else {
1362								var uploadedUrls = parsed_response.uploaded_file_urls || [];
1363								if (uploadedUrls.length === 0 && parsed_response.uploaded_file_url) {
1364									uploadedUrls = [parsed_response.uploaded_file_url];
1365								}
1366								wpep_file_upload_url(uploadedUrls);
1367								saveFileUploadUrlToSession(uploadedUrls, data, current_form_id);
1368							}
1369						}
1370					});
1371				} else {
1372					send_payment_request(data, current_form_id);
1373				}
1374			} else {
1375				send_payment_request(data, current_form_id);
1376			}
1377		}
1378
1379		function saveFileUploadUrlToSession(fileUrl, data, formId) {
1380			jQuery.ajax({
1381				url: wpep_local_vars.ajax_url,
1382				type: 'post',
1383				data: {
1384					action: 'wpep_save_file_upload_url',
1385					file_url: fileUrl,
1386					data: data,
1387					form_id: formId
1388				},
1389				success: function (response) {
1390					send_payment_request(data, formId);
1391				}
1392			});
1393		}
1394		function wpep_file_upload_url(urls) {
1395			var uploadedUrlValue = urls;
1396			if (Array.isArray(urls)) {
1397				uploadedUrlValue = urls.join(', ');
1398			}
1399			form_values.push(
1400				{
1401					label: 'Uploaded URL',
1402					value: uploadedUrlValue
1403				}
1404			);
1405		}
1406
1407
1408	}
1409
1410
1411
1412
1413	// This function tokenizes a payment method. 
1414	// The ‘error’ thrown from this async function denotes a failed tokenization,
1415	// which is due to buyer error (such as an expired card). It is up to the
1416	// developer to handle the error and provide the buyer the chance to fix
1417	// their mistakes.
1418	async function tokenize(paymentMethod, current_form_id, method, options = false) {
1419
1420		var amount = jQuery('input[name="wpep-selected-amount"]').val();
1421
1422		if (isNaN(amount)) {
1423			amount = amount.replace(wpep_local_vars.wpep_currency_symbol, "");
1424		}
1425
1426		var first_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-first-name-field']").val();
1427		var last_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-last-name-field']").val();
1428		var email = jQuery("#theForm-" + current_form_id + " input[name='wpep-email-field']").val();
1429		var payment_type = jQuery('#wpep_payment_form_type_' + current_form_id).val();
1430		var save_card_later = jQuery('#saveCardLater').is(':checked');
1431
1432		if (payment_type == 'subscription' || save_card_later == true) {
1433			var intent = 'STORE';
1434		} else {
1435			var intent = 'CHARGE';
1436		}
1437
1438		var amountText = jQuery('small.display').text();
1439		var amountValue = amountText.match(/[\d,.]+/)[0];
1440
1441		const verificationDetails = {
1442			billingContact: {
1443				familyName: last_name,
1444				givenName: first_name,
1445				email: email,
1446			},
1447			intent: intent,
1448			customerInitiated: true,
1449			sellerKeyedIn: false,
1450		};
1451		if (intent === 'CHARGE') {
1452			verificationDetails.amount = amountValue.replace(/,/g, "")
1453			verificationDetails.currencyCode = wpep_local_vars.wpep_square_currency_new;
1454		}
1455
1456		let tokenResult;
1457		if (method === 'ach') {
1458			tokenResult = await paymentMethod.tokenize(options);
1459		} else {
1460			tokenResult = await paymentMethod.tokenize(verificationDetails);
1461		}
1462		// const tokenResult = await paymentMethod.tokenize(verificationDetails);
1463
1464		if (tokenResult.status === 'OK') {
1465			return tokenResult.token;
1466		} else {
1467			let errorMessage = `Tokenization failed-status: ${tokenResult.status}`;
1468			if (tokenResult.errors) {
1469				errorMessage += ` and errors: ${JSON.stringify(
1470					tokenResult.errors
1471				)}`;
1472			}
1473			jQuery('.wpepLoader').remove();
1474			throw new Error(errorMessage);
1475		}
1476	}
1477
1478	async function handlePaymentMethodSubmission(event, paymentMethod, current_form_id, currency, token = false, method = null, achOptions = null) {
1479
1480		jQuery("#theForm-" + current_form_id).append(jQuery('<div />').attr('class', 'wpepLoader').html('<div class="initial-load-animation"><div class="payment-image icomoonLib"><span class="icon-pay"></span></div><div class="loading-bar"><div class="blue-bar"></div></div></div>'));
1481		if (method === null && method !== 'cashapp') {
1482			event.preventDefault();
1483		}
1484
1485		if (!validateRecaptcha(current_form_id)) {
1486			return;
1487		}
1488
1489		try {
1490
1491			var amount = jQuery('input[name="wpep-selected-amount"]').val();
1492
1493			if (isNaN(amount)) {
1494				amount = amount.replace(wpep_local_vars.wpep_currency_symbols, "");
1495			}
1496
1497			var first_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-first-name-field']").val();
1498			var last_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-last-name-field']").val();
1499			var email = jQuery("#theForm-" + current_form_id + " input[name='wpep-email-field']").val();
1500			var payment_type = jQuery('#wpep_payment_form_type_' + current_form_id).val();
1501			var save_card_later = jQuery('#saveCardLater').is(':checked');
1502
1503			if (payment_type == 'subscription' || save_card_later == true) {
1504				var intent = 'STORE';
1505			} else {
1506				var intent = 'CHARGE';
1507			}
1508
1509			if (!token) {
1510				if (method === 'ach') {
1511					tokenize(paymentMethod, current_form_id, method, achOptions).then(token => {
1512						createPayment(token, current_form_id, currency, false, false, recaptcha);
1513					});
1514				} else {
1515					tokenize(paymentMethod, current_form_id, method).then(token => {
1516						verifyBuyer(payments, token, amount, currency, intent, first_name, last_name, email).then(verifyToken => {
1517							createPayment(token, current_form_id, currency, false, verifyToken, recaptcha);
1518						});
1519					});
1520				}
1521
1522
1523			} else {
1524				verifyBuyer(payments, token, amount, currency, intent, first_name, last_name, email).then(verifyToken => {
1525					createPayment(token, current_form_id, currency, false, verifyToken, recaptcha);
1526				});
1527
1528			}
1529
1530
1531		} catch (e) {
1532			console.log(e)
1533		}
1534		if (jQuery('#afterpay-' + current_form_id).is(':visible')) {
1535			if (afterpay) {
1536				const afterpayButton = document.getElementById('afterpay-button');
1537				afterpayButton.addEventListener('click', async function (event) {
1538					await handlePaymentMethodSubmission(event, afterpay, current_form_id, currency, false);
1539				});
1540			}
1541		}
1542	}
1543
1544	async function handlePaymentMethodSubmissiongftcpay(event, paymentMethod, current_form_id, currency) {
1545
1546		jQuery("#theForm-" + current_form_id).append(jQuery('<div />').attr('class', 'wpepLoader').html('<div class="initial-load-animation"><div class="payment-image icomoonLib"><span class="icon-pay"></span></div><div class="loading-bar"><div class="blue-bar"></div></div></div>'));
1547
1548		if (!validateRecaptcha(current_form_id)) {
1549			return;
1550		}
1551
1552		try {
1553
1554			var amount = jQuery('input[name="wpep-selected-amount"]').val();
1555
1556			if (isNaN(amount)) {
1557				amount = amount.replace("$", "");
1558			}
1559			tokenize(paymentMethod).then(token => {
1560				createPayment(token, current_form_id, currency, false, false, recaptcha);
1561			});
1562
1563		} catch (e) {
1564			console.log(e)
1565		}
1566	}
1567
1568	async function verifyBuyer(payments, token, amount, currency, intent, first_name, last_name, email) {
1569
1570		if (isNaN(amount)) {
1571			amount = amount.replace("$", "");
1572		}
1573
1574		var currencySymbolVerifyBuyer = wpep_local_vars.wpep_square_currency_new;
1575
1576		const verificationDetails = {
1577			amount: amount.toString(),
1578			billingContact: {
1579				familyName: last_name,
1580				givenName: first_name,
1581				email: email,
1582			},
1583			currencyCode: currencySymbolVerifyBuyer,
1584			intent: intent
1585		};
1586
1587		const verificationResults = await payments.verifyBuyer(
1588			token,
1589			verificationDetails
1590		);
1591
1592		return verificationResults.token;
1593
1594	}
1595
1596	function validateEmail(email) {
1597		if (typeof email !== 'string') {
1598			return false;
1599		}
1600		const sanitizedEmail = String(email).trim().replace(/\.+$/, '');
1601		const re = /^[^\s@]+@[^\s@]+\.[a-z]{2,}(?:\.[a-z]{2,})*$/i;
1602		return re.test( sanitizedEmail );
1603	}
1604
1605
1606	function paymentButtonClicked(event, card, current_form_id, currency) {
1607
1608		jQuery('#wpep-selected-amount-' + current_form_id).val(jQuery('#amount_display_' + current_form_id).html());
1609		jQuery('#one_unit_cost').val(jQuery('#amount_display_' + current_form_id).html().trim().replace(wpep_local_vars.wpep_currency_symbol, ""));
1610		var ewallet = false;
1611		var first_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-first-name-field']").val();
1612		var last_name = jQuery("#theForm-" + current_form_id + " input[name='wpep-last-name-field']").val();
1613		var email = jQuery("#theForm-" + current_form_id + " input[name='wpep-email-field']").val();
1614
1615		if (first_name != '' && last_name != '' && email != '') {
1616			jQuery('.wpep-alert').remove();
1617		}
1618		var result1 = jQuery("#theForm-" + current_form_id + " .wizard-fieldset.show .fieldMainWrapper div.wpep-required input").filter(
1619			function () {
1620				return jQuery.trim(jQuery(this).val()).length == 0
1621			}
1622		).length == 0;
1623		// client side validation
1624		var result2 = false;
1625		var emailCheck = false;
1626		var wpepError = '';
1627		var termCond = false;
1628		jQuery("#theForm-" + current_form_id + " .wizard-fieldset.show .fieldMainWrapper div.wpep-required").each(
1629			function () {
1630
1631				var current = jQuery(this);
1632
1633				wpepError = jQuery('<span />').attr('class', 'wpepError').html('Required Field');
1634
1635				if (current.find('input[type="text"]').length > 0) {
1636
1637					if (current.find('input[type="text"]').val() == '' || current.find('input[type="text"]').val() == undefined) {
1638						if (current.find('input[type="text"] ~ .wpepError').length == 0) {
1639							jQuery(wpepError).insertAfter(current.find('input[type="text"]'));
1640						}
1641						result2 = false;
1642					} else {
1643						wpepError = '';
1644						current.find('.wpepError').remove();
1645						result2 = true;
1646					}
1647				}
1648
1649				if (current.find('textarea').length > 0) {
1650
1651					if (current.find('textarea').val() == '' || current.find('textarea').val() == undefined) {
1652						if (current.find('textarea ~ .wpepError').length == 0) {
1653							jQuery(wpepError).insertAfter(current.find('textarea'));
1654						}
1655						result2 = false;
1656					} else {
1657						wpepError = '';
1658						current.find('.wpepError').remove();
1659						result2 = true;
1660					}
1661
1662				}
1663
1664				if (current.find('select').length > 0) {
1665					if (current.find('select').val() == '' || current.find('select').val() == undefined) {
1666						if (current.find('select ~ .wpepError').length == 0) {
1667							jQuery(wpepError).insertAfter(current.find('select'));
1668						}
1669						result2 = false;
1670					} else {
1671						wpepError = '';
1672						current.find('.wpepError').remove();
1673						result2 = true;
1674					}
1675				}
1676
1677				if (current.find('input[type="number"]').length > 0) {
1678					current.find('input[type="number"]').each(function () {
1679						var numberInput = jQuery(this);
1680						var inputValue = numberInput.val();
1681						var minVal = parseInt(numberInput.attr('min'), 10);
1682						var maxVal = parseInt(numberInput.attr('max'), 10);
1683						numberInput.next('.wpepError').remove();
1684						jQuery(wpepError).addClass('num_fields_errors' + numberInput.attr('name'));
1685						if (isNaN(inputValue) || inputValue === undefined || inputValue === '') {
1686							if (current.find('input[type="number"] ~ .wpepError').length === 0) {
1687								jQuery(wpepError).insertAfter(numberInput);
1688							}
1689							result2 = false;
1690						} else if (inputValue.length < minVal) {
1691							if (current.find('input[type="number"] ~ .wpepError').length === 0) {
1692								jQuery(wpepError).insertAfter(numberInput);
1693							}
1694							jQuery('.num_fields_errors' + numberInput.attr('name')).text('Minimum value required. Min: ' + minVal);
1695							result2 = false;
1696						} else if (inputValue.length > maxVal) {
1697							if (current.find('input[type="number"] ~ .wpepError').length === 0) {
1698								jQuery(wpepError).insertAfter(numberInput);
1699							}
1700							jQuery('.num_fields_errors' + numberInput.attr('name')).text('Maximum value exceeded. Max: ' + maxVal);
1701							result2 = false;
1702						} else {
1703							wpepError = '';
1704							current.find('.wpepError').remove();
1705							result2 = true;
1706						}
1707					})
1708
1709				}
1710
1711
1712				if (current.find('input[type="password"]').length > 0) {
1713
1714					if (current.find('input[type="password"]').val() == '' || current.find('input[type="password"]').val() == undefined) {
1715						if (current.find('input[type="password"] ~ .wpepError').length == 0) {
1716							jQuery(wpepError).insertAfter(current.find('input[type="password"]'));
1717						}
1718						result2 = false;
1719						// return false;
1720					} else {
1721						wpepError = '';
1722						current.find('.wpepError').remove();
1723						result2 = true;
1724					}
1725				}
1726
1727				if (current.find('input[type="color"]').length > 0) {
1728
1729					if (current.find('input[type="color"]').val() == '' || current.find('input[type="color"]').val() == undefined) {
1730						if (current.find('input[type="color"] ~ .wpepError').length == 0) {
1731							jQuery(wpepError).insertAfter(current.find('input[type="color"]'));
1732						}
1733						result2 = false;
1734						// return false;
1735					} else {
1736						wpepError = '';
1737						current.find('.wpepError').remove();
1738						result2 = true;
1739					}
1740				}
1741
1742				if (jQuery('#theForm-' + current_form_id).find('input[type="checkbox"]').length > 0) {
1743
1744					// for checkbox input we need name because we can select atleast one at a time in group checkbox.
1745					var checkboxName = current.find('input[type="checkbox"]').attr('name');
1746
1747					if (checkboxName != undefined) {
1748						if (!(jQuery('#theForm-' + current_form_id).find('input[name="' + checkboxName + '"]').is(':checked'))) {
1749							if (jQuery('#theForm-' + current_form_id).find('input[name="' + checkboxName + '"] ~ .wpepError').length == 0) {
1750								jQuery(wpepError).insertAfter(current.find('input[name="' + checkboxName + '"]'));
1751							}
1752							result2 = false;
1753							// return false;
1754						} else {
1755							wpepError = '';
1756							jQuery('#theForm-' + current_form_id).find('input[name="' + checkboxName + '"] ~ .wpepError').remove();
1757							result2 = true;
1758						}
1759					}
1760				}
1761
1762				if (jQuery('#theForm-' + current_form_id).find('input[type="radio"]').length > 0) {
1763
1764					// for radio input we need name because we can select only one at a time.
1765					var radioName = current.find('input[type="radio"]').attr('name');
1766
1767					if (radioName != undefined) {
1768						if (!(jQuery('#theForm-' + current_form_id).find('input[name="' + radioName + '"]').is(':checked'))) {
1769							if (jQuery('#theForm-' + current_form_id).find('input[name="' + radioName + '"] ~ .wpepError').length == 0) {
1770								jQuery(wpepError).insertAfter(current.find('input[name="' + radioName + '"]'));
1771							}
1772							result2 = false;
1773						} else {
1774							wpepError = '';
1775							jQuery('#theForm-' + current_form_id).find('input[name="' + radioName + '"] ~ .wpepError').remove();
1776							result2 = true;
1777						}
1778					}
1779
1780				}
1781
1782				if (current.find('input[type="email"]').length > 0) {
1783					let wpepEmailField = current.find('input[type="email"]');
1784					if (wpepEmailField.val() == '' || wpepEmailField.val() == undefined) {
1785						if (current.find('input[type="email"] ~ .wpepError').length == 0) {
1786							jQuery(wpepError).insertAfter(wpepEmailField);
1787						}
1788						emailCheck = false;
1789					}
1790					else if (validateEmail(wpepEmailField.val()) == false) {
1791						if (wpepEmailField.siblings('.wpepError').length === 0) {
1792							jQuery(wpepError).insertAfter(wpepEmailField);
1793						}
1794						jQuery(wpepEmailField.siblings('.wpepError')).text('Please enter a valid email address.');
1795						emailCheck = false;
1796					} else {
1797						wpepError = '';
1798						current.find('.wpepError').remove();
1799						emailCheck = true;
1800					}
1801				}
1802
1803				if (current.find('input[type="date"]').length > 0) {
1804
1805					if (current.find('input[type="date"]').val() == '' || current.find('input[type="date"]').val() == undefined) {
1806
1807						if (current.find('input[type="date"] ~ .wpepError').length == 0) {
1808							jQuery(wpepError).insertAfter(current.find('input[type="date"]'));
1809						}
1810						result2 = false;
1811
1812					} else {
1813
1814						wpepError = '';
1815						current.find('.wpepError').remove();
1816						result2 = true;
1817					}
1818				}
1819
1820				if (jQuery('#theForm-' + current_form_id).find('input[type="file"]').length) {
1821
1822					let fileInput = jQuery('#theForm-' + current_form_id).find('input[type="file"]');
1823					let fileVal = fileInput.val();
1824					let isFileRequired = fileInput.prop('required');
1825					let selectedFiles = fileInput[0] && fileInput[0].files ? fileInput[0].files.length : 0;
1826
1827					if (isFileRequired && selectedFiles === 0) {
1828						if (fileInput.siblings('.wpepError').length === 0) {
1829							jQuery(wpepError).insertAfter(fileInput);
1830						}
1831						jQuery(fileInput.siblings('.wpepError')).text('Required Field');
1832						result2 = false;
1833					}
1834
1835					if (selectedFiles > 0 && fileVal !== '') {
1836						let ext = fileVal.split('.').pop().toLowerCase();
1837						let allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc'];
1838
1839						if (!allowedExts.includes(ext)) {
1840							if (fileInput.siblings('.wpepError').length === 0) {
1841								jQuery(wpepError).insertAfter(fileInput);
1842							}
1843							jQuery(fileInput.siblings('.wpepError')).text('Invalid file type. Allowed: jpg, jpeg, png, gif, pdf, doc.');
1844							result2 = false;
1845						} else {
1846							fileInput.next('.wpepError').remove();
1847						}
1848					}
1849				}
1850
1851				if (current.find('input[type="url"]').length > 0) {
1852
1853					if (current.find('input[type="url"]').val() == '' || current.find('input[type="url"]').val() == undefined) {
1854						if (current.find('input[type="url"] ~ .wpepError').length == 0) {
1855							jQuery(wpepError).insertAfter(current.find('input[type="url"]'));
1856						}
1857						result2 = false;
1858					} else {
1859						wpepError = '';
1860						current.find('.wpepError').remove();
1861						result2 = true;
1862					}
1863				}
1864
1865			}
1866		);
1867
1868		var termContainer = jQuery("#theForm-" + current_form_id + " #termsCondition-" + current_form_id).is(':checked');
1869
1870		if (termContainer == false) {
1871			if (jQuery("#theForm-" + current_form_id + " div.termsCondition.wpep-required").find('.wpepError').length == 0) {
1872				wpepError = jQuery('<span />').attr('class', 'wpepError').html('Required Field');
1873				jQuery("#theForm-" + current_form_id + " div.termsCondition.wpep-required").append(jQuery(wpepError));
1874			}
1875			termCond = false;
1876		} else {
1877			wpepError = '';
1878			jQuery("#theForm-" + current_form_id + " div.termsCondition.wpep-required").find('.wpepError').remove();
1879			termCond = true;
1880		}
1881
1882		var current = jQuery(event.target);
1883		var result3 = false;
1884		var next = jQuery(event.target);
1885		var currentActiveStep = jQuery(event.target).parents('.form-wizard').find('.form-wizard-steps .active');
1886
1887		if (jQuery('input[name="wpep-selected-amount"]').length > 0) {
1888
1889			if (jQuery('input[name="wpep-selected-amount"]').val() == '') {
1890				result3 = false;
1891
1892				return false;
1893			} else {
1894
1895				result3 = true;
1896			}
1897		}
1898
1899		var selected_payment_tab = current.parents('form').find('ul.wpep_tabs li.tab-link.current').data('tab');
1900		var finalCheck = jQuery("#theForm-" + current_form_id + " .wizard-fieldset.show .fieldMainWrapper div.wpep-required").find("span.wpepError").length;
1901
1902		// Hard stop guard: never allow submit when a required file input is empty.
1903		var requiredFileMissing = false;
1904		jQuery('#theForm-' + current_form_id).find('input[type="file"][required]').each(function () {
1905			var requiredFileInput = jQuery(this);
1906			var hasSelectedFile = this.files && this.files.length > 0;
1907			if (!hasSelectedFile) {
1908				if (requiredFileInput.siblings('.wpepError').length === 0) {
1909					jQuery('<span />').attr('class', 'wpepError').html('Required Field').insertAfter(requiredFileInput);
1910				} else {
1911					requiredFileInput.siblings('.wpepError').text('Required Field');
1912				}
1913				requiredFileMissing = true;
1914			} else {
1915				requiredFileInput.siblings('.wpepError').remove();
1916			}
1917		});
1918		if (requiredFileMissing) {
1919			result2 = false;
1920			finalCheck = 1;
1921		}
1922
1923		if (finalCheck != 0) {
1924			jQuery('.wpepLoader').remove();
1925		}
1926
1927		if (jQuery('input[name="card_on_file"]').is(':checked')) {
1928
1929			var card_on_file = jQuery('input[name="card_on_file"]').val();
1930
1931			if (finalCheck <= 0 && termCond == true) {
1932
1933				jQuery("#theForm-" + current_form_id).append(jQuery('<div />').attr('class', 'wpepLoader').html('<div class="initial-load-animation"><div class="payment-image icomoonLib"><span class="icon-pay"></span></div><div class="loading-bar"><div class="blue-bar"></div></div></div>'));
1934
1935				if (!validateRecaptcha(current_form_id)) {
1936					return;
1937				}
1938
1939				jQuery('.wpep-single-form-' + current_form_id).attr('disabled', 'disabled');
1940				jQuery('.wpep-single-form-' + current_form_id).css('cursor', 'not-allowed');
1941				jQuery('.wpep-wizard-form-' + current_form_id).css('cursor', 'not-allowed');
1942				jQuery('.wpep-wizard-form-' + current_form_id).attr('disabled', 'disabled');
1943				createPayment(false, current_form_id, currency, card_on_file, false, recaptcha);
1944
1945			}
1946
1947		} else {
1948			// if payment type is credit card
1949			creditcard = 'creditCard-' + current_form_id;
1950
1951
1952
1953			if (
1954				selected_payment_tab == creditcard
1955				&& result1 == true
1956				&& result3 == true
1957				&& wpepError == ''
1958				&& termCond == true
1959				&& finalCheck == 0
1960			) {
1961				handlePaymentMethodSubmission(event, card, current_form_id, currency);
1962			} else if (result1 == true && result2 == true && result3 == true && emailCheck == true && wpepError == '' && termCond == true && finalCheck == 0) { // if payment type is google pay
1963				return true;
1964			}
1965
1966		}
1967
1968
1969
1970	}
1971
1972
1973
1974	jQuery('.wizard-section').css('visibility', 'visible');
1975	jQuery('.parent-loader').remove();
1976
1977	// This code is only for the payment tabular layout.
1978	// On the first page load, if a quantity is already set from the backend, 
1979	// the user cannot apply a coupon because the gross_total input is not updated. 
1980	// To fix this, we manually set the gross_total input on the initial load.
1981	if (wpep_local_vars.wpep_square_amount_type == 'payment_tabular') {
1982
1983		jQuery("input.qty").each(function () {
1984			let val = parseInt(jQuery(this).val(), 10);
1985			if (val > 0) {
1986				let wpepSelectedAmountQuantity = jQuery("input[name='wpep-selected-amount']").val();
1987				jQuery('input[name="gross_total"]').val(wpepSelectedAmountQuantity).trigger('change');
1988			}
1989		});
1990
1991	}
1992
1993	jQuery("form div.qty").append('<div class="outer-button"><div class="inc btnqty"><i class="fa fa-plus"></i></div><div class="dec btnqty"><i class="fa fa-minus"></i></div></div>');
1994
1995	jQuery(".btnqty").click('click', function () {
1996
1997		var form_id = jQuery(this).parents('form').data('id');
1998		var currency = jQuery(this).parents('form').data('currency');
1999
2000		var $button = jQuery(this);
2001		var oldQty = $button.parent().parent().find("input").val();
2002		if ($button.html() == '<i class="fa fa-plus"></i>') {
2003			var newQty = parseFloat(oldQty) + 1;
2004		} else {
2005			// Don't allow decrementing less than zero
2006			if (oldQty > 0) {
2007				var newQty = parseFloat(oldQty) - 1;
2008			} else {
2009				newQty = 0;
2010			}
2011		}
2012
2013		$button.parent().parent().find("input").val(newQty);
2014
2015		calculate(form_id, currency);
2016
2017		if (typeof applePay.destroy === "function") {
2018			displayApplePay(payments, form_id, currency, applePay);
2019		}
2020		if (typeof googlePay.destroy === "function") {
2021			googlePay.destroy();
2022			displayGooglePay(payments, form_id, currency, googlePay);
2023		}
2024		if (typeof afterpay.destroy === "undefined") {
2025			if (wpep_local_vars.afterpay == 'on') {
2026				displayAfterPay(payments, form_id, currency);
2027			}
2028		}
2029
2030		if (typeof cashAppPay.destroy === "undefined") {
2031			if (wpep_local_vars.cashapp == 'on') {
2032				displayCashApp(payments, form_id, currency);
2033			}
2034		}
2035
2036	});
2037
2038
2039	jQuery(".form-control").on(
2040		'focus',
2041		function () {
2042			var tmpThis = jQuery(this).val();
2043			if (tmpThis == '') {
2044				jQuery(this).parent().addClass("focus-input");
2045			} else if (tmpThis != '') {
2046				jQuery(this).parent().addClass("focus-input");
2047			}
2048		}
2049	).on(
2050		'blur',
2051		function () {
2052			var tmpThis = jQuery(this).val();
2053			if (tmpThis == '') {
2054				jQuery(this).parent().removeClass("focus-input");
2055				jQuery(this).siblings('.wizard-form-error').slideDown("3000");
2056			} else if (tmpThis != '') {
2057				jQuery(this).parent().addClass("focus-input");
2058				jQuery(this).siblings('.wizard-form-error').slideUp("3000");
2059			}
2060		}
2061	);
2062
2063	jQuery('.paynow').click(
2064		function () {
2065
2066			var form_id = jQuery(this).parents('form').data('id');
2067
2068			if (jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).length > 0) {
2069				jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).remove();
2070				jQuery(`#wpep-coupons-${form_id}`).children().show();
2071			}
2072
2073			if (jQuery(`#theForm-${form_id} .wpep-alert-coupon`).length > 0) {
2074				jQuery(`#theForm-${form_id} .wpep-alert-coupon`).remove();
2075			}
2076			jQuery('form[data-id="' + form_id + '"] .display').text(jQuery(this).text());
2077			var selected_payment_tab = jQuery(`ul.wpep_tabs-${form_id} li.tab-link.current`).data('tab');
2078			if (selected_payment_tab == 'giftcard-' + form_id) {
2079				jQuery(`#amount_display_${form_id}`).hide();
2080				if (jQuery('#giftcard_text_' + form_id).length == 0) {
2081					jQuery('.wpep-single-form-' + form_id + ' span').append(`<small id="giftcard_text_${form_id}" class="giftcard_text" style="font-size: 100%;">with Gift Card</small>`);
2082				}
2083			} else {
2084				jQuery('#giftcard_text_' + form_id).remove();
2085				jQuery(`#amount_display_${form_id}`).show();
2086			}
2087			jQuery('form[data-id="' + form_id + '"] .display').next().next('input[name="one_unit_cost"]').val(jQuery(this).text()).trigger('change');
2088			jQuery('form[data-id="' + form_id + '"] .display').next('input[name="wpep-selected-amount"]').val(jQuery(this).text()).trigger('change');
2089			jQuery('#wpep_quantity_' + form_id).val(1);
2090			jQuery(`#wpep_coupon_applied_${form_id}`).hide();
2091			// jQuery( 'form[data-id="' + form_id + '"] .wpep-single-form-' + current_form_id).removeClass( 'wpep-disabled' );
2092			// jQuery( 'form[data-id="' + form_id + '"] .wpep-wizard-form-' + current_form_id).removeClass( 'wpep-disabled' );
2093
2094			jQuery('form[data-id="' + form_id + '"] .showPayment').removeClass('shcusIn');
2095			jQuery('form[data-id="' + form_id + '"] .customPayment').text(jQuery(this).val());
2096			var selected_payment_tab = jQuery(`ul.wpep_tabs-${form_id} li.tab-link.current`).data('tab');
2097
2098		}
2099	);
2100
2101	jQuery('.otherpayment').on('click', function (e) {
2102		var form_id = jQuery(this).parents('form').data('id');
2103		var min = parseFloat(jQuery('.customPayment').attr('min'));
2104		setTimeout(function () {
2105			jQuery('input[name="wpep-selected-amount"]').val(min).trigger('change');
2106			jQuery('.customPayment.otherPayment').val(min);
2107			// jQuery( 'form[data-id="' + form_id + '"] .wpep-single-form-' + current_form_id).removeClass( 'wpep-disabled' );
2108			// jQuery( 'form[data-id="' + form_id + '"] .wpep-wizard-form-' + current_form_id).removeClass( 'wpep-disabled' );
2109		}, 1500);
2110	});
2111
2112	jQuery('.otherPayment').on(
2113		'change',
2114		function (e) {
2115
2116			window.wpep_other_amount_pending_verification = true;
2117
2118			var form_id      = jQuery( this ).parents( 'form' ).data( 'id' );
2119			var currency     = jQuery( this ).parents( 'form' ).data( 'currency' );
2120			var currencyType = jQuery( this ).parents( 'form' ).data( 'currency-type' );
2121			var max          = parseFloat( jQuery( this ).attr( 'max' ) );
2122			var min          = parseFloat( jQuery( this ).attr( 'min' ) );
2123			var val          = jQuery( this ).val();
2124			jQuery( '#one_unit_cost' ).val( val );
2125			jQuery( '#wpep_quantity_' + form_id ).val( 1 );
2126
2127			if (jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).length > 0) {
2128				jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).remove();
2129				jQuery(`#wpep-coupons-${form_id}`).children().show();
2130			}
2131
2132			if (jQuery(`#theForm-${form_id} .wpep-alert-coupon`).length > 0) {
2133				jQuery(`#theForm-${form_id} .wpep-alert-coupon`).remove();
2134			}
2135
2136			// Amount verify hone tak button disable - user click na kar sake
2137			jQuery( 'form[data-id="' + form_id + '"] .wpep-single-form-' + form_id ).addClass( 'wpep-disabled' );
2138			jQuery( 'form[data-id="' + form_id + '"] .wpep-wizard-form-' + form_id ).addClass( 'wpep-disabled' );
2139			jQuery( 'form[data-id="' + form_id + '"] .wpep-single-form-submit-btn' ).addClass( 'wpep-disabled' );
2140			jQuery( 'form[data-id="' + form_id + '"] .wpep-wizard-form-submit-btn' ).addClass( 'wpep-disabled' );
2141
2142			setTimeout(function() {
2143				if (val != '' && val >= min && val <= max) {
2144					currency = prepare_display_amount(currencyType, currency, val);
2145
2146					jQuery(this).val(val);
2147					jQuery('form[data-id="' + form_id + '"] .display').text(currency);
2148					var selected_payment_tab = jQuery(`ul.wpep_tabs-${form_id} li.tab-link.current`).data('tab');
2149					if (selected_payment_tab == 'giftcard-' + form_id) {
2150						jQuery(`#amount_display_${form_id}`).hide();
2151						if (jQuery('#giftcard_text_' + form_id).length == 0) {
2152							jQuery('.wpep-single-form-' + form_id + ' span').append(`<small id="giftcard_text_${form_id}" class="giftcard_text" style="font-size: 100%;">with Gift Card</small>`);
2153						}
2154					} else {
2155						jQuery('#giftcard_text_' + form_id).remove();
2156						jQuery(`#amount_display_${form_id}`).show();
2157					}
2158					jQuery( 'form[data-id="' + form_id + '"] .display' ).next( 'input[name="wpep-selected-amount"]' ).val( jQuery('.otherPayment ').val() ).trigger('change');
2159					jQuery( 'span.valueCheckWpep' ).text('');
2160					window.wpep_other_amount_pending_verification = false;
2161					jQuery( 'form[data-id="' + form_id + '"] .wpep-single-form-' + form_id ).removeClass( 'wpep-disabled' );
2162					jQuery( 'form[data-id="' + form_id + '"] .wpep-wizard-form-' + form_id ).removeClass( 'wpep-disabled' );
2163					jQuery( 'form[data-id="' + form_id + '"] .wpep-single-form-submit-btn' ).removeClass( 'wpep-disabled' );
2164					jQuery( 'form[data-id="' + form_id + '"] .wpep-wizard-form-submit-btn' ).removeClass( 'wpep-disabled' );
2165
2166				} else {
2167
2168					currency = prepare_display_amount(currencyType, currency);
2169
2170					jQuery(this).val('');
2171					jQuery('form[data-id="' + form_id + '"] .display').text('');
2172					var selected_payment_tab = jQuery(`ul.wpep_tabs-${form_id} li.tab-link.current`).data('tab');
2173					if (selected_payment_tab == 'giftcard-' + form_id) {
2174						jQuery(`#amount_display_${form_id}`).hide();
2175						if (jQuery('#giftcard_text_' + form_id).length == 0) {
2176							jQuery('.wpep-single-form-' + form_id + ' span').append(`<small id="giftcard_text_${form_id}" class="giftcard_text" style="font-size: 100%;">with Gift Card</small>`);
2177						}
2178					} else {
2179						jQuery('#giftcard_text_' + form_id).remove();
2180						jQuery(`#amount_display_${form_id}`).show();
2181					}
2182					jQuery( 'form[data-id="' + form_id + '"] .display' ).next( 'input[name="wpep-selected-amount"]' ).val( '' ).trigger('change');
2183					window.wpep_other_amount_pending_verification = false;
2184					jQuery( 'form[data-id="' + form_id + '"] .wpep-single-form-' + form_id ).addClass( 'wpep-disabled' );
2185					jQuery( 'form[data-id="' + form_id + '"] .wpep-wizard-form-' + form_id ).addClass( 'wpep-disabled' );
2186					var valueValidationWpEp = 'Please insert value between ' + min + ' - ' + max;
2187					jQuery('span.valueCheckWpep').text(valueValidationWpEp);
2188				}
2189				jQuery(`#wpep_coupon_applied_${form_id}`).hide();
2190			}, 400);
2191		}
2192	);
2193
2194	function prepare_display_amount(currencyType, currency, val) {
2195
2196		if (currencyType == 'symbol') {
2197
2198			if (currency == 'USD') {
2199				currency = '$' + val;
2200			}
2201
2202			if (currency == 'CAD') {
2203				currency = 'C$' + val;
2204			}
2205
2206			if (currency == 'AUD') {
2207				currency = 'A$' + val;
2208			}
2209
2210			if (currency == 'JPY') {
2211				currency = 'Â¥' + val;
2212			}
2213
2214			if (currency == 'GBP') {
2215				currency = '£' + val;
2216			}
2217
2218		} else {
2219
2220			currency = val + ' ' + currency;
2221
2222		}
2223
2224		return currency;
2225
2226	}
2227
2228
2229	jQuery('.wpep_delete_tabular_product').click(
2230		function () {
2231
2232			var form_id = jQuery(this).parents('form').data('id');
2233
2234			var currency = jQuery(this).parents('form').data('currency');
2235
2236			jQuery(this).closest('.wpItem').hide();
2237			calculate(form_id, currency);
2238
2239		}
2240	);
2241
2242	jQuery('.wpep_delete_tabular_square_product').click(
2243		function () {
2244
2245			var form_id = jQuery(this).parents('form').data('id');
2246
2247			var currency = jQuery(this).parents('form').data('currency');
2248			var square_product_id = jQuery(this).closest('.wpItem').find('.wpep_square_product_id').val();
2249			jQuery(this).closest('.wpItem').hide();
2250			jQuery('#stock_' + square_product_id).hide();
2251			calculate(form_id, currency);
2252
2253		}
2254	);
2255
2256	function wpepValidateFormSubmitButton() {
2257		var $other = jQuery('.otherPayment');
2258		if (!$other.length || !$other.is(':visible') || $other.val() === '') {
2259			window.wpep_other_amount_pending_verification = false;
2260		}
2261
2262		var $submitBtns = jQuery('button.wpep-single-form-submit-btn, button.wpep-wizard-form-submit-btn');
2263
2264		if (window.wpep_other_amount_pending_verification) {
2265			$submitBtns.addClass('wpep-disabled');
2266			return;
2267		}
2268
2269		var rawAmount = jQuery('input[name="wpep-selected-amount"]').val() || '';
2270		var amount = parseFloat(String(rawAmount).replace(/[^0-9.]/g, ''));
2271		var isTabular =
2272			wpep_local_vars.wpep_square_amount_type === 'tabular_layout_for_square' ||
2273			wpep_local_vars.wpep_square_amount_type === 'payment_tabular';
2274
2275		if (isTabular && (!amount || amount === 0)) {
2276			$submitBtns.addClass('wpep-disabled');
2277		} else if (amount > 0) {
2278			$submitBtns.removeClass('wpep-disabled');
2279		}
2280	}
2281
2282	wpepValidateFormSubmitButton();
2283
2284	jQuery('input[name="wpep-selected-amount"]').on('change', function () {
2285		wpepValidateFormSubmitButton();
2286	});
2287
2288});
2289
2290jQuery(window).on('load', function () {
2291	if (jQuery('form.wpep_payment_form').length > 0) {
2292		jQuery('form.wpep_payment_form').each(
2293			async function () {
2294				var current_form_id = jQuery(this).data('id');
2295				var coupon_data = {
2296					'action': 'wpep_check_coupon',
2297					'current_form_id': current_form_id,
2298					'coupon_code': jQuery(this).siblings('input[name="wpep-coupon"]').val(),
2299				};
2300				jQuery.post(
2301					wpep_local_vars.ajax_url,
2302					coupon_data,
2303					function (response) {
2304						if (response) {
2305							jQuery('#wpep-coupons-' + current_form_id).find('input[name="wpep-coupon"]').focus();
2306							jQuery('#wpep-coupons-' + current_form_id).find('input[name="wpep-coupon"]').val(response);
2307							jQuery('#wpep-coupons-' + current_form_id).find('input[name="wpep-cp-submit"]').click();
2308						}
2309					});
2310			}
2311		)
2312	}
2313
2314	jQuery('.wpep_coupon_remove_btn').on('click', function (e) {
2315		e.preventDefault();
2316		var form_id = jQuery(this).parents('form.wpep_payment_form').data('id');
2317		var coupon_delete_data = {
2318			'action': 'wpep_delete_coupon',
2319			'current_form_id': form_id,
2320		}
2321		jQuery.post(
2322			wpep_local_vars.ajax_url,
2323			coupon_delete_data,
2324			function (response) {
2325				if (response) {
2326					var gross_amount = jQuery('#theForm-' + form_id).find('#gross_total-' + form_id).val();
2327					if (jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).length > 0) {
2328						jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).remove();
2329						jQuery(`#wpep-coupons-${form_id}`).children().show();
2330					}
2331					if (jQuery(`#theForm-${form_id} .wpep-alert-coupon`).length > 0) {
2332						jQuery(`#theForm-${form_id} .wpep-alert-coupon`).remove();
2333					}
2334					jQuery(`#theForm-${form_id}`).find('input[name="wpep-selected-amount"]').val(gross_amount).trigger('change');
2335
2336					jQuery(`#wpep_coupon_applied_${form_id}`).hide();
2337					jQuery('input[name="wpep-coupon"]').val('');
2338				}
2339			});
2340
2341	});
2342
2343	function applyCoupon(element) {
2344		var form_id = jQuery(element).parents('form.wpep_payment_form').data('id');
2345		var discount = jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).length > 0 ? 'yes' : 'no';
2346
2347		var gross_amount = jQuery(`#theForm-${form_id}`).find(`#gross_total-${form_id}`).val();
2348
2349		var currency = wpep_local_vars.currencySymbolType === 'code' ?
2350			wpep_local_vars.wpep_square_currency_new :
2351			wpep_local_vars.wpep_currency_symbol;
2352
2353		var data = {
2354			'action': 'wpep_apply_coupon',
2355			'current_form_id': form_id,
2356			'coupon_code': jQuery(element).siblings('input[name="wpep-coupon"]').val(),
2357			'total_amount': gross_amount,
2358			'extra_fee': jQuery(element).parents('form.wpep_payment_form').find('.is_extra_fee').val(),
2359			'discounted': discount,
2360			'currency': currency,
2361			'cp_submit': jQuery(element).val(),
2362			'wpep_payment_nonce': wpepGetPaymentNonce(form_id),
2363			'wp_payment_nonce': wpepGetPaymentNonce(form_id)
2364		};
2365
2366		jQuery.post(
2367			wpep_local_vars.ajax_url,
2368			data,
2369			function (response) {
2370				var response = jQuery.parseJSON(response);
2371
2372				if (response.status == 'success') {
2373
2374					var amountTotalWpep = response.subtotal;
2375					var couponAmountWpep = response.coupons_amount;
2376
2377					if (response.discount_type != 'percentage') {
2378						if (couponAmountWpep > amountTotalWpep) {  //coupon amount greater then total amount
2379							if (jQuery('.couponAmountError').length === 0) {
2380								jQuery('.coupon-field').after('<div style="margin: -24px 0px -10px 0px;"><span class="couponAmountError">Coupon is bigger then total amount</span></div>');
2381							}
2382							return;
2383						} else {
2384							jQuery('.couponAmountError').remove();
2385						}
2386					}
2387
2388
2389					var discountPrice = parseFloat(response.discount).toFixed(2);
2390					var subTotalPrice = parseFloat(response.subtotal).toFixed(2);
2391					var totalPrice = parseFloat(response.total).toFixed(2);
2392
2393					jQuery(`#wpep-coupons-${form_id}`).children().hide();
2394					jQuery(`#wpep_coupon_applied_${form_id}`).show();
2395
2396					if (jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).length <= 0) {
2397						jQuery(`#theForm-${form_id}`).append(`
2398							<input type="hidden" name="wpep-coupon-amount" value="${response.coupons_amount}" />
2399							<input type="hidden" name="wpep-coupon-type" value="${response.discount_type}" />
2400							<input type="hidden" name="wpep-discount" value="${discountPrice}" />
2401						`);
2402
2403						jQuery(`#wpep-coupons-${form_id}`).prepend(`
2404							<div class="wpep-alert-coupon wpep-alert wpep-alert-success wpep-alert-dismissable">
2405								<a href="#" class="wpep-dismiss-coupon wpep-alert-close">×</a>${response.message_success}
2406							</div>
2407						`);
2408
2409						let amountText = (wpep_local_vars.currencySymbolType == 'code') ?
2410							`${totalPrice} ${response.currency}` :
2411							`${response.currency} ${totalPrice}`;
2412
2413						jQuery(`#theForm-${form_id}`).find(`small#amount_display_${form_id}`).text(amountText);
2414						jQuery(`#theForm-${form_id}`).find('input[name="wpep-selected-amount"]').val(`${subTotalPrice} ${response.currency}`).trigger('change');
2415					} else {
2416						jQuery(`#wpep-coupons-${form_id}`).prepend(`
2417							<div class="wpep-alert-coupon wpep-alert wpep-alert-danger wpep-alert-dismissable">
2418								<a href="#" class="wpep-dismiss-coupon wpep-alert-close">×</a>Coupon already applied!
2419							</div>
2420						`);
2421					}
2422				}
2423
2424				if (response.status == 'failed') {
2425					if (jQuery(`#wpep-coupons-${form_id} .failedcoupon`).length === 0) {
2426						jQuery(`#wpep-coupons-${form_id}`).prepend(`
2427							<div class="wpep-alert-coupon wpep-alert wpep-alert-danger wpep-alert-dismissable failedcoupon">
2428								<a href="#" class="wpep-dismiss-coupon wpep-alert-close">×</a>${response.message_failed}
2429							</div>
2430						`);
2431					}
2432				}	
2433			}
2434		);
2435	}
2436
2437	jQuery('.cp-apply').on('click', function (e) {
2438		e.preventDefault();
2439		applyCoupon(this);
2440	});
2441	jQuery(document).on('keypress', '.otherPayment', function (event) {
2442		if (event.which === 13) {  // 13 is the keycode for Enter
2443			event.preventDefault(); // Prevent form submission
2444		}
2445	});
2446	// payment custom layout of pricing in form settings. 
2447	// This is for coupon apply when each tab click.
2448	
2449	jQuery('.selection input[type="radio"]').on('change', function (e) {
2450		if (jQuery(this).hasClass('otherpayment')) {
2451			return;
2452		}
2453		setTimeout(function () {
2454			jQuery('.cp-apply').trigger("click");
2455		}, 500);
2456	});
2457
2458	// payment radio listing of pricing in form settings. 
2459	// This is for coupon apply when each tab click..
2460	jQuery('.selectedPlan').on('change', function (e) {
2461		e.preventDefault();
2462		setTimeout(function () {
2463			jQuery('.cp-apply').trigger("click");
2464		}, 500);
2465	});
2466
2467	// payment radio listing of pricing in form settings. 
2468	// This is for coupon apply when each tab click..
2469	jQuery('.custom-option').on('click', function (e) {
2470		e.preventDefault();
2471		setTimeout(function () {
2472			jQuery('.cp-apply').trigger("click");
2473		}, 500);
2474	});
2475
2476	// This is for coupon remove on beforeunload function.
2477	jQuery(window).bind('beforeunload', function () {
2478		jQuery('.wpep_coupon_remove_btn').trigger("click");
2479	});
2480
2481	if (jQuery('.ext_number').is(':visible')) {
2482		jQuery('.ext_number').on('input', function () {
2483			var inputElement = jQuery(this); // save the reference to the element
2484			setTimeout(function () {
2485				var enteredValue = parseInt(inputElement.val());
2486				var minValue = parseInt(inputElement.attr('min'));
2487				var maxValue = parseInt(inputElement.attr('max'));
2488				if (enteredValue < minValue || enteredValue > maxValue) {
2489					inputElement.val('');
2490				}
2491			}, 1000);
2492		});
2493	}
2494
2495})
2496jQuery(document).on('click', '.wpep-dismiss-coupon', function (e) {
2497	e.preventDefault();
2498	jQuery('.wpep-alert-coupon').remove();
2499});
2500let current_form_id = jQuery('form.wpep_payment_form').data('id');
2501
2502let debounceTimer;
2503
2504jQuery(document).on('input', 'input[name="wpep_quantity"]', function () {
2505	clearTimeout(debounceTimer); // Clear the previous timer if it's still running
2506
2507	// Get the current value of the input fieldd
2508	jQuery(this).val(jQuery(this).val().replace(/[^0-9]/g, ''));
2509	var value = parseInt(this.value);
2510	// Ensure the value is at least 1
2511	if (isNaN(value) || value < 1) {
2512		value = 1;
2513		jQuery(this).val(1); // Update the input field to reflect the minimum value
2514	}
2515	debounceTimer = setTimeout(function () {
2516		// Get the current form ID
2517		var current_form_id = jQuery('form.wpep_payment_form').data('id');
2518
2519		// Call the update function with the value
2520		wpep_update_amount_with_quantity(current_form_id, value);
2521	}, 1000); // 1-second delay
2522});
2523
2524function wpep_update_amount_with_quantity(current_form_id, value) {
2525
2526	var amount_field_id = "amount_display_" + current_form_id;
2527	var amount_with_currency = document.getElementById(amount_field_id).innerHTML.trim();
2528	var amount_and_currency_split = amount_with_currency.split(" ");
2529	var currency = amount_and_currency_split[1];
2530	var one_unit_cost = jQuery('#one_unit_cost').val();
2531	var one_unit_cost = one_unit_cost.split(" ")[0];
2532	var one_unit_cost = one_unit_cost.replace("$", ""); // remove dollar sign
2533	var new_amount = one_unit_cost * value;
2534	document.getElementById(amount_field_id).innerHTML = new_amount + ' ' + currency;
2535	jQuery('form[data-id="' + current_form_id + '"] .display').next('input[name="wpep-selected-amount"]').val(new_amount + ' ' + currency).trigger('change');
2536	var discount = 'no';
2537	if (jQuery(`#theForm-${current_form_id} input[name="wpep-discount"]`).length > 0) {
2538		discount = 'yes';
2539	}
2540	var data = {
2541		'action': 'wpep_apply_coupon',
2542		'current_form_id': current_form_id,
2543		'coupon_code': jQuery('.cp-apply').siblings('input[name="wpep-coupon"]').val(),
2544		'total_amount': new_amount,
2545		'extra_fee': jQuery(this).parents('form.wpep_payment_form').find('.is_extra_fee').val(),
2546		'discounted': discount,
2547		'currency': currency,
2548		'cp_submit': jQuery('.cp-apply').val(),
2549		'wpep_payment_nonce': wpepGetPaymentNonce(current_form_id),
2550		'wp_payment_nonce': wpepGetPaymentNonce(current_form_id)
2551	};
2552
2553	jQuery.post(
2554		wpep_local_vars.ajax_url,
2555		data,
2556		function (response) {
2557			var response = jQuery.parseJSON(response); // create an object with the key of the array
2558
2559			if (response.status == 'success') {
2560
2561				var discountPrice = parseFloat(response.discount).toFixed(2);
2562				var totalPrice = parseFloat(response.total).toFixed(2);
2563
2564				if (jQuery(`#theForm-${current_form_id} input[name="wpep-discount"]`).length <= 0) {
2565
2566					if (jQuery(`#theForm-${current_form_id} .wpep-alert-coupon`).length > 0) {
2567						jQuery(`#theForm-${current_form_id} .wpep-alert-coupon`).remove();
2568					}
2569
2570					jQuery(`#theForm-${current_form_id}`).append(`<input type="hidden" name="wpep-discount" value="${discountPrice}" />`);
2571					jQuery(`#wpep-coupons-${current_form_id}`).prepend(`<div class="wpep-alert-coupon wpep-alert wpep-alert-success wpep-alert-dismissable"><a href="#" class="wpep-dismiss-coupon wpep-alert-close">×</a>${response.message_success}</div>`);
2572					jQuery(`#theForm-${current_form_id}`).find('input[name="wpep-selected-amount"]').val(`${totalPrice} ${response.currency}`).trigger('change');
2573					jQuery(`#theForm-${current_form_id}`).find(`small#amount_display_${current_form_id}`).text(`${totalPrice} ${response.currency}`);
2574
2575				} else {
2576					jQuery(`#wpep-coupons-${current_form_id}`).prepend(`<div class="wpep-alert-coupon wpep-alert wpep-alert-danger wpep-alert-dismissable quantityCouponAlert"><a href="#" class="wpep-dismiss-coupon wpep-alert-close">×</a>Coupon already applied!</div>`);
2577				}
2578
2579			}
2580
2581			if (response.status == 'failed') {
2582
2583				if (jQuery(`#theForm-${current_form_id} .wpep-alert-coupon`).length > 0) {
2584					jQuery(`#theForm-${current_form_id} .wpep-alert-coupon`).remove();
2585				}
2586
2587				jQuery(`#wpep-coupons-${current_form_id}`).prepend(`<div class="wpep-alert-coupon wpep-alert wpep-alert-danger wpep-alert-dismissable quantityCouponAlert"><a href="#" class="wpep-dismiss-coupon wpep-alert-close">×</a>${response.message_failed}</div>`);
2588
2589			}
2590
2591		}
2592	)
2593
2594}
2595
2596var quantity_waiting = false;
2597jQuery('.wpep_increaseValue').on('click', function () {
2598	var current_form_id = jQuery('form.wpep_payment_form').data('id');
2599	if (jQuery(`#theForm-${current_form_id} input[name="wpep-discount"]`).length > 0) {
2600		jQuery(`#theForm-${current_form_id} input[name="wpep-discount"]`).remove();
2601		jQuery(`#wpep-coupons-${current_form_id}`).children().show();
2602	}
2603
2604	if (jQuery(`#theForm-${current_form_id} .wpep-alert-coupon`).length > 0) {
2605		jQuery(`#theForm-${current_form_id} .wpep-alert-coupon`).remove();
2606	}
2607
2608	var quantity_id = 'wpep_quantity_' + current_form_id;
2609
2610	var value = parseInt(document.getElementById(quantity_id).value, 10);
2611	value = isNaN(value) ? 0 : value;
2612	value++;
2613	document.getElementById(quantity_id).value = value;
2614	if (!quantity_waiting) {
2615		quantity_waiting = true;
2616		setTimeout(function () {
2617			var value = document.getElementById(quantity_id).value;
2618			wpep_update_amount_with_quantity(current_form_id, value);
2619			quantity_waiting = false;  // Reset the flag to allow next operation
2620		}, 1000); // 1 second delayy
2621	}
2622	jQuery(`#wpep_coupon_applied_${current_form_id}`).hide();
2623
2624	if (jQuery('input[name="wpep-coupon"]').length > 0 && jQuery('input[name="wpep-coupon"]').val().trim() !== '') {
2625		jQuery('.cp-apply').trigger("click");
2626	}
2627
2628})
2629
2630jQuery('.wpep_decreaseValue').on('click', function () {
2631
2632	if (jQuery(`#theForm-${current_form_id} input[name="wpep-discount"]`).length > 0) {
2633		jQuery(`#theForm-${current_form_id} input[name="wpep-discount"]`).remove();
2634		jQuery(`#wpep-coupons-${current_form_id}`).children().show();
2635	}
2636
2637	if (jQuery(`#theForm-${current_form_id} .wpep-alert-coupon`).length > 0) {
2638		jQuery(`#theForm-${current_form_id} .wpep-alert-coupon`).remove();
2639	}
2640
2641	var quantity_id = 'wpep_quantity_' + current_form_id;
2642	var value = parseInt(document.getElementById(quantity_id).value, 10);
2643
2644	if (1 !== value) {
2645		value = isNaN(value) ? 0 : value;
2646		value < 1 ? value = 1 : '';
2647		value--;
2648		document.getElementById(quantity_id).value = value;
2649		setTimeout(function () {
2650			var value = parseInt(document.getElementById(quantity_id).value, 10);
2651			wpep_update_amount_with_quantity(current_form_id, value);
2652		}, 1000);
2653	}
2654	jQuery(`#wpep_coupon_applied_${current_form_id}`).hide();
2655});
2656
2657function calculate(form_id, currency) {
2658
2659	if (jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).length > 0) {
2660		jQuery(`#theForm-${form_id} input[name="wpep-discount"]`).remove();
2661		jQuery(`#wpep-coupons-${form_id}`).children().show();
2662	}
2663	if (jQuery(`#theForm-${form_id} .wpep-alert-coupon`).length > 0) {
2664		jQuery(`#theForm-${form_id} .wpep-alert-coupon`).remove();
2665	}
2666
2667	var currency_codes = ['CAD', 'GBP', 'AUD', 'JPY', 'EUR', 'USD'];
2668	var currency_symbol = ['C$', '£', 'A$', '¥', '€', '$'];
2669
2670	if (wpep_local_vars.currencySymbolType == 'symbol') {
2671		jQuery.each(currency_codes, function (i, val) {
2672			if (currency == val) {
2673				currency = currency_symbol[i];
2674			}
2675		});
2676	}
2677
2678	if (wpep_local_vars.currencySymbolType == 'code') {
2679
2680		jQuery.each(currency_symbol, function (i, val) {
2681			if (currency == val) {
2682				currency = currency_codes[i];
2683			}
2684		});
2685
2686	}
2687
2688	var item_display = 'yes';
2689
2690	if (jQuery('form[data-id="' + form_id + '"] .wpItem').length) {
2691
2692		jQuery(".wpItem").each(
2693			function () {
2694
2695				var priceVal = jQuery(this).find('input.price').val();
2696				var qtyVal = jQuery(this).find("input.qty").val();
2697				var costVal = (priceVal * qtyVal);
2698
2699				jQuery(this).find('input.cost').val((costVal).toFixed(2));
2700
2701			}
2702		);
2703
2704		var subtotalVal = 0;
2705		jQuery('.cost').each(
2706			function () {
2707
2708				item_display = jQuery(this).closest('.wpItem').css('display') == 'none' ? 'no' : 'yes';
2709				if ('yes' == item_display) {
2710					subtotalVal += parseFloat(jQuery(this).val());
2711
2712				}
2713
2714			}
2715		);
2716
2717		jQuery('.subtotal').val((subtotalVal).toFixed(2));
2718
2719		var total = parseFloat(subtotalVal);
2720
2721		total = (total).toFixed(2);
2722
2723		if (wpep_local_vars.currencySymbolType == 'symbol') {
2724			jQuery(`#amount_display_${form_id}`).text(currency + ' ' + total);
2725			jQuery('input[name="wpep-selected-amount"]').val(total).trigger('change');
2726		} else if (wpep_local_vars.currencySymbolType == 'code') {
2727			jQuery(`#amount_display_${form_id}`).text(total + ' ' + currency);
2728			jQuery('input[name="wpep-selected-amount"]').val(total).trigger('change');
2729		} else {
2730			jQuery(`#amount_display_${form_id}`).text(total);
2731		}
2732
2733		var selected_payment_tab = jQuery(`ul.wpep_tabs-${form_id} li.tab-link.current`).data('tab');
2734		if (selected_payment_tab == 'giftcard-' + form_id) {
2735			jQuery(`#amount_display_${form_id}`).hide();
2736			if (jQuery('#giftcard_text_' + form_id).length == 0) {
2737				jQuery('.wpep-single-form-' + form_id + ' span').append(`<small id="giftcard_text_${form_id}" class="giftcard_text" style="font-size: 100%;">with Gift Card</small>`);
2738			}
2739		} else {
2740			jQuery('#giftcard_text_' + form_id).remove();
2741			jQuery(`#amount_display_${form_id}`).show();
2742			// jQuery(`#amount_display_${current_form_id}`).text(jQuery(`#amount_display_${current_form_id}`).siblings('input[name="wpep-selected-amount"]').val());
2743		}
2744		var layout = jQuery('#wpep_amount_layout').val();
2745		if (layout !== 'tabular_layout') {
2746			jQuery('form[data-id="' + form_id + '"] .display').next('input[name="wpep-selected-amount"]').val(currency).trigger('change');
2747		}
2748		if (layout == 'tabular_layout_for_square') {
2749			jQuery('form[data-id="' + form_id + '"] .display').next('input[name="wpep-selected-amount"]').val(total).trigger('change');
2750		}
2751		// jQuery( 'form[data-id="' + form_id + '"] .wpep-single-form-' + current_form_id).removeClass( 'wpep-disabled' );
2752		// jQuery( 'form[data-id="' + form_id + '"] .wpep-wizard-form-' + current_form_id).removeClass( 'wpep-disabled' );
2753		jQuery(`#wpep_coupon_applied_${form_id}`).hide();
2754	}
2755}
2756
2757const filterNum = (str) => {
2758	const numericalChar = new Set([".", ",", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
2759	str = str.split("").filter(char => numericalChar.has(char)).join("");
2760	return str;
2761}
2762
2763jQuery(window).on('load', function () {
2764
2765	jQuery('.wpep_payment_form').each(function () {
2766		var current_form_id = jQuery(this).attr('data-id');
2767		var currency = jQuery(this).data('currency');
2768
2769		jQuery('ul.wpep_tabs-' + current_form_id + ' li').click(function () {
2770			var tab_id = jQuery(this).attr('data-tab');
2771
2772			if ('cashapp-' + current_form_id === tab_id || 'achdebit-' + current_form_id === tab_id || 'googlePay-' + current_form_id === tab_id ||
2773				'afterpay-' + current_form_id === tab_id || 'applePayfather-' + current_form_id === tab_id) {
2774				jQuery('.wpep-single-form-' + current_form_id).attr('disabled', 'disabled');
2775				jQuery('.wpep-single-form-' + current_form_id).css('cursor', 'not-allowed');
2776				jQuery('.wpep-wizard-form-' + current_form_id).attr('disabled', 'disabled');
2777				jQuery('.wpep-wizard-form-' + current_form_id).css('cursor', 'not-allowed');
2778				jQuery('.cp-apply').prop('disabled', false);
2779				jQuery('.cp-apply').css('cursor', 'default');
2780			} else {
2781				jQuery('.wpep-single-form-' + current_form_id).prop('disabled', false);
2782				jQuery('.wpep-single-form-' + current_form_id).css('cursor', 'pointer');
2783				jQuery('.wpep-wizard-form-' + current_form_id).prop('disabled', false);
2784				jQuery('.wpep-wizard-form-' + current_form_id).css('cursor', 'pointer');
2785			}
2786			jQuery('ul.wpep_tabs-' + current_form_id + ' li').removeClass('current');
2787			jQuery('.tab-content-' + current_form_id).removeClass('current');
2788			jQuery(this).find('.tab-content-' + current_form_id).addClass('current');
2789			jQuery(this).addClass('current');
2790			jQuery("#" + tab_id).addClass('current');
2791
2792			if (tab_id != 'applePayfather-' + current_form_id) {
2793				jQuery('#applePayfather-' + current_form_id).css('display', 'none');
2794			} else {
2795				jQuery('#applePayfather-' + current_form_id).css('display', 'block');
2796			}
2797			if (tab_id == 'giftcard-' + current_form_id) {
2798				displayGiftcard(payments, current_form_id, currency);
2799				jQuery(`#amount_display_${current_form_id}`).hide();
2800				if (jQuery('#giftcard_text_' + current_form_id).length == 0) {
2801					jQuery('.wpep-single-form-' + current_form_id + ' span').append(`<small id="giftcard_text_${current_form_id}" class="giftcard_text" style="font-size: 100%;">with Gift Card</small>`);
2802				}
2803			} else {
2804				jQuery('#giftcard_text_' + current_form_id).remove();
2805				jQuery(`#amount_display_${current_form_id}`).show();
2806			}
2807		}
2808		);
2809	});
2810
2811
2812	jQuery('input[name="wpep-selected-amount"]').on('change paste keyup', function () {
2813
2814		var form_id = jQuery(this).parents('form.wpep_payment_form').data('id');
2815		var discount = 0.00;
2816		var signup_total = 0.00;
2817		var amount = parseFloat(filterNum(jQuery(this).val()));
2818		if (jQuery(`#theForm-${form_id}`).find('input[name="wpep-signup-amount"]').length > 0) {
2819			var signup_total = parseFloat(jQuery(`#theForm-${form_id}`).find('input[name="wpep-signup-amount"]').val());
2820		}
2821		//var gross_total = parseFloat(jQuery(`#theForm-${form_id}`).find('input[name="gross_total"]').val());
2822		var total_amount = amount + signup_total;
2823		if (isNaN(total_amount)) {
2824			if (!localStorage.getItem("alertDisplayed")) {
2825
2826				localStorage.setItem("alertDisplayed", "true");
2827			}
2828			var total_amount = 0;
2829		}
2830		var unit_cost = 0;
2831		if (jQuery('#one_unit_cost').length > 0) {
2832			var one_unit_cost = jQuery('#one_unit_cost').val().trim();
2833			unit_cost = one_unit_cost.trim();
2834			unit_cost = unit_cost.split(' ');
2835			unit_cost = unit_cost[0];
2836			unit_cost = parseFloat(unit_cost.replace(wpep_local_vars.wpep_currency_symbol, "")).toFixed(2);
2837		}
2838		if (isNaN(unit_cost)) {
2839			var unit_cost = parseFloat(0).toFixed(2);
2840		}
2841		if (wpep_local_vars.wpep_square_amount_type == 'payment_tabular') {
2842			var unit_cost = parseFloat(amount).toFixed(2);
2843		}
2844		jQuery(`#amount_display_${form_id}`).siblings('input[name="wpep-selected-amount"]').val(parseFloat(total_amount).toFixed(2));
2845		if (wpep_local_vars.currencySymbolType == 'symbol') {
2846			var currency = wpep_local_vars.wpep_currency_symbol;
2847			jQuery(`#amount_display_${form_id}`).text(currency + parseFloat(total_amount).toFixed(2));
2848			jQuery(`#theForm-${form_id}`).find('.wpep-fee-subtotal .fee_value').text(currency + unit_cost);
2849			jQuery(`#theForm-${form_id}`).find('.wpep-fee-total .fee_value').text(currency + parseFloat(total_amount).toFixed(2));
2850		} else if (wpep_local_vars.currencySymbolType == 'code') {
2851			var currency = wpep_local_vars.wpep_square_currency_new;
2852			jQuery(`#amount_display_${form_id}`).text(parseFloat(total_amount).toFixed(2) + ' ' + currency);
2853			jQuery(`#theForm-${form_id}`).find('.wpep-fee-subtotal .fee_value').text(unit_cost + ' ' + currency);
2854			jQuery(`#theForm-${form_id}`).find('.wpep-fee-total .fee_value').text(parseFloat(total_amount).toFixed(2) + ' ' + currency);
2855		} else {
2856			var currency = '';
2857			jQuery(`#amount_display_${form_id}`).text(parseFloat(total_amount).toFixed(2));
2858			jQuery(`#theForm-${form_id}`).find('.wpep-fee-subtotal .fee_value').text(unit_cost);
2859			jQuery(`#theForm-${form_id}`).find('.wpep-fee-total .fee_value').text(parseFloat(total_amount).toFixed(2));
2860		}
2861		var selected_payment_tab = jQuery(`ul.wpep_tabs-${form_id} li.tab-link.current`).data('tab');
2862		if (selected_payment_tab == 'giftcard-' + form_id) {
2863			jQuery(`#amount_display_${form_id}`).hide();
2864			if (jQuery('#giftcard_text_' + form_id).length == 0) {
2865				jQuery('.wpep-single-form-' + form_id + ' span').append(`<small id="giftcard_text_${form_id}" class="giftcard_text" style="font-size: 100%;">with Gift Card</small>`);
2866			}
2867		} else {
2868			jQuery('#giftcard_text_' + form_id).remove();
2869			jQuery(`#amount_display_${form_id}`).show();
2870		}
2871		if (jQuery(`#theForm-${form_id}`).find('input[name="gross_total"]').length > 0) {
2872			jQuery(`#theForm-${form_id}`).find('input[name="gross_total"]').val(amount);
2873		}
2874		if (jQuery(`#theForm-${form_id}`).find('input[name="wpep-discount"]').length > 0) {
2875			discount = parseFloat(jQuery(`#theForm-${form_id}`).find('input[name="wpep-discount"]').val());
2876		}
2877
2878		var extra_fee = jQuery(this).parents('form.wpep_payment_form').find('.is_extra_fee').val();
2879		if (extra_fee == 1 || discount > 0) {
2880			wpep_calculate_fee_data_ajax(form_id, amount, discount);
2881		}
2882
2883	});
2884})
2885
2886let is_wpep_calculate_fee_data_ajax_InProgress = false;
2887function wpep_calculate_fee_data_ajax(form_id, amount, discount) {
2888	if (is_wpep_calculate_fee_data_ajax_InProgress) {
2889		return; // Prevent duplicate requests
2890	}
2891	var data = {
2892		'action': 'wpep_calculate_fee_data',
2893		'dataType': 'html',
2894		'current_form_id': form_id,
2895		'total_amount': amount,
2896		'coupon_amount': jQuery('input[name="wpep-coupon-amount"]').val(),
2897		'coupon_type': jQuery('input[name="wpep-coupon-type"]').val(),
2898		'discount': discount,
2899		'currency': wpep_local_vars.wpep_square_currency_new,
2900		'wpep_payment_nonce': wpepGetPaymentNonce(form_id),
2901		'wp_payment_nonce': wpepGetPaymentNonce(form_id),
2902	};
2903	is_wpep_calculate_fee_data_ajax_InProgress = true;
2904	jQuery.post(
2905		wpep_local_vars.ajax_url,
2906		data,
2907		function (response) {
2908			var extra_fee = jQuery('.is_extra_fee').val();
2909			if (extra_fee == 1 || jQuery('input[name="wpep-signup-amount"]').length > 0) {
2910				jQuery(`#wpep-payment-details-${form_id}`).html(response);
2911				var get_total = jQuery(`#wpep-payment-details-${form_id}`).find('.wpep-fee-total span.fee_value').text();
2912				get_total = get_total.trim();
2913				get_total = get_total.split(' ');
2914				get_total = get_total[0];
2915				get_total = get_total.replace(wpep_local_vars.wpep_currency_symbol, "");
2916			} else {
2917				var rrr = JSON.parse(response);
2918				var get_total = rrr.subtotal;
2919			}
2920			if (wpep_local_vars.currencySymbolType == 'symbol') {
2921				jQuery(`#amount_display_${form_id}`).text(wpep_local_vars.wpep_currency_symbol + get_total);
2922			} else if (wpep_local_vars.currencySymbolType == 'code') {
2923				jQuery(`#amount_display_${form_id}`).text(get_total + ' ' + wpep_local_vars.wpep_square_currency_new);
2924			} else {
2925				jQuery(`#amount_display_${form_id}`).text(get_total);
2926			}
2927			var selected_payment_tab = jQuery(`ul.wpep_tabs-${form_id} li.tab-link.current`).data('tab');
2928			if (selected_payment_tab == 'giftcard-' + form_id) {
2929				jQuery(`#amount_display_${form_id}`).hide();
2930				if (jQuery('#giftcard_text_' + form_id).length == 0) {
2931					jQuery('.wpep-single-form-' + form_id + ' span').append(`<small id="giftcard_text_${form_id}" class="giftcard_text" style="font-size: 100%;">with Gift Card</small>`);
2932				}
2933			} else {
2934				jQuery('#giftcard_text_' + form_id).remove();
2935				jQuery(`#amount_display_${form_id}`).show();
2936			}
2937			jQuery(`#amount_display_${form_id}`).siblings('input[name="wpep-selected-amount"]').val(get_total);
2938
2939			let current_form_id = form_id;
2940			let currency = jQuery('#wpep_form_currency').val();
2941
2942			if (typeof googlePay.destroy === "function") { }
2943
2944			if (typeof afterpay.destroy === "function") { }
2945
2946			if (typeof cashAppPay.destroy === "function") { }
2947
2948			is_wpep_calculate_fee_data_ajax_InProgress = false;
2949			// console.clear();
2950		}
2951	);
2952}
2953
2954function wpep_delete_cof(customer_id, card_on_file, current_form_id, delete_id) {
2955
2956	var data = {
2957		'action': 'wpep_delete_cof',
2958		'customer_id': customer_id,
2959		'card_on_file': card_on_file,
2960		'current_form_id': current_form_id,
2961		'wpep_payment_nonce': wpepGetPaymentNonce(current_form_id),
2962		'wp_payment_nonce': wpepGetPaymentNonce(current_form_id)
2963	};
2964
2965	jQuery.post(
2966		wpep_local_vars.ajax_url,
2967		data,
2968		function (response) {
2969			if ('success' == response) {
2970				jQuery('#' + delete_id).closest("li").remove();
2971			}
2972		}
2973	).done(function () { });
2974
2975}
2976
2977function afterPaybuildPaymentRequest(payments, current_form_id, currency) {
2978
2979
2980	// var finalamoutn = amount;
2981	if (jQuery('input[name="wpep-selected-amount"]').val().trim() != '' && wpep_local_vars.wpep_square_amount_type != 'payment_tabular') {
2982		amount = jQuery('input[name="wpep-selected-amount"]').val();
2983	} else {
2984		amount = jQuery('#amount_display_' + current_form_id).text();
2985	}
2986
2987	coupon_apply = jQuery('#wpep-coupons-' + current_form_id).length;
2988	if (coupon_apply > 0) {
2989		jQuery('.cp-apply').click(function () {
2990			setTimeout(function () {
2991				if (jQuery('input[name="wpep-selected-amount"]').val().trim() != '') {
2992					amount = jQuery('input[name="wpep-selected-amount"]').val();
2993				} else {
2994					amount = jQuery('#amount_display_' + current_form_id).text();
2995				}
2996			}, 1000);
2997		})
2998	}
2999	amount = amount.trim();
3000	amount = amount.replace("$", "");
3001	var min = parseFloat(jQuery('.otherPayment').attr('min'));
3002	if (amount == 0) {
3003		amount = min;
3004	}
3005
3006	const req = payments.paymentRequest({
3007		countryCode: 'US',
3008		currencyCode: currency,
3009		total: {
3010			amount: amount.replace(/[^0-9\.]/gi, '').toString("#0000\\.0000"),
3011			label: 'Total',
3012		},
3013		requestShippingContact: true,
3014	});
3015
3016	// Note how afterpay has its own listeners
3017	req.addEventListener('afterpay_shippingaddresschanged', function (_address) {
3018		return {
3019			shippingOptions: [
3020				{
3021					amount: '0.00',
3022					id: 'shipping-option-1',
3023					label: 'Free',
3024					taxLineItems: [
3025						{
3026							amount: '0.00',
3027							label: 'Tax'
3028						}
3029					],
3030					total: {
3031						amount: amount.replace(/[^0-9\.]/gi, '').toString("#0000\\.0000"),
3032						label: 'total',
3033					},
3034				},
3035			],
3036		};
3037	});
3038
3039	return req;
3040}
3041function cashAppbuildPaymentRequest(payments, current_form_id, currency) {
3042	amount = jQuery('#amount_display_' + current_form_id).text();
3043	coupon_apply = jQuery('#wpep-coupons-' + current_form_id).length;
3044	if (coupon_apply > 0) {
3045		jQuery('.cp-apply').click(function () {
3046			setTimeout(function () {
3047				if (jQuery('input[name="wpep-selected-amount"]').val().trim() != '') {
3048					amount = jQuery('input[name="wpep-selected-amount"]').val();
3049				} else {
3050					amount = jQuery('#amount_display_' + current_form_id).text();
3051				}
3052			}, 1000);
3053		})
3054	}
3055	amount = amount.trim();
3056	amount = amount.split(' ');
3057	amount = amount[0];
3058	amount = amount.replace("$", "");
3059	var min = parseFloat(jQuery('.otherPayment').attr('min'));
3060	if (amount == 0) {
3061		amount = min;
3062	}
3063
3064	jQuery('#cashapp-amount').hide();
3065	paymentRequest = payments.paymentRequest({
3066		countryCode: 'US',
3067		currencyCode: currency,
3068		total: {
3069			amount: amount.toString(),
3070			label: 'Total',
3071		},
3072	});
3073
3074
3075	return paymentRequest;
3076}
3077
3078
3079function gpaybuildPaymentRequest(payments, current_form_id, currency, googlePay) {
3080
3081
3082	var req = {};
3083	amount = jQuery('#amount_display_' + current_form_id).text();
3084	coupon_apply = jQuery('#wpep-coupons-' + current_form_id).length;
3085	if (coupon_apply > 0) {
3086		jQuery('.cp-apply').click(function () {
3087			setTimeout(function () {
3088				if (jQuery('input[name="wpep-selected-amount"]').val().trim() != '') {
3089					amount = jQuery('input[name="wpep-selected-amount"]').val();
3090				} else {
3091					amount = jQuery('#amount_display_' + current_form_id).text();
3092				}
3093			}, 1000);
3094		})
3095	}
3096	amount = amount.trim();
3097	amount = amount.split(' ')[0];
3098	amount = amount.replace('$', '');
3099
3100	req[current_form_id] = payments.paymentRequest({
3101		countryCode: 'US',
3102		currencyCode: currency,
3103		total: {
3104			amount: amount.replace(/[^0-9\.]/gi, '').toString("#0000\\.0000"),
3105			label: 'Total',
3106		},
3107		requestShippingContact: true,
3108	});
3109	req[current_form_id].addEventListener('afterpay_shippingaddresschanged', function (_address) {
3110		return {
3111			shippingOptions: [
3112				{
3113					amount: '0.00',
3114					id: 'shipping-option-1',
3115					label: 'Free',
3116					taxLineItems: [
3117						{
3118							amount: '0.00',
3119							label: 'Tax'
3120						}
3121					],
3122					total: {
3123						amount: amount.replace(/[^0-9\.]/gi, '').toString("#0000\\.0000"),
3124						label: 'total',
3125					},
3126				},
3127			],
3128		};
3129	});
3130
3131	return req[current_form_id];
3132}
3133
3134async function initializeAfterpay(payments, current_form_id, currency) {
3135	var max = parseFloat(jQuery('.otherPayment').attr('max'));
3136	var min = parseFloat(jQuery('.otherPayment').attr('min'));
3137	var val = jQuery('.otherPayment').val();
3138	if ('code' == wpep_local_vars.currencySymbolType) {
3139		currency = wpep_local_vars.wpep_square_currency_new;
3140	}
3141	var amount = jQuery('#amount_display_' + current_form_id).text();
3142	amount = amount.trim();
3143	amount = amount.replace("$", "");
3144
3145	if (val == '') {
3146		jQuery('.otherPayment').val(min);
3147		val = min;
3148	}
3149	if (!isNaN(val) && val >= min && val <= max) {
3150		const paymentRequest = afterPaybuildPaymentRequest(payments, current_form_id, currency);
3151		afterpay = await payments.afterpayClearpay(paymentRequest);
3152		await afterpay.attach('#afterpay-button-' + current_form_id);
3153		return afterpay;
3154	}
3155	else if (!isNaN(amount) && wpep_local_vars.wpep_square_user_defined_amount != 'on') {
3156		const paymentRequest = afterPaybuildPaymentRequest(payments, current_form_id, currency);
3157		afterpay = await payments.afterpayClearpay(paymentRequest);
3158
3159		setTimeout(function () {
3160			afterpay.attach('#afterpay-button-' + current_form_id);
3161		}, 2000);
3162		return afterpay;
3163	}
3164	else if (!isNaN(amount)
3165		&&
3166		wpep_local_vars.wpep_square_amount_type == 'payment_radio'
3167		|| wpep_local_vars.wpep_square_amount_type == 'payment_drop'
3168		|| wpep_local_vars.wpep_square_amount_type == 'payment_custom'
3169		|| wpep_local_vars.wpep_square_amount_type == 'payment_tabular'
3170		|| wpep_local_vars.wpep_square_amount_type == 'tabular_layout_for_square'
3171	) {
3172		const paymentRequest = afterPaybuildPaymentRequest(payments, current_form_id, currency);
3173		afterpay = await payments.afterpayClearpay(paymentRequest);
3174		await afterpay.attach('#afterpay-button-' + current_form_id);
3175		return afterpay;
3176	}
3177	else {
3178		jQuery('#afterpay-amount').show();
3179	}
3180}
3181async function applepaybuildPaymentRequest(payments, current_form_id, currency, applePay) {
3182
3183	var req = {};
3184	amount = jQuery('#amount_display_' + current_form_id).text();
3185	coupon_apply = jQuery('#wpep-coupons-' + current_form_id).length;
3186	if (coupon_apply > 0) {
3187		jQuery('.cp-apply').click(function () {
3188			setTimeout(function () {
3189				if (jQuery('input[name="wpep-selected-amount"]').val().trim() != '') {
3190					amount = jQuery('input[name="wpep-selected-amount"]').val();
3191				} else {
3192					amount = jQuery('#amount_display_' + current_form_id).text();
3193				}
3194			}, 1000);
3195		})
3196	}
3197	amount = amount.trim();
3198	amount = amount.split(' ')[0];
3199	amount = amount.replace('$', '');
3200
3201	req[current_form_id] = payments.paymentRequest({
3202		countryCode: 'US',
3203		currencyCode: currency,
3204		total: {
3205			amount: amount.replace(/[^0-9\.]/gi, '').toString("#0000\\.0000"),
3206			label: 'Total',
3207		},
3208		requestShippingContact: true,
3209	});
3210
3211
3212	return req[current_form_id];
3213}
3214async function initializeApplepay(payments, current_form_id, currency, applePay) {
3215
3216	if (applePay == undefined) {
3217		var applePay = {};
3218	}
3219
3220	var max = parseFloat(jQuery('.otherPayment').attr('max'));
3221	var min = parseFloat(jQuery('.otherPayment').attr('min'));
3222	var val = jQuery('.otherPayment').val();
3223
3224	var amount = jQuery('#amount_display_' + current_form_id).text();
3225	amount = amount.trim();
3226	amount = amount.split(' ');
3227	amount = amount[0];
3228	amount = amount.replace(wpep_local_vars.wpep_currency_symbol, "");
3229	if (val == '') {
3230		jQuery('.otherPayment').val(min);
3231		val = min;
3232	}
3233
3234
3235	if ((val != '' && val >= min && val <= max) || (!isNaN(amount) && amount >= min && amount <= max) && wpep_local_vars.wpep_square_user_defined_amount == 'on') {
3236
3237		const paymentRequest = await applepaybuildPaymentRequest(payments, current_form_id, currency, applePay);
3238
3239		applePay = await payments.applePay(paymentRequest);
3240
3241		jQuery('#applepay-amount').hide();
3242
3243		return applePay;
3244	} else if (!isNaN(amount) && wpep_local_vars.wpep_square_user_defined_amount != 'on') {
3245
3246		const paymentRequest = await applepaybuildPaymentRequest(payments, current_form_id, currency, applePay);
3247
3248		applePay = await payments.applePay(paymentRequest);
3249
3250		jQuery('#applepay-amount').hide();
3251
3252		return applePay;
3253	} else if (!isNaN(amount) && wpep_local_vars.wpep_square_amount_type == 'payment_radio' || wpep_local_vars.wpep_square_amount_type == 'payment_drop' || wpep_local_vars.wpep_square_amount_type == 'payment_tabular' || wpep_local_vars.wpep_square_amount_type == 'tabular_layout_for_square') {
3254
3255		const paymentRequest = await applepaybuildPaymentRequest(payments, current_form_id, currency, applePay);
3256
3257		applePay = await payments.applePay(paymentRequest);
3258
3259		jQuery('#applepay-amount').hide();
3260
3261		return applePay;
3262	} else {
3263		jQuery('#applepay-amount').show();
3264
3265	}
3266}
3267
3268async function initializeGooglepay(payments, current_form_id, currency, googlePay) {
3269
3270	if (googlePay && typeof googlePay.destroy === "function") {
3271		await googlePay.destroy();
3272	}
3273
3274	var max = parseFloat(jQuery('.otherPayment').attr('max'));
3275	var min = parseFloat(jQuery('.otherPayment').attr('min'));
3276	var val = jQuery('.otherPayment').val();
3277
3278	var amount = jQuery('#amount_display_' + current_form_id).text();
3279	amount = amount.trim();
3280	amount = amount.split(' ');
3281	amount = amount[0];
3282	amount = amount.replace(wpep_local_vars.wpep_currency_symbol, "");
3283
3284	if (val == '') {
3285		jQuery('.otherPayment').val(min);
3286		val = min;
3287	}
3288
3289	var parsedVal = parseFloat(val);
3290	var parsedAmount = parseFloat(amount);
3291
3292	if ((parsedVal > 0 && parsedVal >= min && parsedVal <= max) || (!isNaN(parsedAmount) && parsedAmount > 0 && parsedAmount >= min && parsedAmount <= max) && wpep_local_vars.wpep_square_user_defined_amount == 'on') {
3293		const paymentRequest = gpaybuildPaymentRequest(payments, current_form_id, currency, googlePay);
3294
3295		const gPay = await payments.googlePay(paymentRequest);
3296
3297		await gPay.attach('#google-pay-button-' + current_form_id);
3298		jQuery('#gpay-amount').hide();
3299
3300		return gPay;
3301	} else if (!isNaN(parsedAmount) && parsedAmount > 0 && wpep_local_vars.wpep_square_user_defined_amount != 'on') {
3302		const paymentRequest = gpaybuildPaymentRequest(payments, current_form_id, currency, googlePay);
3303		const gPay = await payments.googlePay(paymentRequest);
3304		await gPay.attach('#google-pay-button-' + current_form_id);
3305		jQuery('#gpay-amount').hide();
3306		return gPay;
3307	} else if (!isNaN(parsedAmount) && parsedAmount > 0 && (wpep_local_vars.wpep_square_amount_type == 'payment_radio' || wpep_local_vars.wpep_square_amount_type == 'payment_drop' || wpep_local_vars.wpep_square_amount_type == 'payment_tabular' || wpep_local_vars.wpep_square_amount_type == 'tabular_layout_for_square')) {
3308		const paymentRequest = gpaybuildPaymentRequest(payments, current_form_id, currency, googlePay);
3309		const gPay = await payments.googlePay(paymentRequest);
3310		await gPay.attach('#google-pay-button-' + current_form_id);
3311		jQuery('#gpay-amount').hide();
3312		return gPay;
3313	} else {
3314		jQuery('#gpay-amount').show();
3315	}
3316}
3317
3318async function initializeCashApp(payments, current_form_id, currency) {
3319	var max = parseFloat(jQuery('.otherPayment').attr('max'));
3320	var min = parseFloat(jQuery('.otherPayment').attr('min'));
3321	var val = jQuery('.otherPayment').val();
3322
3323	var amount = jQuery('#amount_display_' + current_form_id).text();
3324	amount = amount.trim();
3325	amount = amount.replace(currency + " ", "");
3326	if (val == '') {
3327		jQuery('.otherPayment').val(min);
3328		val = min;
3329	}
3330	if ((val != '' && val >= min && val <= max) || (!isNaN(amount) && amount >= min && amount <= max) && wpep_local_vars.wpep_square_user_defined_amount == 'on') {
3331		const paymentRequest = cashAppbuildPaymentRequest(payments, current_form_id, currency);
3332		cashAppPay = await payments.cashAppPay(paymentRequest, {
3333			redirectURL: 'https://my.website/checkout',
3334			referenceId: 'my-website-00000001',
3335		});
3336		await cashAppPay.attach('#cash-app-pay-' + current_form_id);
3337		return cashAppPay;
3338	} else if (!isNaN(amount) && wpep_local_vars.wpep_square_user_defined_amount != 'on') {
3339		const paymentRequest = cashAppbuildPaymentRequest(payments, current_form_id, currency)
3340		cashAppPay = await payments.cashAppPay(paymentRequest, {
3341			redirectURL: 'https://my.website/checkout',
3342			referenceId: 'my-website-00000001',
3343		});
3344		await cashAppPay.attach('#cash-app-pay-' + current_form_id);
3345		return cashAppPay;
3346	} else if (
3347		wpep_local_vars.wpep_square_amount_type == 'payment_radio'
3348		|| wpep_local_vars.wpep_square_amount_type == 'payment_custom'
3349		|| wpep_local_vars.wpep_square_amount_type == 'payment_drop'
3350		|| wpep_local_vars.wpep_square_amount_type == 'payment_tabular'
3351		|| wpep_local_vars.wpep_square_amount_type == 'tabular_layout_for_square'
3352	) {
3353		const paymentRequest = cashAppbuildPaymentRequest(payments, current_form_id, currency)
3354		cashAppPay = await payments.cashAppPay(paymentRequest, {
3355			redirectURL: 'https://my.website/checkout',
3356			referenceId: 'my-website-00000001',
3357		});
3358		await cashAppPay.attach('#cash-app-pay-' + current_form_id);
3359		return cashAppPay;
3360	} else {
3361		jQuery('#cashapp-amount').show();
3362	}
3363}
3364
3365function cleanUpDuplicateGiftCards() {
3366	jQuery('#sq-gift-card-coupen .sq-card-wrapper').slice(1).remove();
3367}
3368
3369 async function initializeGiftcard(payments, current_form_id, currency) {
3370	var max          = parseFloat( jQuery( '.otherPayment' ).attr( 'max' ) );
3371	var min          = parseFloat( jQuery( '.otherPayment' ).attr( 'min' ) );
3372	var val          = jQuery(  '.otherPayment'  ).val();
3373
3374	var amount = jQuery('#amount_display_' + current_form_id).text();
3375	amount = amount.trim();
3376	amount = amount.replace(currency + " ", "");
3377	if (val == '') {
3378		jQuery('.otherPayment').val(min);
3379		val = min;
3380	}
3381	if ((val != '' && val >= min && val <= max) || (!isNaN(amount) && amount >= min && amount <= max) && wpep_local_vars.wpep_square_user_defined_amount == 'on') {
3382		const giftCard = await payments.giftCard();
3383		await giftCard.attach('#sq-gift-card-coupen');
3384		cleanUpDuplicateGiftCards();
3385
3386		return giftCard;
3387	} else if (!isNaN(amount) && wpep_local_vars.wpep_square_user_defined_amount != 'on') {
3388		const giftCard = await payments.giftCard();
3389		await giftCard.attach('#sq-gift-card-coupen');
3390		cleanUpDuplicateGiftCards();
3391
3392		return giftCard;
3393	} else if (
3394		wpep_local_vars.wpep_square_amount_type == 'payment_radio'
3395		|| wpep_local_vars.wpep_square_amount_type == 'payment_custom'
3396		|| wpep_local_vars.wpep_square_amount_type == 'payment_drop'
3397		|| wpep_local_vars.wpep_square_amount_type == 'payment_tabular'
3398		|| wpep_local_vars.wpep_square_amount_type == 'tabular_layout_for_square'
3399	) {
3400		const giftCard = await payments.giftCard();
3401		await giftCard.attach('#sq-gift-card-coupen');
3402		cleanUpDuplicateGiftCards();
3403
3404		return giftCard;
3405	} else {
3406		jQuery('#giftcard-amount').show();
3407
3408	}
3409}
3410
3411
3412
3413
3414
3415function initializePayments( appId, locationId ) {
3416	return window.Square.payments(appId, locationId);
3417}
3418function destroyGooglePay() {
3419	if (jQuery('#google-pay-button').is(':visible')) {
3420		googlePay.destroy();
3421	}
3422}
3423
3424async function displayApplePay(payments, current_form_id, currency, applePay, app_btn) {
3425
3426	var amount = jQuery('#amount_display_' + current_form_id).text();
3427	amount = amount.trim();
3428	amount = amount.replace(currency, "");
3429	if (applePay == undefined) {
3430		var applePay = {};
3431	}
3432
3433	if (currency !== amount) {
3434
3435
3436		try {
3437			/* const divElement = document.getElementById("testing_apple");
3438
3439			// Convert the applePay object to a string
3440			const applePayString = JSON.stringify(applePay, null, 2);
3441
3442			// Create a text node with the string representation of the applePay object
3443			const textNode = document.createTextNode(applePayString);
3444
3445			// Append the text node to the div element
3446			divElement.appendChild(textNode); */
3447
3448			applePay = await initializeApplepay(payments, current_form_id, currency, applePay[current_form_id]);
3449
3450
3451
3452
3453		} catch (e) {
3454			console.error('Initializing Applepay failed', e);
3455		}
3456	} else {
3457		jQuery('#applePay-' + current_form_id).html('<p>Please define amount from Admin</p>')
3458	}
3459
3460	return applePay;
3461
3462}
3463
3464async function displayGooglePay(payments, current_form_id, currency, googlePay) {
3465
3466	var amount = jQuery('#amount_display_' + current_form_id).text();
3467	amount = amount.trim();
3468	amount = amount.replace(currency, "");
3469	if (googlePay == undefined) {
3470		var googlePay = {};
3471	}
3472	if (currency !== amount) {
3473		try {
3474			googlePay[current_form_id] = await initializeGooglepay(payments, current_form_id, currency, googlePay[current_form_id]);
3475			jQuery('.loader').hide();
3476
3477
3478
3479			let timeoutpayId;
3480
3481			function handleDOMChanges() {
3482				clearTimeout(timeoutpayId);
3483
3484				timeoutpayId = setTimeout(async function () {
3485					try {
3486						googlePay[current_form_id] = await initializeGooglepay(payments, current_form_id, currency, googlePay[current_form_id]);
3487						jQuery('.loader').hide();
3488
3489					} catch (e) {
3490						console.error('Initializing Googlepay failed', e);
3491						jQuery('.loader').hide();
3492					}
3493				}, 1000);
3494			}
3495
3496			// Use Mutation Observer to detect DOM changes
3497			const observer = new MutationObserver(handleDOMChanges);
3498
3499			// Observe changes in the amount display element
3500			const amountDisplayElement = document.getElementById('amount_display_' + current_form_id);
3501			if (amountDisplayElement) {
3502				observer.observe(amountDisplayElement, { subtree: true, childList: true });
3503			}
3504
3505
3506
3507
3508
3509		} catch (e) {
3510			console.error('Initializing Googlepay failed', e);
3511		}
3512	} else {
3513		jQuery('#google-pay-button-' + current_form_id).html('<p>Please define amount from Admin</p>')
3514	}
3515
3516
3517
3518	return googlePay[current_form_id];
3519
3520}
3521
3522async function displayAfterPay(payments, current_form_id, currency) {
3523
3524	var amount = jQuery('#amount_display_' + current_form_id).text();
3525	amount = amount.trim();
3526	amount = amount.replace(currency + " ", "");
3527	if (currency !== amount) {
3528
3529		let afterpay;
3530		try {
3531			jQuery('.loader').show();
3532			afterpay = await initializeAfterpay(payments, current_form_id, currency);
3533			jQuery('.loader').hide();
3534		} catch (e) {
3535			console.error('Initializing Afterpay/Clearpay failed', e);
3536		}
3537	} else {
3538		jQuery('#afterpay-amount').show();
3539
3540	}
3541
3542	jQuery('.other-' + current_form_id).click(function () {
3543		let timeoutId;
3544		jQuery('.other-' + current_form_id).on('input', function () {
3545
3546			jQuery('#afterpay-amount').hide();
3547
3548			clearTimeout(timeoutId);
3549			timeoutId = setTimeout(function () {
3550				if (afterpay) {
3551					afterpay.destroy();
3552				}
3553
3554				let afterpay;
3555				try {
3556					jQuery('.loader').show();
3557					afterpay = initializeAfterpay(payments, current_form_id, currency);
3558					jQuery('.loader').hide();
3559				} catch (e) {
3560					console.error('Initializing Afterpay/Clearpay failed', e);
3561				}
3562
3563
3564			}, 1000);
3565		});
3566	});
3567
3568	let timeoutQtyId;
3569	jQuery('#wpep_quantity_' + current_form_id).on('input', function () {
3570
3571		jQuery('#afterpay-amount').hide();
3572
3573		clearTimeout(timeoutQtyId);
3574		timeoutQtyId = setTimeout(function () {
3575
3576			if (afterpay) {
3577				afterpay.destroy();
3578			}
3579			let afterpay;
3580			try {
3581				jQuery('.loader').show();
3582				afterpay = initializeAfterpay(payments, current_form_id, currency);
3583				jQuery('.loader').hide();
3584			} catch (e) {
3585				console.error('Initializing Afterpay/Clearpay failed', e);
3586			}
3587
3588
3589		}, 1000);
3590	});
3591	// Product Table
3592
3593	//Drop Down & Radio clicked event
3594	let timeoutChangeId;
3595	jQuery('input[name="wpep-selected-amount"]').on('change', function () {
3596
3597		if (wpep_local_vars.afterpay == 'on') {
3598			jQuery('#afterpay-amount').hide();
3599			if (jQuery('#afterpay-button-' + current_form_id).html().length > 1) {
3600				afterpay.destroy();
3601			}
3602			clearTimeout(timeoutChangeId);
3603			timeoutChangeId = setTimeout(function () {
3604
3605
3606				let afterpay;
3607				try {
3608					jQuery('.loader').show();
3609					afterpay = initializeAfterpay(payments, current_form_id, currency);
3610					jQuery('.loader').hide();
3611				} catch (e) {
3612					console.error('Initializing Afterpay/Clearpay failed', e);
3613				}
3614
3615
3616			}, 2500);
3617		}
3618	});
3619	let timeoutpayId;
3620	jQuery('.payamount-' + current_form_id).on('click', function (event) {
3621
3622		jQuery('#afterpay-amount').hide();
3623
3624		clearTimeout(timeoutpayId);
3625		timeoutpayId = setTimeout(function () {
3626			if (afterpay) {
3627				afterpay.destroy();
3628			}
3629			let afterpay;
3630			try {
3631
3632				afterpay = initializeAfterpay(payments, current_form_id, currency);
3633				jQuery('.loader').hide();
3634			} catch (e) {
3635				console.error('Initializing Afterpay/Clearpay failed', e);
3636			}
3637
3638
3639		}, 2000);
3640	});
3641	return afterpay;
3642}
3643jQuery('.other-' + current_form_id).click(function () {
3644	let timeoutId;
3645	jQuery('.other-' + current_form_id).on('input', function () {
3646		if (wpep_local_vars.cashapp == 'on') {
3647			jQuery('#cashapp-amount').hide();
3648			clearTimeout(timeoutId);
3649			timeoutId = setTimeout(function () {
3650				if (cashAppPay) {
3651					cashAppPay.destroy();
3652				}
3653				let cashAppPay;
3654				try {
3655
3656					// Check if Cash App Pay is already attached before reinitializing
3657					if (typeof cashAppPay === 'undefined') {
3658						var current_form_id = jQuery('form.wpep_payment_form').data('id');
3659						var currency = jQuery('form.wpep_payment_form').data('currency');
3660						jQuery('.loader').show();
3661						cashAppPay = initializeCashApp(payments, current_form_id, currency);
3662						jQuery('.loader').hide();
3663					}
3664				} catch (e) {
3665					console.error('Initializing Cash App Pay failed', e);
3666				}
3667
3668			}, 1000);
3669		}
3670	});
3671	let timeoutQtyId;
3672	jQuery('#wpep_quantity_' + current_form_id).on('input', function () {
3673		if (wpep_local_vars.cashapp == 'on') {
3674			jQuery('#cashapp-amount').hide();
3675			if (jQuery('#cash_app_pay_v1_element').is(':visible')) {
3676
3677			}
3678			clearTimeout(timeoutId);
3679			timeoutId = setTimeout(function () {
3680				if (cashAppPay) {
3681					cashAppPay.destroy();
3682				}
3683				let cashAppPay;
3684				try {
3685
3686					// Check if Cash App Pay is already attached before reinitializing
3687					if (typeof cashAppPay === 'undefined') {
3688						var current_form_id = jQuery('form.wpep_payment_form').data('id');
3689						var currency = jQuery('form.wpep_payment_form').data('currency');
3690						jQuery('.loader').show();
3691						cashAppPay = initializeCashApp(payments, current_form_id, currency);
3692						jQuery('.loader').hide();
3693					}
3694
3695				} catch (e) {
3696					console.error('Initializing Cash App Pay failed', e);
3697				}
3698
3699			}, 1000);
3700		}
3701	});
3702});
3703jQuery(window).on('load', function () {
3704	if (wpep_local_vars.recaptcha_version == 'v3' && wpep_local_vars.enable_recaptcha == 'on') {
3705		grecaptcha.ready(function () {
3706			grecaptcha.execute(wpep_local_vars.recaptcha_site_key_v3, { action: 'validate_captcha' })
3707				.then(function (token) {
3708
3709					document.getElementById('g-recaptcha-response').value = token;
3710					jQuery('.wpep_payment_form').append('<input type="hidden" id="wpep_recaptcha" name="wpep_recaptcha" value="' + token + '">');
3711
3712				});
3713		});
3714	}
3715	jQuery('.payamount-' + current_form_id).click(function (event) {
3716		if (wpep_local_vars.cashapp == 'on') {
3717			let timeoutId;
3718			jQuery('#cashapp-amount').hide();
3719			if (cashAppPay) {
3720				cashAppPay.destroy();
3721			}
3722			clearTimeout(timeoutId);
3723			timeoutId = setTimeout(function () {
3724				let cashAppPay;
3725				try {
3726					// Check if Cash App Pay is already attached before reinitializing
3727					if (typeof cashAppPay === 'undefined') {
3728						var current_form_id = jQuery('form.wpep_payment_form').data('id');
3729						var currency = jQuery('form.wpep_payment_form').data('currency');
3730						cashAppPay = initializeCashApp(payments, current_form_id, currency);
3731						jQuery('.loader').hide();
3732					}
3733				} catch (e) {
3734					console.error('Initializing Cash App Pay failed', e);
3735				}
3736			}, 1000);
3737		}
3738	})
3739	jQuery('input[name="wpep-selected-amount"]').on('change', function () {
3740		if (wpep_local_vars.cashapp == 'on') {
3741			let timeChangeId;
3742			jQuery('#cashapp-amount').hide();
3743			if (jQuery('#cash_app_pay_v1_element').is(":visible") && jQuery('#cash_app_pay_v1_element').html().length > 1) {
3744				cashAppPay.destroy();
3745			}
3746			clearTimeout(timeChangeId);
3747			timeChangeId = setTimeout(function () {
3748				let cashAppPay;
3749				try {
3750					// Check if Cash App Pay is already attached before reinitializing
3751					if (typeof cashAppPay === 'undefined') {
3752						var current_form_id = jQuery('form.wpep_payment_form').data('id');
3753						var currency = jQuery('form.wpep_payment_form').data('currency');
3754						cashAppPay = initializeCashApp(payments, current_form_id, currency);
3755						jQuery('.loader').hide();
3756					}
3757				} catch (e) {
3758					console.error('Initializing Cash App Pay failed', e);
3759				}
3760			}, 1000);
3761		}
3762	})
3763});
3764
3765async function displayCashApp(payments, current_form_id, currency) {
3766
3767	var amount = jQuery('#amount_display_' + current_form_id).text();
3768	amount = amount.trim();
3769	amount = amount.replace(currency + " ", "");
3770
3771	if (currency !== amount) {
3772		let cashAppPay;
3773		try {
3774			jQuery('.loader').show();
3775			cashAppPay = await initializeCashApp(payments, current_form_id, currency);
3776			jQuery('.loader').hide();
3777		} catch (e) {
3778			console.error('Initializing Cash App Pay failed', e);
3779		}
3780	} else {
3781		jQuery('#cashapp-amount').show();
3782	}
3783
3784	return cashAppPay;
3785
3786
3787}
3788
3789async function displayGiftcard(payments, current_form_id, currency) {
3790	let giftcard = null;
3791	var amount = jQuery('#amount_display_' + current_form_id).text();
3792	amount = amount.trim();
3793	amount = amount.replace(currency + " ", "");
3794	var selected_payment_tab = jQuery(`ul.wpep_tabs-${current_form_id} li.tab-link.current`).data('tab');
3795	// if(selected_payment_tab){
3796	if (currency !== amount) {
3797		try {
3798			jQuery('.loader').show();
3799
3800			giftcard = await initializeGiftcard(payments, current_form_id, currency);
3801
3802			jQuery('.loader').hide();
3803		} catch (e) {
3804			console.error('Initializing Giftcard failed', e);
3805		}
3806	} else {
3807		jQuery('#giftcard-amount').show();
3808	}
3809
3810
3811	return giftcard;
3812	// }
3813}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.