
$(function() {
	// Helper Functions
	function clearToggles() {
		jcf.refresh($('#refine-filters .checklist input[type=checkbox]').prop('checked', false));
	}

	function notifySearching() {
		$('#content').html('<p class="search-message">Searching...</p>');
		$('#refine-filters .disable').show();
	}

	function linkSearch(key, value, refine) {
		// Set values on the input
		$('#link-search .dynamic')
			.attr('name', key)
			.attr('value', value);

		// If asked not to refine, remove the extra parameters
		if (!refine) {
			$('#link-search .refine').remove();
		}

		// If we are refining, or the key is the same as our current grouping, we'll want to switch to relevance
		var grouping = $('#link-search .grouping');
		if (refine || key == grouping.val()) {grouping.val('relevance');}

		// If we're actually linksearching /by/ grouping (grouping drop down), delete the grouping field to stop it overriding.
		if (key == 'grouping') {grouping.remove();}

		// Notify that we're searching and submit the form.
		notifySearching();
		$('#link-search').submit();
	}

	function updateDefaultGrouping() {
		var resource   = $('.resource-form #resource').val()
		  , artform    = $('.resource-form #artform').val()
		  , legalTopic = $('.resource-form #legal-topic').val()
		  , input      = $('.resource-form input[name=grouping]');

		if (resource != 'all' && artform == 'all' && legalTopic == 'all') {input.val('alphabetical');} else {input.val('relevance');}
	}

	// Handle link search tag clicks
	$('.link-search').click(function() {
		var $this = $(this);
		linkSearch(
			$this.data('key'),
			$this.data('value'),
			$this.data('refine'));
		return false;
	})

	// When a narrative filter select is changed, update the text in the hidden fields
	$('.resource-form select').change(function() {
		var $this = $(this);
		$('.resource-form [name="narrative_' + $this.attr('name') + '"]')
			.val($this.find(':selected').text());
	});
	// Populate the fields at page load
	$('.resource-form select').each(function() {$(this).change();});

	// Default grouping for /_search_form
	$('.resource-form select').change(function() {updateDefaultGrouping();});
	// Run on page load
	updateDefaultGrouping();

	// Grouping drop down
	$('#grouped').change(function() {
		linkSearch('grouping', $(this).val(), true);
	});

	// Refine filter submission
	$('#refine-filters').submit(function() {
		// If 'search within results' is unchecked, clear other toggles.
		if (!$('#search-within-results').prop('checked')) {clearToggles();}

		notifySearching();
	});

	// Handle checkbox clicks
	var timer = false;
	$('#refine-filters .checklist input').change(function() {
		// Someone just selected a checkbox, make sure search within results is enabled
		$('#search-within-results').prop('checked', true);

		// ~5 second cooldown before the form is submitted, resets each time something new is selected
		if (timer != false) {clearTimeout(timer);}
		timer = setTimeout(function() {$('#refine-filters').submit();}, 5000);
	});

	// Refine filter clear button
	$('#refine-filters .clear-all').click(function() {
		// Clear keywords
		$('#refine-filters [type=search]').val('');

		// Uncheck all checkboxes
		$('#refine-filters [type=checkbox]').prop('checked', false);

		// Re-check the search within results box
		$('#search-within-results').prop('checked', true);

		// Switch resources to 'all'
		$('#refine-filters [name=resource][value=all]').prop('checked', true);

		// Refresh JCF
		jcf.setOptions('Select', {
			wrapNative: false,
			wrapNativeOnMobile: false
		});
		jcf.replaceAll();

		return false;
	});

	// Keyword search readout close button
	$('.remove-filter-keywords').click(function() {
		notifySearching();
		$(this).parent().find('form').submit();
	});

	// On small screens, need to be able to show/hide the filters
	$('#refine-filters .head').click(function() {
		$('#refine-filters').toggleClass('opened closed');
	});
});
