// Enable jQuery validator on any form with class="validate" which hasn't already been set up
// Modifications made for bootstrap 4 noted below
function enableValidator() {
	var config = {
		ignore: ":hidden",
		// For popover-style validation errors that go nicely with bootstrap
		showErrors: function(errorMap, errorList) {
			window._dbgErrorMap = errorMap;
			window._dbgErrorList = errorList;
			$.each(this.successList, function(index, value) {
				return $(value).popover("hide");
			});

			for ( i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				if ( this.settings.highlight ) {
					this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
				}
			}
			if ( this.settings.unhighlight ) {
				for ( i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
				}
			}

			// Only warn about one error at a time, to avoid popup explosion
			//errorList = errorList.slice(0, 1);
			$.each(errorList, function(index, value) {
				var _popover;
				if ($(value.element).is(':hidden')) {
					value.element = $(value.element).parent();
				}
				_popover = $(value.element).popover({
					trigger: "manual",
					placement: "bottom",
					content: value.message,
					template: "<div class=\"popover\" role=\"tooltip\"><div class=\"arrow\"></div><div class=\"popover-body\"></div></div>", //updated template for bootstrap4
				});
				// _popover.data("bs.popover").options.content = value.message; //js error for bootstrap 4, not vital
				$(value.element).popover("show");
			});
		},
		invalidHandler: function(e) {
			if (typeof enableSubmit == 'function') {
				enableSubmit("Submit Order");
			} else { //if this is not the orders page
				//enable all submits
                $(':submit').removeAttr("disabled");
			}
			return true;
		},
		submitHandler: function(form, e) {
			if (typeof disableSubmit == 'function') {
				disableSubmit('Sending...');
			} else { //if this is not the orders page
				//disable all submits
                $(':submit').prop("disabled", true);
			}
			return true;
		},
	};

	$.extend($.validator.messages, {
		url: 'Please enter a valid URL using this format: https://domain.com'
	});

	$("form.validate").validate(config);
}

$(document).ready(function() {
	// Enable jquery validator for forms which request it (class="validate")
	enableValidator();
});
