if ( rsvp_pro_data == undefined ) {
	var rsvp_pro_data = {};
}
jQuery(document).ready(function(){
	jQuery(".rsvpProCustomQuestionDatePicker").datepicker({
		dateFormat: 'yy-mm-dd'
	})

	jQuery.validator.addMethod("customNote", function(value, element) {
		if((jQuery("#additionalProRsvp").val() > 0) && (jQuery("#note").val() == "")) {
			return false;
		}

		return true;
	}, "<br />Please enter an email address that we can use to contact you about the extra guest.  We have to keep a pretty close eye on the number of attendees.  Thanks!");

	if( rsvp_pro_data == undefined ) {
		if( jQuery("#rsvp_id").val() != undefined && (jQuery("#rsvp_id").val() > 0)) {
			var data = {
				'action': 'get_validation_messages',
				'rsvp_id': jQuery("#rsvp_id").val()
			};
			jQuery.ajaxSetup({async:false});
			jQuery.post(rsvp_pro_data.ajaxurl, data , function(response) {
				var json = JSON.parse(response);
				rsvp_pro_data = json;
			});
			jQuery.ajaxSetup({async:true});
		}
		if( rsvp_pro_data == undefined ) {
			rsvp_pro_data = {
				'first_name_message': 'Please enter a first name',
	        	'last_name_message': 'Please enter a last name',
	        	'note_message': 'If you are adding additional RSVPs please enter your email address in case we have questions',
	        	'email_message': 'Please enter an email address',
	        	'gdpr_message': 'This field is required',
	        	'unique_passcode_message': 'Passcode is already in use',
	        	'unique_email_message': 'Email is already in use',
	        	'require_unique_passcode': true,
	        	'require_unique_email' : true,
	        	'enable_ajax' : false,
	        	'always_show_additional' : false,
	        	'enable_payments' : false,
	        	'thousands_separator' : ',',
	        	'decimal_separator' : '.',
	        	'currency_symbol' : '$',
	        	'ticket_prices' : [],
			}
		}
	}

	if ( rsvp_pro_data.enable_payments ) {
		rsvpProWireUpCostCalculation();
		jQuery("input[class=rsvpStatusInput]").on('change', function() {
			rsvpProCalculateAttendeeCost();
		});
		rsvpProCalculateAttendeeCost(); // Fire this once on page load.
	}

	jQuery("input[type=radio][name=mainRsvp]").change( function() {
		toggleAdditionalRsvpContainer( this.value, rsvp_pro_data.always_show_additional );
	});

	toggleAdditionalRsvpContainer( jQuery('input[name=mainRsvp]:checked').val(), rsvp_pro_data.always_show_additional );

	jQuery.validator.addMethod("rsvpRequired", function(value, element) {
		var prefix = jQuery(element).attr("data-rsvpprefix");
		var rsvp_js_id = jQuery(element).closest(".rsvpCustomQuestion").attr("data-rsvp-question-js-id");
		var rsvpFormName = "";
		if(prefix == "main") {
			rsvpFormName = "mainRsvp";
		} else {
			rsvpFormName = "attending" + prefix;
		}
		
		var rsvpValue = jQuery("input[data-rsvp-js-id='" + rsvp_js_id + "']:checked").val();
		if(jQuery("input[data-rsvp-js-id='" + rsvp_js_id + "']").attr("type") == "hidden") {
			rsvpValue = jQuery("input[data-rsvp-js-id='" + rsvp_js_id + "']").val();
		} 

		if(value == undefined) {
			value = "";
		}
		
		if(rsvpValue == "Y" || rsvpValue == "W" || rsvpValue == "PlusOne") {
			if(value == "") {
				return false;
			}
		}
		return true;
	}, "<br />This field is required");

	jQuery.validator.addMethod("rsvpProEmailUnique", function( value, element ) {
		var eventId = jQuery('#rsvp_id').val();
	    var attendeeId = jQuery('#attendeeID').val();
	    var isUnique = true;

	    if ( attendeeId == undefined ) {
	      attendeeId = 0;
	    }

	    if ( !rsvp_pro_data.require_unique_email ) {
	    	return true;
	    }

	    // Loop through the client-side email fields first and if a non-unique value is found 
	    // error out here and don't make the 'expensive' AJAX call to check the backend.
	    var emailFields = jQuery(".rsvpEmailField");
	    for( var i = 0; i < emailFields.length; i++) {
	    	if ( ( jQuery(emailFields[i]).attr('name') != jQuery(element).attr('name') ) && ( jQuery(emailFields[i]).val() == value ) ) {
	    		isUnique = false;
	    	}
	    }
	    

	    if ( isUnique ) {
		    var datastring = "rsvp_id=" + eventId + "&attendee_id=" + attendeeId + "&email=" + value;
		    datastring += "&action=rsvp_pro_unique_email_validation";
		    jQuery.ajax({
		      type: "POST",
		      async: false,
		      url: rsvp_pro_data.ajaxurl,
		      data: datastring ,
		      success: function(response) {
		        var json = JSON.parse(response);
		        if( json.has_been_used == true ) {
		          isUnique = false;
		        }
		      },
		    });
		}
	    
	    return isUnique;
	}, "<br />" + rsvp_pro_data.unique_email_message);

	jQuery.validator.addMethod("rsvpProPasscodeUnique", function(value, element) {
	    var eventId = jQuery('#rsvp_id').val();
	    var attendeeId = jQuery('#attendeeID').val();
	    var isUnique = true;

	    if ( attendeeId == undefined ) {
	      attendeeId = 0;
	    }

	    if ( !rsvp_pro_data.require_unique_passcode ) {
	    	return true;
	    }

	    // Loop through the client-side passcode fields first and if a non-unique value is found 
	    // error out here and don't make the 'expensive' AJAX call to check the backend.
	    var passcodeFields = jQuery(".rsvpPasscodeField");
	    for( var i = 0; i < passcodeFields.length; i++) {
	    	if ( ( jQuery(passcodeFields[i]).attr('name') != jQuery(element).attr('name') ) && ( jQuery(passcodeFields[i]).val() == value ) ) {
	    		isUnique = false;
	    	}
	    }
	    

	    if ( isUnique ) {
		    var datastring = "rsvp_id=" + eventId + "&attendee_id=" + attendeeId + "&passcode=" + value;
		    datastring += "&action=rsvp_pro_has_passcode_been_used";
		    jQuery.ajax({
		      type: "POST",
		      async: false,
		      url: rsvp_pro_data.ajaxurl,
		      data: datastring ,
		      success: function(response) {
		        var json = JSON.parse(response);
		        if( json.has_been_used == true ) {
		          isUnique = false;
		        }
		      },
		    });
		}
	    
	    return isUnique;
	  }, "<br />" + rsvp_pro_data.unique_passcode_message);

	rsvp_pro_wireup_rsvp_form_validation();
  /* First step, where they search for a name */
	jQuery("#rsvp").validate({
		rules: {
			firstName: "required",
			//lastName: "required"
		},
    	messages: {
      		firstName: "<br />" + rsvp_pro_data.first_name_message,
      		lastName: "<br />" + rsvp_pro_data.last_name_message
    	}
  	});

	wireup_rsvp_add_additional_attendee_buttons();
	wireup_rsvp_questions_for_custom_question_toggle();
	toggle_custom_questions_on_load();

	jQuery("#rsvp_toggle_attendee_search").on('click', function() {
		jQuery("#rsvp_toggle_attendee_search").hide();
		jQuery("#rsvp_existing_attendee_form").removeClass("hide_form");
	});

	rsvp_pro_ajax_form_handling(rsvp_pro_data.enable_ajax, rsvp_pro_data.ajaxurl);

	jQuery(".delete_attendee_attachment").on("click", function(event) {
    event.preventDefault();
    let token = jQuery(this).attr("data-attendee-token");
    let qid = jQuery(this).attr("data-question-id");

    if ( ( token != '' ) && ( qid != '' ) ) {
      var datastring = "attendee_token=" + token + "&qid=" + qid;
      datastring += "&action=rsvp_delete_custom_question_file";
      jQuery.ajax({
        context: this,
        type: "POST",
        url: rsvp_pro_data.ajaxurl,
        data: datastring ,
        success: function(response) {
          jQuery(this).parent().remove();
        },
      });
    }
  });
});

function wireup_rsvp_add_additional_attendee_buttons() {
	jQuery(".addAdditionalProAttendees").click(function(event) {
		event.preventDefault();
		let rsvp_id = jQuery(this).parents('form').find("#rsvp_id").val();
		let function_name = "handleAddRsvpClick_" + rsvp_id + "()";
		eval( function_name );
	});
	jQuery("#addWizardRsvp").click(function(event) {
		event.preventDefault();
		handleAddWizardRsvpClick();
	});
}

function wireup_rsvp_questions_for_custom_question_toggle() {
	jQuery(".rsvpRsvpQuestionArea input[type=radio]").change(function() {
		var rsvp_value = translate_rsvp_value(jQuery(this).val());
		var js_id = jQuery(this).attr("data-rsvp-js-id");

		handle_custom_question_toggle(rsvp_value, js_id);
	});
}

function toggle_custom_questions_on_load() {
	// first hide all items that should be hidden...
	var questions = jQuery(".rsvpCustomQuestion[data-rsvp-only-show-on]");
	for( var i = 0; i < questions.length; i++) {
		jQuery(questions[i]).hide();
	}

	var rsvps = jQuery(".rsvpRsvpQuestionArea input[type=radio]:checked");
	for( var i = 0; i < rsvps.length; i++) {
		var rsvp_value = translate_rsvp_value(jQuery(rsvps[i]).val());
		var js_id = jQuery(rsvps[i]).attr("data-rsvp-js-id");
		
		handle_custom_question_toggle(rsvp_value, js_id);
	}
}

function handle_custom_question_toggle(rsvp_value, js_id) {
	var questions = jQuery(".rsvpCustomQuestion[data-rsvp-question-js-id=" + js_id + "]");
	for( var i = 0; i < questions.length; i++ ) {
		if(jQuery(questions[i]).attr("data-rsvp-only-show-on") == rsvp_value) {
			jQuery(questions[i]).show();
		} else if(jQuery(questions[i]).attr("data-rsvp-only-show-on") != undefined) {
			jQuery(questions[i]).hide();
		}
	}
}

function translate_rsvp_value(rsvp_value) {
	if( rsvp_value == 'Y') {
		rsvp_value = 'Yes';
	} else if( rsvp_value == 'W' ) {
		rsvp_value = 'Waitlist';
	} else if( rsvp_value == 'N' ) {
		rsvp_value = "No";
	} else if( rsvp_value == 'M' ) {
		rsvp_value = "Maybe";
	} else if (rsvp_value == "NoResponse" ) {
		rsvp_value = "NoResponse";
	} else if (rsvp_value == "PlusOne" ) {
		rsvp_value = "PlusOne";
	}

	return rsvp_value;
}

function wireup_rsvp_captcha() {
	if(jQuery("#rsvpCaptcha").length) {
		grecaptcha.render('rsvpCaptcha', {
		    sitekey: jQuery("#rsvpCaptcha").attr("data-sitekey")
		});
	}
}

function rsvp_pro_wireup_rsvp_form_validation() {
	jQuery("#rsvpForm").validate({
		onkeyup: false,
		rules: {
			note: "customNote",
			newAttending1LastName: {
				required: (( rsvp_pro_data.require_last_name ) ? true : false)
			},
			newAttending1FirstName: "required",
			newAttending2LastName: {
				required:( ( rsvp_pro_data.require_last_name ) ? true : false)
			},
			newAttending2FirstName: "required",
			newAttending3LastName: {
				required: (( rsvp_pro_data.require_last_name ) ? true : false)
			},
			newAttending3FirstName: "required",
			attendeeFirstName: "required",
			attendeeLastName: {
				required: (( rsvp_pro_data.require_last_name ) ? true : false)
			},
			gdpr_question: "required",
		},
		messages: {
			note: "<br />" + rsvp_pro_data.note_message,
			newAttending1LastName:  "<br />" + rsvp_pro_data.last_name_message,
			newAttending1FirstName: "<br />" + rsvp_pro_data.first_name_message,
			newAttending2LastName:  "<br />" + rsvp_pro_data.last_name_message,
			newAttending2FirstName: "<br />" + rsvp_pro_data.first_name_message,
			newAttending3LastName:  "<br />" + rsvp_pro_data.last_name_message,
			newAttending3FirstName: "<br />" + rsvp_pro_data.first_name_message,
      		attendeeFirstName: "<br />" + rsvp_pro_data.first_name_message,
      		attendeeLastName: "<br />" + rsvp_pro_data.last_name_message,
      		gdpr_question: "<br />" + rsvp_pro_data.gdpr_message,
		},
		errorPlacement: function(error, element) {
			if (element.attr("type") == "checkbox" || element.attr("type") == "radio") {
				error.prependTo(element.parent("div.rsvpFormField"));	
			} else {
				// the default error placement for the rest
         		error.prependTo(element.parent("div.rsvpFormField"));	
			}
		}
	});
}

function rsvp_pro_ajax_form_handling(enable_ajax, ajax_url) {
	if ( enable_ajax ) {
		jQuery(document).on( "submit", ".rsvp_pro_container form", function(event) {
			event.preventDefault();
			var data = new FormData(this);
			var rsvp_id = jQuery( this ).find("#rsvp_id").val();
			data.append('action', 'handle_rsvp_form');
			jQuery.ajax({
		      type: "POST",
		      url: ajax_url,
		      processData: false,
		      contentType: false,
		      data: data,
		      success: function(response) {
		      	jQuery("#rsvp_pro_container_" + rsvp_id).replaceWith(response);
		      	wireup_rsvp_questions_for_custom_question_toggle();
		      	toggle_custom_questions_on_load();
		      	wireup_rsvp_captcha();
				onloadRSVPTurnstileCallback();
		      	wireup_rsvp_add_additional_attendee_buttons();
		      	if ( rsvp_pro_data.enable_payments ) {
					rsvpProWireUpCostCalculation();
					rsvpProCalculateAttendeeCost(); // Fire this once on page load.
				}
		      	jQuery(document).resize();
		      	rsvp_pro_wireup_rsvp_form_validation();
		      },
		    });
		});

		jQuery(document).on( "click", ".rsvpFindAttendeeLinkContainer a", function(event) {
			event.preventDefault();
			var rsvp_id = jQuery( this ).parents(".rsvp_pro_container").find("#rsvp_id").val();
			datastring = 'rsvpStep' + rsvp_id + "=attendee_search&rsvp_id=" + rsvp_id + "&action=handle_rsvp_form";
			jQuery.ajax({
				type: "POST",
				url: ajax_url,
				data: datastring,
				success: function(response) {
					jQuery("#rsvp_pro_container_" + rsvp_id).replaceWith(response);
					wireup_rsvp_add_additional_attendee_buttons();
					if ( rsvp_pro_data.enable_payments ) {
						rsvpProWireUpCostCalculation();
						rsvpProCalculateAttendeeCost(); // Fire this once on page load.
					}
					jQuery(document).resize();
					rsvp_pro_wireup_rsvp_form_validation();
				},
			})
		});
	}
}

function toggleAdditionalRsvpContainer(mainRsvpValue, alwaysShowAdditional) {
	if ( alwaysShowAdditional || (jQuery("#wizardStep").val() != undefined ) ) {
		jQuery("#additionalRsvpContainer").show();
		return;
	}
	
	if (mainRsvpValue == "Y" || mainRsvpValue == "M" ) {
		jQuery("#additionalRsvpContainer").show();
	} else {
		jQuery("#additionalRsvpContainer").hide();
	}
}

function rsvpProWireUpCostCalculation() {
	if ( rsvp_pro_data.enable_payments ) {
		jQuery("input[class=rsvpStatusInput]").on('change', function() {
			rsvpProCalculateAttendeeCost();
		});
	}
}

function rsvpProCalculateAttendeeCost() {
	var totalPrice = 0;

	jQuery("input[class=rsvpStatusInput]:checked").each(function( i, obj ) {
		let tmpVal = jQuery(this).val();

		if ( tmpVal == "PlusOne" || tmpVal == "Y" || tmpVal == "M" ) {
			let multiple = 1;

			if ( tmpVal == "PlusOne" ) {
				multiple = 2;
			}

			if ( jQuery(this).attr("name").indexOf("RsvpSub") != -1 ) {
				let idx = jQuery(this).attr("name").indexOf("RsvpSub");
				idx = idx + 7;
				let tmpId = jQuery(this).attr("name").substring(idx);
				if ( ( typeof rsvp_pro_data.ticket_prices[tmpId] !== undefined ) && ( rsvp_pro_data.ticket_prices[tmpId] != "" ) ) {
					totalPrice += parseFloat(rsvp_pro_data.ticket_prices[tmpId]) * multiple;
				}
			} else {
				if ( typeof rsvp_pro_data.ticket_prices['main'] !== undefined ) {
					totalPrice += parseFloat(rsvp_pro_data.ticket_prices['main']) * multiple;
				}
			}
		}
	});

	let formattedPrice = totalPrice.toFixed(2) // always two decimal digits
	      .replace('.', rsvp_pro_data.decimal_separator) // replace decimal point character
	      .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + rsvp_pro_data.thousands_separator);
    if ( rsvp_pro_data.currency_position == 'after' ) {
    	formattedPrice = formattedPrice + rsvp_pro_data.currency_symbol;
    } else {
    	formattedPrice = rsvp_pro_data.currency_symbol + formattedPrice;
    }
	jQuery("#rsvpProTicketTotal").text( formattedPrice );
}

jQuery.extend(jQuery.validator.messages, { 
	required : rsvp_pro_translate.errors['required'],
	email    : rsvp_pro_translate['errors']['email'],
 });

function onloadRSVPTurnstileCallback() {
	const turnstileDiv = document.getElementById( 'rsvpTurnstile' );
	if ( ! turnstileDiv ) {
		return;
	}
	if (window?.turnstile) {
		window.turnstile.ready(function() {
			window.turnstile.render(turnstileDiv, {
				sitekey: turnstileDiv.getAttribute("data-sitekey"),
				refreshExpired: 'auto',
			});
		});
	}      
};