(function($) {

	// Any element with the .fd-ajaxLoad class has its AJAX action called on load (load its data asynchronously)
	$('.fd-ajaxLoad').each(function(){
		ajaxLoad($(this).data('ajax-action'), {}, null, false);
	});

	// Any element with the .fd-ajaxSwitch class has its AJAX action called when changed, passing its `checked` value
	$('.fd-ajaxSwitch').change(function(){
		var filter = false;
		if ($(this).prop('checked')) {
			filter = true;
		}
		$(this).prop('disabled', 'disabled'); // Don't allow double submission
		ajaxLoad($(this).data('ajax-action'), { filter: filter }, this, true);
	});

	// Any element with the .fd-ajaxButton class has its AJAX action called when clicked, passing its params
	$('.fd-ajaxButton').click(function(){
		ajaxButtonClick(this);
	});

	// Update parameters for submission in an AJAX form (stored in data for the submit button)
	$('.fd-ajaxFormSelect').change(function(){
		$button = $(this).closest('.fd-ajaxForm').find('.fd-ajaxButton');
		var params = $button.data('ajax-params');
		params[$(this).attr('id')] = $(this).val();
		$button.data('ajax-params', params);
	});

	// Button click function separated so it can be initialised for AJAX-loaded buttons as well
	function ajaxButtonClick(button) {
		$(button).prop('disabled', true); // Don't allow double submission
		ajaxLoad($(button).data('ajax-action'), $(button).data('ajax-params'), button, true);
	}

	// Single function for all AJAX forms that passes data to the correct hook
	// then replaces the content of the relevant DOM object with the results
	function ajaxLoad(action, data, context, showHourglass) {
		if (!action) {
			return;
		}
		if (showHourglass) {
			$('html').addClass('fd-util-wait');
		}
		$.ajax({
			type: "POST",
			url: fdAjax.url,
			context: context,
			dataType: 'html',
			data: { action: action, data: data },
			success: function(data) {

				// If context object (switch or button) was disabled for the call, re-enable
				if ($(this).prop('disabled') === true) {
					$(this).prop('disabled', false);
				}

				// Remove hourglass
				$('html').removeClass('fd-util-wait');

				// Turn the result into jQuery object ready to be appended
				var $content = $(data);

				// console.log(action, data);
				// console.log($content.data('ajax-replace'));

				// Find the target container (specified by the ajax-replace data attribute of the content), insert the new content after it, then remove the target
				$('#' + $content.data('ajax-replace')).after($content).remove();

				// Activate any AJAX buttons contained within the results (load more)
				$('#' + $content.data('ajax-replace')).find('.fd-ajaxButton').click(function() {
					ajaxButtonClick(this);
				});
			}
		});
	}

}(jQuery));
