/* global cartcueCheckout, jQuery */
(function ($) {
	'use strict';

	// Capture guest email from the checkout billing email field as soon as it
	// looks valid, before the form is submitted.

	var captured = false;
	var debounceTimer;

	function captureEmail() {
		var email = $('#billing_email').val();

		if (!email || captured) {
			return;
		}

		// Basic email validation.
		if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
			return;
		}

		captured = true;

		$.post(cartcueCheckout.ajaxUrl, {
			action: 'cartcue_capture_email',
			nonce: cartcueCheckout.nonce,
			email: email
		});
	}

	$(document).on('input change blur', '#billing_email', function () {
		clearTimeout(debounceTimer);
		debounceTimer = setTimeout(captureEmail, 800);
	});

}(jQuery));
