(function ($, window) {

	// from jquery.validate.additional.js
	$.validator.addMethod("matadorMaxsize", function (value, element, param) {
		let param_in_bytes = ( param * Math.pow(1024, 2) );

		if (this.optional(element)) {
			return true;
		}

		if ($(element).attr("type") === "file") {
			if (element.files && element.files.length) {
				for (var i = 0; i < element.files.length; i++) {
					if (element.files[i].size > param_in_bytes) {
						return false;
					}
				}
			}
		}

		return true;
	}, $.validator.format(jquery_validate_localization.maxsize));

	// from jquery.validate.additional.js
	$.validator.addMethod("matadorExtension", function (value, element, param) {
		param = typeof param === "string" ? param.replace(/,/g, "|") : "png|jpe?g|gif";
		return this.optional(element) || value.match(new RegExp("\\.(" + param + ")$", "i"));
	}, $.validator.format(jquery_validate_localization.extension));

	$('#matador-application-form').validate({
		submitHandler: function (form) {
			if ( $(".matador-field .g-recaptcha").length && typeof grecaptcha !== 'undefined' && !grecaptcha.getResponse()) {
				alert(jquery_validate_localization.reCaptcha);
				return false;
			}

			$("[name='submit']").attr("disabled", true).addClass('madator-disabled');
			$('#matador-upload-overlay').show();
			return true;
		}
	});

	$('.inputfile').each(function () {
		var $input = $(this);

		$input.rules('add', {
			matadorMaxsize: jquery_validate_localization.maxFileSize,
			matadorExtension: jquery_validate_localization.acceptedExtensions,
		});
		$input.on('change', function (e) {
			var fileName = '',
				$current_input = $(e.target),
				$label = $current_input.prev('label'),
				labelVal = $label.html();

			if (this.files && this.files.length > 1)
				fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
			else if (e.target.value)
				fileName = e.target.value.split('\\').pop();

			if (fileName) {
				$label.find('span').html(fileName);
				$label.addClass('file_added');
			} else {
				$label.html(labelVal);
				$label.removeClass('file_added');
			}
		});

		// Firefox bug fix
		$input
			.on('focus', function () {
				$input.addClass('has-focus');
			})
			.on('blur', function () {
				$input.removeClass('has-focus');
			});
	});

	// auto reload page on select change for filters
	$('.matador-terms-select select[data-method="link"], .matador-terms-select select[data-method="filter"]').each(function () {
		$(this).on('change', function () {
			window.location = $(this).find('option:selected').data('url');
		});
	});

	$('form.matador-search-form[method="get"]').submit(function() {
		// For all inputs, if empty, disable them.
		$(':input', this).each(function () {
			$(this).prop('disabled',!($(this).val()));
		});
		// For multiselect inputs, loop through values and if any are selected,
		// create a hidden input with the values imploded (joined). This will ensure
		// a querystring format that works with WP's taxonomy query.
		$('.matador-terms select[multiple]', this).each(function () {
			var nameMulti = $(this).prop('name'),
				value = $(this).val();

			// The first part does not disable select if the value
			// is an array with an empty string, ie: from a multiselect,
			// so disable this too.
			$(this).prop('disabled', true);

			// If the string has values, we will add the hidden input here.
			// Note, we take a substring of the field name because it comes
			// in as matador-taxonomy[] and we don't want the brackets.
			if (0 !== value.join().length) {
				$('<input type="hidden" name="' + nameMulti.substring(0, nameMulti.length - 2) + '" value="' + value.join() + '" />').insertAfter(this);
			}
		});

		// Loop through the datalist inputs, disable them, sanitize their value, then add a hidden input with the sanitized value.
		const datalistInputContainers = document.querySelectorAll('.matador-search-form .matador-terms-datalist');
		if (datalistInputContainers.length) {
			datalistInputContainers.forEach((container) => {
				const visibleInput = container.querySelector('input[type="text"]');
				if (visibleInput) {
					visibleInput.disabled = true;
					if ( visibleInput.value ) {
						let sanitizedValue = visibleInput.value.toLowerCase().replace(/\s+/g, '-');
						
						// If the selected option exists in the datalist, we use its value instead of simply sanitizing the input text.
						const datalist = container.querySelector('datalist');
						const selectedOption = datalist.querySelector('option[value="' + visibleInput.value + '"]');
						
						if ( selectedOption && selectedOption.dataset.value ) {
							sanitizedValue = selectedOption.dataset.value
						}
						
						const hiddenInput = document.createElement('input');
						hiddenInput.type = 'hidden';
						hiddenInput.name = visibleInput.name;
						hiddenInput.value = sanitizedValue;
						
						container.appendChild(hiddenInput);
					}
				}
			});
		}
	});

	if ( $('#matador-application-form').length ) {
        $.post({
            url: matador_javascript_localize.wp_rest_base + "matador/v1/application/preload",
            data: $('#matador-application-form').serializeArray(),
            headers: {
                'X-WP-Nonce': matador_javascript_localize.wp_rest_nonce
            },
            success: function (data, status) {
                if (data) {
                    data._wpuser =
                        $.each(data, function (key, value) {
                            $('#matador-application-form #' + key).val(value);
                        });
                }
            }
        });
    }

	// Reset button behaviour for Matador Search.
	const resetBtn = document.querySelectorAll( '.matador-search-reset' );
	if ( resetBtn.length ) {
		resetBtn.forEach( (btn ) => {
            btn.addEventListener( 'click', function( e ) {
                e.preventDefault();
                const form = btn.closest( 'form' );
                [...form.elements ].forEach( ( input ) => {
					if ( input.type!=='submit' && input.type!=='reset' ) {
						input.value = '';
					}
				})
            } );
        } );
	}

})(jQuery, window);