/*!
 * CartNinja Recovery - Public JS
 * Source file included in this plugin package.
 * Not minified - this is the full source.
 */

(function ($) {
	'use strict';

	var timer = null;
	var hasCapturedCheckoutData = false;

	function hasValue(value) {
		return !!String(value || '').trim();
	}

	function hasCheckoutContactDetails() {
		return hasValue($('#billing_phone').val()) || hasValue($('#billing_email').val());
	}

	function captureFields(extra) {
		var payload = {
			action: 'cartninja_capture_checkout_fields',
			nonce: cartninjaPublic.nonce,
			email: $('#billing_email').val() || '',
			phone: $('#billing_phone').val() || '',
			first_name: $('#billing_first_name').val() || '',
			country_code: $('#billing_country').val() || '+91'
		};

		payload = $.extend(payload, extra || {});

		if (!payload.email && !payload.phone) {
			return $.Deferred().reject().promise();
		}

		return $.post(cartninjaPublic.ajaxUrl, payload);
	}

	$(document).on('input change', '#billing_email, #billing_phone, #billing_first_name, #billing_country', function () {
		if (hasCheckoutContactDetails()) {
			hasCapturedCheckoutData = true;
		}

		clearTimeout(timer);
		timer = window.setTimeout(function () {
			captureFields().done(function () {
				hasCapturedCheckoutData = true;
			});
		}, 700);
	});

	$(function () {
		if (hasCheckoutContactDetails()) {
			hasCapturedCheckoutData = true;
		}
	});
})(jQuery);
