(function ($) {
	"use strict";

	/**
	 * All of the code for your public-facing JavaScript source
	 * should reside in this file.
	 *
	 * Note: It has been assumed you will write jQuery code here, so the
	 * $ function reference has been prepared for usage within the scope
	 * of this function.
	 *
	 * This enables you to define handlers, for when the DOM is ready:
	 *
	 * $(function() {
	 *
	 * });
	 *
	 * When the window is loaded:
	 *
	 * $( window ).load(function() {
	 *
	 * });
	 *
	 * ...and/or other possibilities.
	 *
	 * Ideally, it is not considered best practise to attach more than a
	 * single DOM-ready or window-load handler for a particular page.
	 * Although scripts in the WordPress core, Plugins and Themes may be
	 * practising this, we should strive to set a better example in our own work.
	 */

	// Survey form feedback script
	document.addEventListener("DOMContentLoaded", function () {
		// Loop over outer containers to handle multiple forms independently
		const formContainers = document.querySelectorAll(".peet-custom-form-block");

		formContainers.forEach(container => {
			// Get the inner form for this container
			const form = container.querySelector(".contact-form");
			if (!form) return;

			// Scope steps to current form
			const steps = form.querySelectorAll(".peet-survey-form__section");
			// Scope submit button to current form
			const submitBtn = form.querySelector(".peet-survey-form__submit");
			let currentStep = 0;

			steps.forEach(step => {
				const legend = step.querySelector(".peet-survey-form__question");
				if (legend) {
					const counterSpan = document.createElement("span");
					counterSpan.className = "peet-survey-form__counter";
					step.parentNode.insertBefore(counterSpan, step);
				}
			});

			function showStep(index) {
				steps.forEach((step, i) => {
					step.classList.toggle("active", i === index);
					const counterSpan = step.previousElementSibling;
					if (counterSpan && counterSpan.classList.contains("peet-survey-form__counter")) {
						counterSpan.textContent = i === index ? `Question ${i + 1} of ${steps.length}` : "";
					}
				});

				if( 0 < index  ){
					const backBtn = steps[index].querySelector(".back-step");
					if (backBtn) {
						backBtn.style.display = index === 0 ? "none" : "flex";
					}
				}

				const nextBtn = steps[index].querySelector(".next-step");
				let answered = false;
				if (nextBtn) {
					const inputs = steps[index].querySelectorAll("input, select");
					// check if the select is selected
					if( inputs.length > 0 && inputs[0].tagName === "SELECT" ) {
						inputs.forEach(input => {
							if (input.tagName === "SELECT" && input.value && input.value !== "") {
								answered = true;
							}
						});	
					} else {
						inputs.forEach(input => {
							if (input.checked) answered = true;
						});
					}
					nextBtn.style.display = ( index === steps.length - 1 ) || !answered ? "none" : "flex";
				}

				if (submitBtn) {
					submitBtn.style.display = index === steps.length - 1 ? "block" : "none";
					submitBtn.disabled = answered ? false : true; // disabled until answer selected
				}
			}

			steps.forEach((step, i) => {
				step.querySelectorAll("input, select").forEach(input => {
					input.addEventListener("change", function () {
						//enable the next button
						const nextBtn = step.querySelector(".next-step");
						if (nextBtn) {
							nextBtn.style.display = "inline-block";
						}
						
						if( currentStep === steps.length - 1 ) {
							checkLastStepAnswered();
						}
					});
				});

				const backBtn = step.querySelector(".back-step");
				if (backBtn) {
					backBtn.addEventListener("click", function () {
						if (i > 0) {
							currentStep = i - 1;
							showStep(currentStep);
						}
					});
				}
				const nextBtn = step.querySelector(".next-step");
				if (nextBtn) {
					nextBtn.addEventListener("click", function () {
						if (i < steps.length - 1) {
							currentStep = i + 1;
							showStep(currentStep);
						}
					});
				}
			});

			function checkLastStepAnswered() {
				const lastInputs = steps[steps.length - 1].querySelectorAll("input, select");
				// check if the select is selected
				let answered = false;
				if( lastInputs.length > 0 && lastInputs[0].tagName === "SELECT" ) {
					lastInputs.forEach(input => {
						if (input.tagName === "SELECT" && input.value && input.value !== "") {
							answered = true;
						}
					});	
				} else {
					lastInputs.forEach(input => {
						if (input.checked) answered = true;
					});
				}
				if (submitBtn) submitBtn.disabled = !answered;
			}

			// Initialize for current form
			showStep(currentStep);
		});
	});

	jQuery(document).ready(function () {

		if (
			document.getElementsByClassName("captcha-field").length > 0 &&
			ccf_settings &&
			ccf_settings.captcha_key
		) {
			var script = document.createElement("script");
			script.type = "text/javascript";
			script.src = "https://www.google.com/recaptcha/api.js";
			document.body.appendChild(script);
			var captchaInt = setInterval(() => {
				if (window.grecaptcha && window.grecaptcha.render) {
					var captchaFields = document.getElementsByClassName("captcha-field");
					for (var i = 0; i < captchaFields.length; i++) {
						grecaptcha.render(captchaFields[i], {
							sitekey: ccf_settings.captcha_key,
						});
					}
					clearInterval(captchaInt);
				}
			}, 500);
		}

		if (jQuery(".wp-block-contact-form .datepicker").length > 0) {
			jQuery(".datepicker").datepicker({
				yearRange: "c-100:c+10",
				dateFormat: "mm/dd/yy", // Set the date format as needed
				changeMonth: true, // Allow the month to be changed directly
				changeYear: true, // Allow the year to be changed directly
			});
			jQuery("#tour_date").datepicker("setDate", "today");
			jQuery("#Date_Requested, #tour_date").datepicker("option", "minDate", 0); // Enable only future dates

			if (jQuery("#gf_end_date").length > 0) {
				var minDate = new Date();
				minDate.setDate(minDate.getDate() + 60); // Set the start of the range to 60 days from now

				var maxDate = new Date(minDate);
				maxDate.setFullYear(maxDate.getFullYear() + 1); // Set the end of the range to 12 months from the minDate

				jQuery("#gf_end_date").datepicker("option", "minDate", minDate);
				jQuery("#gf_end_date").datepicker("option", "maxDate", maxDate);
				jQuery("#gf_end_date").datepicker("setDate", minDate);

				jQuery(".datepicker").each(function () {
					var $this = jQuery(this);
					if ($.datepicker._getInst($this[0])) {
						$this.keydown(function (e) {
							return false; // Prevent keydown events
						});
					}
				});
			}
		}

		// Check if the label with the class "conditional-visibility" exists
		if (jQuery("label.conditional-visibility").length > 0) {
			jQuery("label.conditional-visibility").each(function () {
				var label = jQuery(this);
				var select = label.prev("select");
				var input = label.next("input");

				if (select.length > 0) {
					select.change(function () {
						var selectedOptionIndex = select.prop("selectedIndex");
						var lastOptionIndex = select.find("option").length - 1;

						// Check if the last option is selected
						if (selectedOptionIndex === lastOptionIndex) {
							label.show();
							input.show();
						} else {
							label.hide();
							input.hide();
						}
					});
				}
			});
		}
	});

	$(document).ready(function () {

		$(".peet-custom-form-block .contact-form").each(function () {
			var $currentForm = $(this);
			var $enquireForm = $currentForm.parents(".enquire-form");

			if ($enquireForm.length) {
				if ($currentForm.find(".contact-form-loader").length === 0) {
					$enquireForm.find(".contact-form-loader").remove();
					$currentForm.prepend("<div class='contact-form-loader'></div>");
				}
			}
		});


		// Add a custom validation method for mobile number
		$.validator.addMethod("validMobile", function (value, element) {
			// This checks if the value matches the pattern of 10 or more digits
			return this.optional(element) || /^[0-9]{10,}$/.test(value);
		}, "Please enter a valid mobile number (10 or more digits).");

		validateFormSubmission();
		function validateFormSubmission() {
			if ($(".peet-custom-form-block .contact-form").length) {
				// Loop through each contact form
				$(".peet-custom-form-block .contact-form").each(function () {
					var $form = $(this);
					var rules = {};
					var messages = {};

					// Loop through each field-wrap to build the rules and messages
					$form.find(".field-wrap.required").each(function () {
						var $fieldWrap = $(this);
						var $input = $fieldWrap.find("input, select, textarea"); // Include textarea

						var fieldName = $input.attr("name");
						var fieldLabel = $fieldWrap
							.find(".field-label")
							.text()
							.replace("*", "")
							.trim();

						// Add a required rule for this field
						rules[fieldName] = {
							required: true,
						};

						// Add a dynamic error message based on the label text
						messages[fieldName] = {
							required: `${fieldLabel} is required.`,
						};

						// Handle specific input types
						if ($input.attr("type") === "email") {
							rules[fieldName].email = true;
							messages[fieldName].email = "Please enter a valid email address.";
						} else if ($input.attr("type") === "tel") {
							// Use the custom method for mobile number validation
							rules[fieldName].validMobile = true;
							messages[fieldName].validMobile = "Please enter a valid mobile number.";
						} else if ($input.attr("type") === "checkbox") {
							// Custom rule for checkbox (ensure at least one checkbox is checked)
							var checkboxGroupName = fieldName; // Use the name attribute for grouping
							rules[checkboxGroupName] = {
								required: true,
							};
							messages[checkboxGroupName] = {
								required: `Please select at least one ${fieldLabel.toLowerCase()}.`,
							};
						} else if ($input.is("textarea")) {
							// Additional validation for textareas can go here if needed
						} else if ($input.attr("type") === "file") {
							// Custom file validation
							rules[fieldName] = {
								required: true,
								extension: "pdf,doc,png,xlsx,pptx,jpg", // Specify allowed file types
							};
							messages[fieldName] = {
								required: `${fieldLabel} is required.`,
								extension: `Please upload a valid file type (pdf, doc, png, xlsx, pptx, jpg).`,
							};
						}
					});

					var postCodeField = $form.find('input[name="post_code"]');
					if (postCodeField.length) {
						// Create a span element to display the suburb information
						var suburbField = $('<span>', {
							class: 'suburb-display',
							text: 'Please select a suburb from the dropdown.' // Placeholder text
						});
						postCodeField.after(suburbField);

						var suburbInput = $form.find('input[name="suburb"]');

						postCodeField.on("input", function () {
							var postcode = $(this).val();
							if (postcode.length >= 3) {
								fetchSuburbData(postcode);
							} else {
								$(".suburb-suggestions").remove();
								suburbField.text("Please select a suburb from the dropdown.");

								// Clear the hidden input values when no suggestions or postcode is removed
								suburbInput.val('');
							}
						});

						function fetchSuburbData(postcode) {
							$.ajax({
								url: ccf_settings.ajaxUrl,
								type: 'POST',
								dataType: 'json',
								data: {
									action: 'get_suburb_state',
									postcode: postcode,
									nonce: ccf_settings.ajax_nonce
								},
								success: function (response) {
									if (response.success) {
										displaySuburbSuggestions(response.data);
									}
								},
								error: function (jqXHR, textStatus, errorThrown) {

								}
							});
						}

						function displaySuburbSuggestions(data) {
							console.log("Displaying suggestions:", data);
							$(".suburb-suggestions").remove();
							var $suggestionsContainer = $('<ul class="suburb-suggestions"></ul>');

							// Check if data is empty
							if (data.length === 0) {
								suburbField.text('Please select a suburb from the dropdown.'); // Update text when no data is available
								return; // Exit the function if no data is found
							}

							$.each(data, function (index, item) {
								var $suggestionItem = $('<li></li>', {
									class: 'active',
									'data-value': item.postcode,
									style: 'padding-left: 10px; padding-right: 10px;',
									html: `<b>${item.postcode}</b> (${item.suburb}, ${item.state})`
								});

								$suggestionItem.on('click', function (event) {
									event.stopPropagation();
									suburbField.text(`${item.suburb}, ${item.state}`); // Update suburb and state in the span
									postCodeField.val(item.postcode); // Set the full postcode in the postcode field

									// Set hidden input values for suburb
									suburbInput.val(item.suburb);

									$suggestionsContainer.remove(); // Remove suggestions after selection
								});

								$suggestionsContainer.append($suggestionItem);
							});

							suburbField.after($suggestionsContainer);
						}
					}

					// Initialize validation for the current form
					$form.validate({
						rules: rules,
						messages: messages,
						errorElement: "div",
						errorPlacement: function (error, element) {
							error.addClass("error-message");
							error.insertAfter(element.closest(".field-container"));
						},
						submitHandler: function (form, event) {
							event.preventDefault(); // Prevent default form submission
							var $currentContactForm = $(form);
							var $currentFormContainer = $currentContactForm.closest(".wp-block-contact-form"); // Parent container for the form
							var $contactloader;

							// Check if loader is inside or outside the form container
							if ($currentFormContainer.find(".contact-form-loader").length > 0) {
								// Loader is inside the form container
								$contactloader = $currentFormContainer.find(".contact-form-loader");
							} else if ($currentFormContainer.prev(".contact-form-loader").length > 0) {
								// Loader is outside the form container (directly above)
								$contactloader = $currentFormContainer.prev(".contact-form-loader");
							}

							if ($contactloader) {
								$contactloader.show(); // Show the loader
							}

							// Clear any previous messages
							$form.closest(".wp-block-contact-form").find(".contact-form-message").html("");
							
							// Prevent multiple simultaneous submissions
							var isSubmitting = false;
							
							// Prevent duplicate submissions
							if (isSubmitting) {
								return;
							}
							
							isSubmitting = true;
							
							// Serialize form data
							var formDataString = $form.serialize();
							
							// Perform an AJAX call on form submission
							$.ajax({
								url: ccf_settings.ajaxUrl,
								dataType: "json",
								type: "POST",
								data: {
									action: "peet_validate_form_submission", // Action for the callback
									formData: formDataString, // Serialize form data
									pageTitle: ccf_settings.page_title
								},
								success: function (response) {
									isSubmitting = false; // Reset submission flag
									
									if (response.submitted) {
										if (response.is_survey_form) {
											jQuery(".contact-form-loader").hide();
											// Clear any error messages when showing step 2
											$form.closest(".wp-block-contact-form").find(".contact-form-message").html("");
											$form.find(".contact-form-step1").hide();
											$form.find(".contact-form-step2").show();
											// Add the leadid to a hidden field if it's provided in the response
											if (response.lead_id) {
												// Check if a hidden field for leadId already exists; if not, create one
												let leadIdField = $form.find(
													'.contact-form-step2 input[name="leadId"]'
												);
												if (leadIdField.length === 0) {
													leadIdField = $("<input>", {
														type: "hidden",
														name: "leadId",
														value: response.lead_id,
													});
													$form.find(".contact-form-step2").append(leadIdField);
												} else {
													// Update existing hidden field value
													leadIdField.val(response.lead_id);
												}
											}
										} else {
											$form.find(".contact-form-steps").hide();
											if (response.success_msg) {
												$form
													.closest(".wp-block-contact-form")
													.find(".contact-form-message")
													.html(
														'<div class="form-success">' +
														response.success_msg +
														"</div>"
													);
											}
										}
										let community_object = {
											name: siteConfig.blogName,
											region: siteConfig.websiteRegion,
											availability: siteConfig.communityAvailability,
										};

										// Initialize data for dataLayer push
										let dataLayerEvent = {
											event: "form_submission_success",
											marketing: true, // or set based on conditions
											community: community_object,
										};

										// Add properties only if they exist in the response
										if (typeof response.form_type !== 'undefined' && response.form_type) {
											dataLayerEvent.form_type = response.form_type;
										}
										if (typeof response.lot_id !== 'undefined' && response.lot_id) {
											let lot_items = [];
											const lotArray = Array.isArray(response.lot_id)
												? response.lot_id
												: response.lot_id.split(',');
											lotArray.forEach(lotId => {
												const matchingLot = lotConfig.lots_data.find(lot => lot.lot_id == lotId.trim())
												if (matchingLot) {
													let lot_object = {
														name: matchingLot.lot_name,
														type: $(this).data("product-type"),
														size: matchingLot.size,
														price: matchingLot.price,
														stage: matchingLot.stage,
														bedrooms: matchingLot.bedrooms,
														bathrooms: matchingLot.bathrooms,
														car_spaces: matchingLot.garage_spaces,
														stories: matchingLot.stories,
														product_id: matchingLot.product_id,
														open_times: '',
														builder: '',
														frontage: matchingLot.frontage
													};
													lot_items.push(lot_object);
												}
											});
											dataLayerEvent.lot = lot_items;
										}
										if (typeof response.first_name !== 'undefined' && response.first_name) {
											dataLayerEvent.first_name = response.first_name;
										}
										if (typeof response.last_name !== 'undefined' && response.last_name) {
											dataLayerEvent.last_name = response.last_name;
										}
										if (typeof response.email !== 'undefined' && response.email) {
											dataLayerEvent.email = response.email;
										}
										if (typeof response.mobile !== 'undefined' && response.mobile) {
											dataLayerEvent.mobile = response.mobile;
										}
										if (typeof response.postcode !== 'undefined' && response.postcode) {
											dataLayerEvent.postcode = response.postcode;
										}
										if (typeof response.suburb !== 'undefined' && response.suburb) {
											dataLayerEvent.suburb = response.suburb;
										}
										if (typeof response.contact_time !== 'undefined' && response.contact_time) {
											dataLayerEvent.contact_time = response.contact_time;
										}

										// Push the finalized data object to dataLayer
										window.dataLayer = window.dataLayer || [];
										window.dataLayer.push(dataLayerEvent);


										// $form[0].reset(); // Reset the form fields
									} else {
										let errorData = response.error_data;
										// Check if errorData exists and if it contains an err_msg property
										if (errorData && errorData.err_msg) {
											const $errorContainer = $form
												.closest(".wp-block-contact-form")
												.find(".contact-form-message");

											const alertDiv = document.createElement("div");
											alertDiv.classList.add("alert", "alert-danger");
											alertDiv.textContent = errorData.err_msg; // Using textContent prevents HTML injection

											$errorContainer.html(''); // Clear existing messages
											$errorContainer.append(alertDiv); // Safely append the new message
										}

										else {
											// Optional: Handle the case where there is no error message, if needed

											$form
												.closest(".wp-block-contact-form")
												.find(".contact-form-message")
												.html('<div class="alert alert-danger">An unexpected error occurred. Please try again.</div>');
										}
										jQuery(".contact-form-loader").hide();
									}
									$form[0].reset(); // This resets the form fields to their initial values
								},
								error: function (jqXHR, textStatus, errorThrown) {
									isSubmitting = false; // Reset submission flag on error
									// Handle AJAX errors here
									jQuery(".contact-form-loader").hide();
								},
							});
						},
					});

					// Additional checkbox validation for groups (if needed)
					$form.find('input[type="checkbox"]').each(function () {
						var $checkboxGroup = $(this).closest(".field-wrap.required");
						var $checkboxes = $checkboxGroup.find('input[type="checkbox"]');
						var checkboxName = $checkboxes.first().attr("name");

						$checkboxes.on("change", function () {
							var isChecked = $checkboxes.is(":checked");
							// If at least one checkbox is checked, remove error
							if (isChecked) {
								$form.validate().settings.messages[checkboxName].required = ""; // Clear required message
							} else {
								$form.validate().settings.messages[
									checkboxName
								].required = `Please select at least one ${fieldLabel.toLowerCase()}.`;
							}
						});
					});
				});
			}
		}

		// Home Buyer Form in popup
		$('.home-buyer-toolkit-form').click(function () {
			if (0 < $('.first-home-buyer-form-wrapper .peet-custom-form-block').length) {
				// reset the form
				const $popup = $('.first-home-buyer-form-wrapper .peet-custom-form-block');
				$(".suburb-suggestions").remove();
				if (typeof window.resetContactForm === 'function') {
					window.resetContactForm($popup[0]);
				}
				$('.popup-body').empty();
				// $('.first-home-buyer-form-wrapper.peet-custom-form-block').clone().appendTo('.popup-body');

				let originalForm = $('.first-home-buyer-form-wrapper .peet-custom-form-block form');
				let originalRules = originalForm.validate().settings.rules;
				// let originalSubmitHandler = originalForm.data('events').submit[0].handler;

				let clonedFormWrapper = $('.first-home-buyer-form-wrapper .peet-custom-form-block').clone();
				// Remove existing reCAPTCHA from clone
				clonedFormWrapper.find('.captcha-field').remove();
				
				// Append the cloned form to the popup body
				clonedFormWrapper.appendTo('.popup-body');

				// Add fresh CAPTCHA placeholder
				let freshCaptcha = $('<div class="captcha-field"></div>');
				clonedFormWrapper.find('.contact-form .contact-form-step1 .google-captcha .field-container').append(freshCaptcha);

				// Move .contact-form-loader inside the cloned form container
				$('.popup-body').find('.contact-form-loader').remove();
				clonedFormWrapper.find('.contact-form').prepend('<div class="contact-form-loader" style="display: none;"></div>');

				$('.popup-overlay').fadeIn();

				let clonedForm = $('.popup-overlay form');
				if (
					document.getElementsByClassName("captcha-field").length > 0 &&
					ccf_settings &&
					ccf_settings.captcha_key
				) {
					var captchaInt = setInterval(() => {
						if (window.grecaptcha && window.grecaptcha.render) {
							const captchaField = $('.popup-body .captcha-field');
							// Only render if it hasn't been rendered yet
							if (!captchaField.attr('data-grecaptcha-rendered')) {
								grecaptcha.render(captchaField[0], {
									sitekey: ccf_settings.captcha_key
								});
								captchaField.attr('data-grecaptcha-rendered', 'true');
							}
							clearInterval(captchaInt);
						}
					}, 500);
					
				}
				let $form = clonedForm;
				clonedForm.validate({
					rules: originalRules,
					submitHandler: function (form, event) {
						event.preventDefault();
						var $currentContactForm = $(form);
						var $currentFormContainer = $currentContactForm.closest(".wp-block-contact-form"); // Parent container for the form
						var $contactloader;

						// Check if loader is inside or outside the form container
						if ($currentFormContainer.find(".contact-form-loader").length > 0) {
							// Loader is inside the form container
							$contactloader = $currentFormContainer.find(".contact-form-loader");
						} else if ($currentFormContainer.prev(".contact-form-loader").length > 0) {
							// Loader is outside the form container (directly above)
							$contactloader = $currentFormContainer.prev(".contact-form-loader");
						}

						if ($contactloader) {
							$contactloader.show(); // Show the loader
						}

						// Clear any previous messages
						$form.closest(".wp-block-contact-form").find(".contact-form-message").html("");
						
						// Prevent multiple simultaneous submissions
						var isSubmitting = false;
						
						// Prevent duplicate submissions
						if (isSubmitting) {
							return;
						}
						
						isSubmitting = true;
						
						// Serialize form data
						var formDataString = $form.serialize();
						
						// Perform an AJAX call on form submission
						$.ajax({
							url: ccf_settings.ajaxUrl,
							dataType: "json",
							type: "POST",
							data: {
								action: "peet_validate_form_submission", // Action for the callback
								formData: formDataString, // Serialize form data
								pageTitle: ccf_settings.page_title
							},
							success: function (response) {
								isSubmitting = false; // Reset submission flag
								
								if (response.submitted) {
									if (response.is_survey_form) {
										jQuery(".contact-form-loader").hide();
										// Clear any error messages when showing step 2
										$form.closest(".wp-block-contact-form").find(".contact-form-message").html("");
										$form.find(".contact-form-step1").hide();
										$form.find(".contact-form-step2").show();
										// Add the leadid to a hidden field if it's provided in the response
										if (response.lead_id) {
											// Check if a hidden field for leadId already exists; if not, create one
											let leadIdField = $form.find(
												'.contact-form-step2 input[name="leadId"]'
											);
											if (leadIdField.length === 0) {
												leadIdField = $("<input>", {
													type: "hidden",
													name: "leadId",
													value: response.lead_id,
												});
												$form.find(".contact-form-step2").append(leadIdField);
											} else {
												// Update existing hidden field value
												leadIdField.val(response.lead_id);
											}
										}
									} else {
										$form.find(".contact-form-steps").hide();
										if (response.success_msg) {
											$form
												.closest(".wp-block-contact-form")
												.find(".contact-form-message")
												.html(
													'<div class="form-success">' +
													response.success_msg +
													"</div>"
												);
										}
									}
									let community_object = {
										name: siteConfig.blogName,
										region: siteConfig.websiteRegion,
										availability: siteConfig.communityAvailability,
									};

									// Initialize data for dataLayer push
									let dataLayerEvent = {
										event: "form_submission_success",
										marketing: true, // or set based on conditions
										community: community_object,
									};

									// Add properties only if they exist in the response
									if (typeof response.form_type !== 'undefined' && response.form_type) {
										dataLayerEvent.form_type = response.form_type;
									}
									if (typeof response.lot_id !== 'undefined' && response.lot_id) {
										let lot_items = [];
										const lotArray = Array.isArray(response.lot_id)
											? response.lot_id
											: response.lot_id.split(',');
										lotArray.forEach(lotId => {
											const matchingLot = lotConfig.lots_data.find(lot => lot.lot_id == lotId.trim())
											if (matchingLot) {
												let lot_object = {
													name: matchingLot.lot_name,
													type: $(this).data("product-type"),
													size: matchingLot.size,
													price: matchingLot.price,
													stage: matchingLot.stage,
													bedrooms: matchingLot.bedrooms,
													bathrooms: matchingLot.bathrooms,
													car_spaces: matchingLot.garage_spaces,
													stories: matchingLot.stories,
													product_id: matchingLot.product_id,
													open_times: '',
													builder: '',
													frontage: matchingLot.frontage
												};
												lot_items.push(lot_object);
											}
										});
										dataLayerEvent.lot = lot_items;
									}
									if (typeof response.first_name !== 'undefined' && response.first_name) {
										dataLayerEvent.first_name = response.first_name;
									}
									if (typeof response.last_name !== 'undefined' && response.last_name) {
										dataLayerEvent.last_name = response.last_name;
									}
									if (typeof response.email !== 'undefined' && response.email) {
										dataLayerEvent.email = response.email;
									}
									if (typeof response.mobile !== 'undefined' && response.mobile) {
										dataLayerEvent.mobile = response.mobile;
									}
									if (typeof response.postcode !== 'undefined' && response.postcode) {
										dataLayerEvent.postcode = response.postcode;
									}
									if (typeof response.suburb !== 'undefined' && response.suburb) {
										dataLayerEvent.suburb = response.suburb;
									}
									if (typeof response.contact_time !== 'undefined' && response.contact_time) {
										dataLayerEvent.contact_time = response.contact_time;
									}

									// Push the finalized data object to dataLayer
									window.dataLayer = window.dataLayer || [];
									window.dataLayer.push(dataLayerEvent);


									// $form[0].reset(); // Reset the form fields
								} else {
									let errorData = response.error_data;
									// Check if errorData exists and if it contains an err_msg property
									if (errorData && errorData.err_msg) {
										const $errorContainer = $form
											.closest(".wp-block-contact-form")
											.find(".contact-form-message");

										const alertDiv = document.createElement("div");
										alertDiv.classList.add("alert", "alert-danger");
										alertDiv.textContent = errorData.err_msg; // Using textContent prevents HTML injection

										$errorContainer.html(''); // Clear existing messages
										$errorContainer.append(alertDiv); // Safely append the new message
									}

									else {
										// Optional: Handle the case where there is no error message, if needed

										$form
											.closest(".wp-block-contact-form")
											.find(".contact-form-message")
											.html('<div class="alert alert-danger">An unexpected error occurred. Please try again.</div>');
									}
									jQuery(".contact-form-loader").hide();
								}
								$form[0].reset(); // This resets the form fields to their initial values
							},
							error: function (jqXHR, textStatus, errorThrown) {
								isSubmitting = false; // Reset submission flag on error
								// Handle AJAX errors here
								jQuery(".contact-form-loader").hide();
							},
						});
						return false;
					}
				});

				// Add a class to the body to prevent scrolling
				$('body, html').addClass('first-home-buyer-toolkit-modal-open');

			}
		});

		//console.log($modalForm.data("unobtrusiveValidation"));

		// Close popup
		$(document).on('click', '.popup-close, .popup-overlay', function (e) {
			e.preventDefault();
			$('.popup-overlay').fadeOut(); // Hide overlay
			$('body, html').removeClass('first-home-buyer-toolkit-modal-open'); // Remove the class to allow scrolling again
		});

		// Prevent close when clicking inside the popup content
		$(document).on('click', '.popup-overlay .popup', function (e) {
			e.stopPropagation();
		});


		/**
		 * jQuery event handler for handling form submissions within .peet-survey-form containers.
		 * This function gathers form input values, validates them, and sends an AJAX request only if all data is available.
		 *
		 * Assumes the following dependencies are available:
		 * - jQuery library
		 * - ccf_settings.ajaxUrl (contains the AJAX endpoint URL)
		 */

		jQuery(document).on("click", ".peet-survey-form__submit", function (e) {
			e.preventDefault(); // Prevent default form submission behavior


			// Limit scope to the form related to the clicked button to avoid conflicts on multiple forms
			var surveyForm = jQuery(this).closest(".peet-survey-form");
			surveyForm.closest(".wp-block-contact-form").find(".peet-survey-form__message").remove();
			jQuery(".wp-block-contact-form-heading").hide();
			surveyForm.closest(".wp-block-contact-form").parent().find(".contact-form-loader").show();

			// Gather values from form fields within the selected form container
			var leadId = surveyForm.find('input[name="leadId"]').val();
			// var leadId  = "6fb32226-80ba-4475-9db9-e4cbf5e869db"
			var buyerType = surveyForm.find('input[name="buyer-type"]:checked').val();
			var purchaseTimeline = surveyForm
				.find('input[name="purchase-timeline"]:checked')
				.val();
			var propertyTypes = surveyForm
				.find('input[name="property-type[]"]:checked')
				.map(function () {
					return jQuery(this).val();
				})
				.get()
				.join(",");
			var currentFormId = surveyForm.find('input[name="form_id"]').val();
			var formId = $(this).closest('.peet-custom-form-block').find('input[name="form_id"]').val();
			var propertySource = surveyForm.find('select[name="property-source"]').val();
			// Prepare data for the AJAX request
			var ajaxData = {
				action: "peet_survey_form_submission",
				leadId: leadId,
				buyerType: buyerType,
				purchaseTimeline: purchaseTimeline,
				propertyTypes: propertyTypes,
				propertySource: propertySource,
				currentFormId: formId,
			};

			// Send AJAX request to the server
			jQuery.ajax({
				url: ccf_settings.ajaxUrl,
				type: "POST",
				dataType: "json",
				data: ajaxData, // Send the validated data
				success: function (response) {
					// Handle successful form submission response
					var hasSuccessMsg = response.data && response.data.success_msg ? response.data.success_msg : 'Thank you for your survey form submission!';
					var redirectUrl = surveyForm.closest(".wp-block-contact-form").find(".redirect_url").val();
					if (response.success) {
						surveyForm.hide();
						jQuery(".contact-form-loader").hide();
						// if ( response.data && response.data.redirect_url ) {
						if ( redirectUrl ) {
							window.location.href = redirectUrl;
						} else {
							surveyForm.closest(".wp-block-contact-form")
							.find(".contact-form-message")
							.append('<div class="peet-survey-form__message peet-survey-form__message--success">' + hasSuccessMsg + '</div>');
						}
						jQuery(".wp-block-contact-form-heading").show();
					} else {
						surveyForm.closest(".wp-block-contact-form")
							.find(".contact-form-message")
							.append('<div class="peet-survey-form__message peet-survey-form__message--error">There was an issue with your survey form submission. Please try again.</div>');
					}
					surveyForm.find('input[type="radio"]:checked').prop('checked', false);
					surveyForm.find('input[type="checkbox"]:checked').prop('checked', false);

				},
				error: function (jqXHR, textStatus, errorThrown) {
					jQuery(".contact-form-loader").hide();
					// Handle AJAX errors gracefully
				},
			});
		});
	});
})(jQuery);

if (
	jQuery("select[multiple]").length > 0 &&
	ccf_settings &&
	ccf_settings.select2_css &&
	ccf_settings.select2_js
) {
	// Load Select2 CSS
	var link = document.createElement("link");
	link.rel = "stylesheet";
	link.type = "text/css";
	link.href = ccf_settings.select2_css;
	document.head.appendChild(link);

	// Load Select2 JS
	jQuery.getScript(ccf_settings.select2_js, function () {
		// Load select2Sortable JS after Select2 JS is loaded
		jQuery("select[multiple]").each(function () {
			var placeholder = jQuery(this).siblings("label").text(); // Get the text of the associated label
			placeholder = placeholder.replace("*", ""); // Remove the asterisk
			jQuery(this)
				.select2({
					placeholder: placeholder, // Set the placeholder
				})
				.on("select2:select", function (evt) {
					var id = evt.params.data.id;
					var element = jQuery(this).children("option[value=" + id + "]");
					moveElementToEndOfParent(element);
					jQuery(this).trigger("change");
				});
		});
	});

	moveElementToEndOfParent = function (element) {
		var parent = element.parent();
		element.detach();
		parent.append(element);
	};
};
/*! WOW wow.js - v1.3.0 - 2016-10-04
* https://wowjs.uk
* Copyright (c) 2016 Thomas Grainger; Licensed MIT */!function(a,b){if("function"==typeof define&&define.amd)define(["module","exports"],b);else if("undefined"!=typeof exports)b(module,exports);else{var c={exports:{}};b(c,c.exports),a.WOW=c.exports}}(this,function(a,b){"use strict";function c(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function d(a,b){return b.indexOf(a)>=0}function e(a,b){for(var c in b)if(null==a[c]){var d=b[c];a[c]=d}return a}function f(a){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(a)}function g(a){var b=arguments.length<=1||void 0===arguments[1]?!1:arguments[1],c=arguments.length<=2||void 0===arguments[2]?!1:arguments[2],d=arguments.length<=3||void 0===arguments[3]?null:arguments[3],e=void 0;return null!=document.createEvent?(e=document.createEvent("CustomEvent"),e.initCustomEvent(a,b,c,d)):null!=document.createEventObject?(e=document.createEventObject(),e.eventType=a):e.eventName=a,e}function h(a,b){null!=a.dispatchEvent?a.dispatchEvent(b):b in(null!=a)?a[b]():"on"+b in(null!=a)&&a["on"+b]()}function i(a,b,c){null!=a.addEventListener?a.addEventListener(b,c,!1):null!=a.attachEvent?a.attachEvent("on"+b,c):a[b]=c}function j(a,b,c){null!=a.removeEventListener?a.removeEventListener(b,c,!1):null!=a.detachEvent?a.detachEvent("on"+b,c):delete a[b]}function k(){return"innerHeight"in window?window.innerHeight:document.documentElement.clientHeight}Object.defineProperty(b,"__esModule",{value:!0});var l,m,n=function(){function a(a,b){for(var c=0;c<b.length;c++){var d=b[c];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(a,d.key,d)}}return function(b,c,d){return c&&a(b.prototype,c),d&&a(b,d),b}}(),o=window.WeakMap||window.MozWeakMap||function(){function a(){c(this,a),this.keys=[],this.values=[]}return n(a,[{key:"get",value:function(a){for(var b=0;b<this.keys.length;b++){var c=this.keys[b];if(c===a)return this.values[b]}}},{key:"set",value:function(a,b){for(var c=0;c<this.keys.length;c++){var d=this.keys[c];if(d===a)return this.values[c]=b,this}return this.keys.push(a),this.values.push(b),this}}]),a}(),p=window.MutationObserver||window.WebkitMutationObserver||window.MozMutationObserver||(m=l=function(){function a(){c(this,a),"undefined"!=typeof console&&null!==console&&(console.warn("MutationObserver is not supported by your browser."),console.warn("WOW.js cannot detect dom mutations, please call .sync() after loading new content."))}return n(a,[{key:"observe",value:function(){}}]),a}(),l.notSupported=!0,m),q=window.getComputedStyle||function(a){var b=/(\-([a-z]){1})/g;return{getPropertyValue:function(c){"float"===c&&(c="styleFloat"),b.test(c)&&c.replace(b,function(a,b){return b.toUpperCase()});var d=a.currentStyle;return(null!=d?d[c]:void 0)||null}}},r=function(){function a(){var b=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];c(this,a),this.defaults={boxClass:"wow",animateClass:"animated",offset:0,mobile:!0,live:!0,callback:null,scrollContainer:null,resetAnimation:!0},this.animate=function(){return"requestAnimationFrame"in window?function(a){return window.requestAnimationFrame(a)}:function(a){return a()}}(),this.vendors=["moz","webkit"],this.start=this.start.bind(this),this.resetAnimation=this.resetAnimation.bind(this),this.scrollHandler=this.scrollHandler.bind(this),this.scrollCallback=this.scrollCallback.bind(this),this.scrolled=!0,this.config=e(b,this.defaults),null!=b.scrollContainer&&(this.config.scrollContainer=document.querySelector(b.scrollContainer)),this.animationNameCache=new o,this.wowEvent=g(this.config.boxClass)}return n(a,[{key:"init",value:function(){this.element=window.document.documentElement,d(document.readyState,["interactive","complete"])?this.start():i(document,"DOMContentLoaded",this.start),this.finished=[]}},{key:"start",value:function(){var a=this;if(this.stopped=!1,this.boxes=[].slice.call(this.element.querySelectorAll("."+this.config.boxClass)),this.all=this.boxes.slice(0),this.boxes.length)if(this.disabled())this.resetStyle();else for(var b=0;b<this.boxes.length;b++){var c=this.boxes[b];this.applyStyle(c,!0)}if(this.disabled()||(i(this.config.scrollContainer||window,"scroll",this.scrollHandler),i(window,"resize",this.scrollHandler),this.interval=setInterval(this.scrollCallback,50)),this.config.live){var d=new p(function(b){for(var c=0;c<b.length;c++)for(var d=b[c],e=0;e<d.addedNodes.length;e++){var f=d.addedNodes[e];a.doSync(f)}});d.observe(document.body,{childList:!0,subtree:!0})}}},{key:"stop",value:function(){this.stopped=!0,j(this.config.scrollContainer||window,"scroll",this.scrollHandler),j(window,"resize",this.scrollHandler),null!=this.interval&&clearInterval(this.interval)}},{key:"sync",value:function(){p.notSupported&&this.doSync(this.element)}},{key:"doSync",value:function(a){if("undefined"!=typeof a&&null!==a||(a=this.element),1===a.nodeType){a=a.parentNode||a;for(var b=a.querySelectorAll("."+this.config.boxClass),c=0;c<b.length;c++){var e=b[c];d(e,this.all)||(this.boxes.push(e),this.all.push(e),this.stopped||this.disabled()?this.resetStyle():this.applyStyle(e,!0),this.scrolled=!0)}}}},{key:"show",value:function(a){return this.applyStyle(a),a.className=a.className+" "+this.config.animateClass,null!=this.config.callback&&this.config.callback(a),h(a,this.wowEvent),this.config.resetAnimation&&(i(a,"animationend",this.resetAnimation),i(a,"oanimationend",this.resetAnimation),i(a,"webkitAnimationEnd",this.resetAnimation),i(a,"MSAnimationEnd",this.resetAnimation)),a}},{key:"applyStyle",value:function(a,b){var c=this,d=a.getAttribute("data-wow-duration"),e=a.getAttribute("data-wow-delay"),f=a.getAttribute("data-wow-iteration");return this.animate(function(){return c.customStyle(a,b,d,e,f)})}},{key:"resetStyle",value:function(){for(var a=0;a<this.boxes.length;a++){var b=this.boxes[a];b.style.visibility="visible"}}},{key:"resetAnimation",value:function(a){if(a.type.toLowerCase().indexOf("animationend")>=0){var b=a.target||a.srcElement;b.className=b.className.replace(this.config.animateClass,"").trim()}}},{key:"customStyle",value:function(a,b,c,d,e){return b&&this.cacheAnimationName(a),a.style.visibility=b?"hidden":"visible",c&&this.vendorSet(a.style,{animationDuration:c}),d&&this.vendorSet(a.style,{animationDelay:d}),e&&this.vendorSet(a.style,{animationIterationCount:e}),this.vendorSet(a.style,{animationName:b?"none":this.cachedAnimationName(a)}),a}},{key:"vendorSet",value:function(a,b){for(var c in b)if(b.hasOwnProperty(c)){var d=b[c];a[""+c]=d;for(var e=0;e<this.vendors.length;e++){var f=this.vendors[e];a[""+f+c.charAt(0).toUpperCase()+c.substr(1)]=d}}}},{key:"vendorCSS",value:function(a,b){for(var c=q(a),d=c.getPropertyCSSValue(b),e=0;e<this.vendors.length;e++){var f=this.vendors[e];d=d||c.getPropertyCSSValue("-"+f+"-"+b)}return d}},{key:"animationName",value:function(a){var b=void 0;try{b=this.vendorCSS(a,"animation-name").cssText}catch(c){b=q(a).getPropertyValue("animation-name")}return"none"===b?"":b}},{key:"cacheAnimationName",value:function(a){return this.animationNameCache.set(a,this.animationName(a))}},{key:"cachedAnimationName",value:function(a){return this.animationNameCache.get(a)}},{key:"scrollHandler",value:function(){this.scrolled=!0}},{key:"scrollCallback",value:function(){if(this.scrolled){this.scrolled=!1;for(var a=[],b=0;b<this.boxes.length;b++){var c=this.boxes[b];if(c){if(this.isVisible(c)){this.show(c);continue}a.push(c)}}this.boxes=a,this.boxes.length||this.config.live||this.stop()}}},{key:"offsetTop",value:function(a){for(;void 0===a.offsetTop;)a=a.parentNode;for(var b=a.offsetTop;a.offsetParent;)a=a.offsetParent,b+=a.offsetTop;return b}},{key:"isVisible",value:function(a){var b=a.getAttribute("data-wow-offset")||this.config.offset,c=this.config.scrollContainer&&this.config.scrollContainer.scrollTop||window.pageYOffset,d=c+Math.min(this.element.clientHeight,k())-b,e=this.offsetTop(a),f=e+a.clientHeight;return d>=e&&f>=c}},{key:"disabled",value:function(){return!this.config.mobile&&f(navigator.userAgent)}}]),a}();b["default"]=r,a.exports=b["default"]});;
(()=>{var e={958:()=>{function e(){return window.innerWidth<992}function t(e,t){e.classList.toggle(t)}function o(e,t){e.classList.add(t)}function n(e,t){e.classList.remove(t)}function i(){var e=document.querySelector(".site-header--main"),t=document.querySelector(".site-header__top"),o=document.querySelector(".wp-block-peet-hero-banner"),n=o?o.offsetTop+o.offsetHeight:0,i=t?t.offsetHeight-50:0;window.scrollY>=i&&window.scrollY>0?(e.classList.add("fixed-header"),o&&t?window.scrollY>n?t.classList.add("hidden"):t.classList.remove("hidden"):t&&t.classList.add("hidden"),s()):(e.classList.remove("fixed-header"),t&&t.classList.remove("hidden"),s())}function r(){if(e()){const e=document.querySelector(".peet-mega-menu-wrapper .mega-menu-left-col"),t=document.querySelector(".peet-mega-menu-wrapper .mega-menu-right-col__inner-wrapper");if(e&&!e.querySelector(".hamburger-icon")){const t=document.createElement("span");t.classList.add("hamburger-icon"),e.appendChild(t),t.addEventListener("click",(function(){o(document.querySelector(".peet-mega-menu-wrapper .mega-menu-right-col"),"menu-open"),o(document.querySelector("body"),"menu-toggled"),o(document.querySelector("html"),"menu-toggled"),s()}))}if(!document.querySelector(".menu-close-icon")){const e=document.createElement("span");e.classList.add("menu-close-icon");const t=document.querySelector(".peet-mega-menu-wrapper .mega-menu-right-col__inner-wrapper");if(t){const o=t.querySelector(".megamenu");o&&o.prepend(e)}e.addEventListener("click",(function(){n(document.querySelector(".peet-mega-menu-wrapper .mega-menu-right-col"),"menu-open"),n(document.querySelector("body"),"menu-toggled"),n(document.querySelector("html"),"menu-toggled")}))}const i=document.querySelector(".megamenu-wrapper__header-mobile");i.parentNode!==t.parentNode&&t.parentNode.insertBefore(i,t.nextSibling)}}function s(){var t=document.querySelector(".site-header__bottom"),o=document.querySelector(".megamenu .megamenu__body");if(t&&o&&(o.style.top=t.offsetHeight+"px"),e()){var n=document.querySelector(".site-header__bottom .peet-mega-menu-wrapper"),i=document.querySelector(".peet-mega-menu-wrapper .mega-menu-right-col");if(n&&i){i.style.top=n.offsetHeight+"px";const e=document.querySelector(".peet-mega-menu-wrapper .mega-menu-right-col.menu-open");if(e){const t=e.getBoundingClientRect().top;document.documentElement.style.setProperty("--top-value",`${t}px`)}}}}function c(){document.querySelectorAll(".megamenu").forEach((function(t){var o=t.querySelectorAll("[id^='megamenu-block-']");if(e())o.forEach((function(e){var o=e.getAttribute("id"),n=t.querySelector('span[data-href="#'+o+'"]');e&&n&&(e.parentNode.removeChild(e),n.parentNode.insertBefore(e,n.nextSibling))}));else{var n=t.querySelector(".megamenu__body .megamenu__body-container");o.forEach((function(e){n.appendChild(e)}))}}))}function a(){const e=document.querySelector(".site-header__bottom .megamenu__items li:last-child"),t=document.querySelector(".community-menu");if(e&&t){const o=e.getBoundingClientRect(),n=t.getBoundingClientRect().bottom-o.bottom;document.documentElement.style.setProperty("--menu-space-below",`${n}px`)}}window.addEventListener("scroll",i),document.addEventListener("DOMContentLoaded",i),document.addEventListener("click",(function(e){const o=document.getElementById("search-btn"),i=document.getElementById("search-form-container");o&&i&&(e.target===o?(e.stopPropagation(),t(i,"active")):i.contains(e.target)||o.contains(e.target)||n(i,"active"))})),document.addEventListener("click",(function(e){const o=document.getElementById("menu-toggle"),i=document.getElementById("primary-menu-container"),r=document.getElementById("menu-close-toggle"),s=document.querySelector(".peet-main-menu-wrapper").parentElement.parentElement;o&&(e.target===o?(t(i,"active"),s.classList.add("contain-auto")):r&&e.target===r?(n(i,"active"),s.classList.remove("contain-auto")):i.contains(e.target)||o.contains(e.target)||(n(i,"active"),s.classList.remove("contain-auto")))})),document.addEventListener("DOMContentLoaded",(function(){var e=document.querySelectorAll(".megamenu__item");e.forEach((function(e){var t=e.querySelector("span").getAttribute("data-href"),n=document.querySelector(t);n&&n.classList.contains("empty-content")&&o(e,"no-submenu")})),window.innerWidth<992&&e.forEach((function(e){var t=e.querySelector("span").getAttribute("data-href"),o=document.querySelector(t);if(o&&!o.classList.contains("empty-content")){var n=document.createElement("span");n.classList.add("subarrow"),e.querySelector("span").appendChild(n)}})),r(),c(),s()})),window.addEventListener("resize",(function(){c(),s(),r(),a()})),document.addEventListener("click",(function(t){if(t.target.matches(".megamenu ul > li .subarrow")&&e()){const e=t.target.closest(".megamenu__item");e.classList.toggle("active");const o=e.querySelector(".megamenu__content");Array.from(e.parentNode.children).filter((t=>t!==e)).forEach((e=>{e.classList.remove("active");const t=e.querySelector(".megamenu__content");t&&(t.style.display="none")})),o&&(o.style.display=e.classList.contains("active")?"block":"none")}})),document.addEventListener("DOMContentLoaded",(function(){if(!e()){a();const e=document.querySelectorAll(".site-header__bottom ul.megamenu__items > li > span"),t=document.querySelector(".megamenu__body"),o=document.querySelector(".mega-menu"),n=document.querySelector(".site-header__bottom"),i=document.querySelector(".peet-main-menu-wrapper");let r,s;document.querySelector(".hide-header")||(e.forEach((function(n){n.addEventListener("mouseenter",(function(){clearTimeout(s),clearTimeout(r),e.forEach((e=>e.parentNode.classList.remove("active"))),document.querySelectorAll(".submenu-active").forEach((e=>e.classList.remove("submenu-active"))),t.classList.remove("visible-content"),n.parentNode.classList.add("active"),i.classList.add("contain-auto"),o.classList.add("fixed-header-bg");const c=n.getAttribute("data-href");if(c){const e=document.getElementById(c.substring(1));e&&(r=setTimeout((()=>{e.classList.add("submenu-active"),requestAnimationFrame((()=>{t.classList.add("visible-content")}))}),50))}})),n.addEventListener("mouseleave",(function(e){clearTimeout(r),s=setTimeout((()=>{const r=e.relatedTarget;if(!(n.parentNode.contains(r)||t&&t.contains(r))){n.parentNode.classList.remove("active"),i.classList.remove("contain-auto"),o.classList.remove("fixed-header-bg");const e=n.getAttribute("data-href");if(e){const t=document.getElementById(e.substring(1));t?.classList.remove("submenu-active")}t.classList.remove("visible-content")}}),200)}))})),t.addEventListener("mouseleave",(()=>{e.forEach((e=>e.parentNode.classList.remove("active"))),document.querySelectorAll(".submenu-active").forEach((e=>e.classList.remove("submenu-active"))),t.classList.remove("visible-content"),i.classList.remove("contain-auto"),o.classList.remove("fixed-header-bg")})),document.addEventListener("mousemove",(r=>{n&&n.contains(r.target)||t&&t.contains(r.target)||(e.forEach((e=>e.parentNode.classList.remove("active"))),document.querySelectorAll(".submenu-active").forEach((e=>e.classList.remove("submenu-active"))),t.classList.remove("visible-content"),o.classList.remove("fixed-header-bg"),i.classList.remove("contain-auto"))})))}})),document.querySelectorAll(".toggle-field .field-container p:first-child").forEach((e=>{e.addEventListener("click",(function(){this.closest(".field-container").classList.toggle("is-open")}))}))},8013:()=>{!function(e){"use strict";e(".menu-toggle").click((function(){e("header .main-navigation").toggleClass("toggled")})),e(".main-navigation ul.menu>li.menu-item-has-children").on("click",(function(){767>e(window).width()&&(e(this).find(".sub-menu,.children").slideToggle(),e(this).toggleClass("active-sub"))})),e(window).scroll((function(){var t=67;e(".site-header__bottom").hasClass("disable-corporate-menu")&&(t=0),e(window).scrollTop()>=t?e(".peet-header").addClass("fixed-header"):e(".peet-header").removeClass("fixed-header")})),0==e(".mega-menu .community-menu").length&&e(".mega-menu.site-header--main").addClass("parent-menu")}(jQuery)}},t={};function o(n){var i=t[n];if(void 0!==i)return i.exports;var r=t[n]={exports:{}};return e[n](r,r.exports,o),r.exports}(()=>{"use strict";function e(e){if(!jQuery(".peet-custom-form-block").length)return;let t=null;if(t=e?"string"==typeof e?jQuery(e):e:jQuery(".lot-filter-popup-outer.enquire .contact-form, .form-popup .contact-form"),!t.length)return;const o=t.closest(".lot-filter-popup-outer.enquire, .peet-custom-form-block, .form-popup"),n=o.length?o:t.parent();t[0]&&t[0].reset(),n.find(".wp-block-contact-form-heading").show(),n.find(".contact-form-message").html("");const i=n.find(".suburb-display");i.length&&i.text("Please select a suburb from the dropdown.");const r=n.find(".contact-form-step1");r.length&&r.show();const s=n.find(".contact-form-step2");s.length&&s.hide()}o(8013),o(958),function(e){function t(){const t=e(window).width(),o=e=>{e.forEach((e=>{const t=document.querySelectorAll(e);if(0===t.length)return;let o=0;t.forEach((e=>{e.style.height="auto"})),t.forEach((e=>{o=Math.max(o,e.offsetHeight)})),t.forEach((e=>{e.style.height=`${o}px`}))}))};o([".footer-slider .footer-slider__inner .footer-slider__item p:not(.btn-footer)",".footer-slider .footer-slider__inner .footer-slider__item h4"]),t>=767&&o([".related-news__title",".news-content-title",".partners-logo .partners-logo-inner .partners .partner .partner-image",".layout2 .lot-content .lot-details",".layout2 .lot-content .lot-info .lot-title"]),t<993&&o([".key-selling-slider__slide"])}function o(){if(0===e(".hero-banner").length){var t=e(".peet-main-menu-wrapper").outerHeight()+(window.innerWidth<992?40:0);e(".wp-site-blocks").css("padding-top",t+"px").addClass("no-banner")}}jQuery(document).ready((function(e){const t=e(".wp-block-peet-community-footer");if(t.length&&2===t.find(".sales-representative-info").length){const t=e(".community-menu>.wp-block-group");t.length&&t.addClass("logo-hide")}function o(){const t=e(window).width(),o=e("img.custom-logo");if(o.length){const n=siteConfig.customMobileLogoURL,i=siteConfig.darkMobileLogoURL,r=siteConfig.isDarkTheme;if(t<992)if(r&&i)o.attr("src",i);else if(n){const t=e("header img.custom-logo");t.length&&t.attr("src",n)}}}o(),e(window).on("resize",(function(){o()}))})),jQuery(document).ready((function(e){e(".slick-slider").each((function(){const t=e(this),o=t.attr("data-slick");let n={},i=1;if(o)try{n=JSON.parse(o),i=n.slidesToShow||1}catch(e){console.error("Invalid slick settings JSON:",e)}const r=t.find(".slick-slide").not(".slick-cloned").length;t.hasClass("slick-initialized")?r<=i&&(t.slick("slickSetOption","dots",!1,!0),t.slick("slickSetOption","arrows",!1,!0)):r<=i?t.slick({...n,dots:!1,arrows:!1}):t.slick(n)}))})),document.addEventListener("DOMContentLoaded",t),window.addEventListener("resize",t),document.addEventListener("DOMContentLoaded",(()=>{const e=document.querySelector("footer .wp-block-peet-social-share"),t=document.querySelector("footer .social-wrapper-mobile"),o=document.querySelector("footer .wp-block-peet-sales-representative"),n=document.querySelector("footer .sales-rep-wrapper-mobile"),i=e?e.parentNode:null,r=e?e.nextElementSibling:null,s=o?o.parentNode:null,c=o?o.nextElementSibling:null;function a(e,t,o,n){if(e&&t&&o)if(window.innerWidth<767)t.contains(e)||t.appendChild(e);else if(!o.contains(e))try{n&&o.contains(n)?o.insertBefore(e,n):o.appendChild(e)}catch(e){console.error("Error moving element:",e)}}function l(){a(e,t,i,r),a(o,n,s,c)}l(),window.addEventListener("resize",l)})),document.addEventListener("DOMContentLoaded",(function(){document.querySelector(".disable-corporate-menu")||document.body.classList.add("has-corpmenu")})),window.addEventListener("load",o),e(window).resize((function(){o()})),(new WOW).init(),document.addEventListener("DOMContentLoaded",(function(){if(e(".single-news").length){const t=e(".peet-main-menu-wrapper").outerHeight(),o=document.createElement("div");o.classList.add("detail_progressbar_container"),o.style.position="fixed",o.style.left="0",o.style.width="100%",o.style.height="12px",o.style.backgroundColor="#fff",o.style.zIndex="1000",o.style.display="none";const n=document.createElement("span");function i(){const t=e(".peet-main-menu-wrapper").outerHeight();o.style.top=e("body").hasClass("logged-in")?`${t+32}px`:`${t}px`}n.classList.add("detail_progressbar"),n.style.display="block",n.style.width="0%",n.style.height="100%",n.style.backgroundColor="var(--wp--preset--color--color-3)",o.appendChild(n),document.body.appendChild(o),i(),window.addEventListener("scroll",i),window.addEventListener("resize",i);const r=document.querySelector(".content-taxonomy");if(!r)return;function s(){const e=r.getBoundingClientRect().top+window.scrollY-t,i=e+r.offsetHeight;if(window.scrollY>=e&&window.scrollY<=i){o.style.display="block";const t=Math.max(0,r.offsetHeight-window.innerHeight),i=window.scrollY-e;let s;s=r.offsetHeight<=window.innerHeight?100:t>0?i/t*100:0;const c=Math.max(0,Math.min(100,s));n.style.width=c+"%"}else o.style.display="none"}window.addEventListener("scroll",s),s()}})),function(){const t=e(".peet-main-menu-wrapper");let o=e(".sticky_detail_info"),n=e(".detail_content");if(o.length&&n.length&&n.find(".entry-content").outerHeight()>o.outerHeight()){const i=o.parent(),r=o.offset().top-t.outerHeight();let s,c=i.width(),a=o.position().left;function l(){const s=e(window).scrollTop(),c=i.offset().top+i.outerHeight()-100,l=o.outerHeight(),d=o.innerHeight(),u=n.outerHeight(),m=o.outerHeight(),p=t.outerHeight(),f=c-l;u>m&&e(window).width()>781?s>r&&s<f?o.css({position:"fixed",top:e("body").hasClass("logged-in")?`${p+32+30}px`:`${p+30}px`,left:a+i.offset().left,width:i.width()+"px",height:d+"px"}):s>f?o.css({position:"absolute",top:"auto",bottom:"80px",left:a,width:i.width()+"px",height:d+"px"}):o.css({position:"static",top:"auto",bottom:"auto",left:"auto",height:"auto",width:"auto"}):o.css({position:"static",top:"auto",bottom:"auto",left:"auto",height:"auto",width:"auto"})}o.css("width",c+"px"),e(window).off("resize.stickyBehavior").on("resize.stickyBehavior",(function(){e(window).width()>781&&o.css("width",i.width()+"px")})),e(window).off("scroll.stickyBehavior").on("scroll.stickyBehavior",(function(){clearTimeout(s),s=setTimeout(l,10)}))}}()}(jQuery),document.addEventListener("DOMContentLoaded",(function(){const e=document.querySelector(".latest-news-section");function t(){const t=document.querySelector(".latest-news-featured"),o=document.querySelector(".latest-news-content");e&&t&&o&&window.innerWidth>992?t.style.height=`${o.offsetHeight}px`:t&&(t.style.height="")}t(),window.addEventListener("resize",t)})),document.addEventListener("DOMContentLoaded",(function(){const t=document.querySelectorAll(".button-with-form__label"),o=document.querySelector(".peet-main-menu-wrapper");function n(e){(e?e.querySelectorAll(".peet-custom-form-block"):document.querySelectorAll(".peet-custom-form-block")).forEach((e=>{const t=e.querySelector(".contact-form");if(!t)return;const o=t.querySelectorAll(".peet-survey-form__counter");o.length>0&&o.forEach((e=>{e.textContent=""}));const n=t.querySelectorAll(".peet-survey-form__section");if(n.length>0){n.forEach(((e,t)=>{e.classList.remove("active"),0===t&&e.classList.add("active"),e.querySelectorAll("input, select").forEach((e=>{"radio"===e.type||"checkbox"===e.type?e.checked=!1:"SELECT"===e.tagName?e.selectedIndex=0:e.value=""}))}));const e=n[0].previousElementSibling;e&&e.classList.contains("peet-survey-form__counter")&&(e.textContent=`Question 1 of ${n.length}`),n.forEach(((e,o)=>{const i=e.querySelector(".next-step"),r=e.querySelector(".back-step"),s=t.querySelector(".peet-survey-form__submit");i&&(i.style.display="none"),r&&(r.style.display="none"),s&&0===o&&(s.style.display=1===n.length?"block":"none",s.disabled=!0)}))}}))}t.forEach((e=>{e.addEventListener("click",(function(e){e.preventDefault(),o.parentElement.classList.add("contain-auto");const t=this.getAttribute("data-form-link"),n=document.getElementById(`form-popup-${t}`);n&&(n.style.display="block",document.body.style.overflow="hidden")}))})),document.querySelectorAll(".form-popup__close").forEach((t=>{t.addEventListener("click",(function(){const t=this.closest(".form-popup");t&&(t.style.display="none",document.body.style.overflow="",o.parentElement.classList.remove("contain-auto"),e(),n())}))})),document.addEventListener("click",(function(t){document.querySelectorAll(".form-popup").forEach((i=>{if("block"===i.style.display||""===i.style.display){const r=i.querySelector(".form-popup__content");i.contains(t.target)&&!r.contains(t.target)?(i.style.display="none",document.body.style.overflow="",o.parentElement.classList.remove("contain-auto"),e(),n()):i.contains(t.target)||t.target.closest(".button-with-form__label")||(i.style.display="none",document.body.style.overflow="",o.parentElement.classList.remove("contain-auto"),e(),n())}}))}))}));const t={name:siteConfig.blogName,region:siteConfig.websiteRegion,availability:siteConfig.communityAvailability};document.addEventListener("DOMContentLoaded",(function(){const e=[".forsale-right-container__info .brochure-btn",".tabs-popup-btns .btn-tab-brochure",".tabs-popup-btns-info .btn-tab-brochure",".floorplan-btn",".forsale-lot__wrapper .stageplan-btn"];document.querySelectorAll("a").forEach((o=>{o.addEventListener("click",(function(n){if(o.href.endsWith(".pdf")){if(e.some((e=>o.closest(e))))return;n.preventDefault(),window.open(o.href,"_blank");let i=window.location.href,r=o.href?o.href.split("/").pop():"",s={event:"pdf_download",community:t,lot:void 0,filename:r+"|"+i};window.dataLayer=window.dataLayer||[],window.dataLayer.push(s)}}))}))})),jQuery(document).on("click",".hero-banner__btn",(function(){let e=jQuery(this).text().trim(),o=jQuery(this).closest(".hero-banner__header").find("h1").text().trim(),n={event:"click_cta",community:t,promotion_name:o,cta_text:e};window.dataLayer=window.dataLayer||[],window.dataLayer.push(n)})),jQuery(document).ready((function(e){if(0<jQuery(".single-news").length){let e=jQuery(".hero-banner__header--title").text().trim(),o=jQuery(".wp-block-post-date").text().trim(),n=jQuery(".article-categories-list"),i="";n.find("li").each((function(){i+=jQuery(this).text().trim()+", "})),i=i.replace(/, $/,"");let r={event:"blog_view",type:"community",community:t,title:e,category:i,publish_date:o,reading_time:""};window.dataLayer=window.dataLayer||[],window.dataLayer.push(r)}})),jQuery(document).ready((function(e){if(siteConfig.blogName&&siteConfig.websiteRegion){let e={event:"view_community",community:t};window.dataLayer=window.dataLayer||[],window.dataLayer.push(e)}}))})()})();;
