(function(){
	var data = window.kramarAddressValidation || {};
	var countries = data.countries || [];
	var msg = data.msg || '';
	var shown = {};

	function validate(id, countryId) {
		var field = document.getElementById(id);
		var country = document.getElementById(countryId);
		if (!field) return;
		var cv = country ? country.value : '';
		var val = field.value || '';
		var needsError = countries.indexOf(cv) !== -1 && val.length > 0 && !/\d/.test(val);
		var errId = id + '_kramar_err';
		var errEl = document.getElementById(errId);

		if (needsError && document.activeElement !== field) {
			if (!errEl) {
				var el = document.createElement('span');
				el.id = errId;
				el.textContent = msg;
				field.parentNode.parentNode.appendChild(el);
			}
			field.style.borderColor = '#e2401c';
			shown[id] = true;
		} else if (!needsError && shown[id]) {
			if (errEl) errEl.remove();
			field.style.removeProperty('border-color');
			shown[id] = false;
		}
	}

	setInterval(function() {
		validate('billing_address_1', 'billing_country');
		validate('shipping_address_1', 'shipping_country');
	}, 500);
})();
