// super duper speedy search filter!!
// working with jQuery quicksearch this script toggles to visual state
// of the buttons within 3 categories and a show all button
// then populates the quicksearch field with the appropriate tag to trigger the search
// Paul Evans, PEDesign, Oct 2009

$(document).ready(function () {
	// activate quicksearch
	$('.searchtags').quicksearch({
		position: 'before',
		attached: '#srp',
		labelText: '',
		hideElement: 'parent',
		formId:'filterer',
		loaderImg:'/sites/all/themes/bakewellpools/images/ui/spinner.gif',
		labelText: 'DEV ONLY',
		onAfter: function() {checkResults($('#freetext').val())},
		randomElement: 'freetext'
	});
	// set the click function for the buttons
	$('.filter').click(function() {
		if (!$(this).is('.selected') ) {
			$(this).addClass('selected');
			$(this).siblings().removeClass('selected');
			var thisTag = $(this).attr('tag');
			updateSearchField(thisTag,1);
			$(this).siblings().each(function() {
				removeTag = $(this).attr('tag');
				updateSearchField(removeTag,0);
			});
		} else {
			$(this).removeClass('selected');
			var thisTag = $(this).attr('tag');
			updateSearchField(thisTag,0);
		}
	});
});

// function to populate the quicksearch field based on the button clicked
// passes 'tag' which is the text clicked
// passes 'type' which specifies whether to add(1) or delete(2) it from the field
function updateSearchField(tag,type) {
	if (tag == 'all') {
		var newFilters = '';
		$('#search-filters .filter').removeClass('selected');
		$('#all-option').addClass('selected');
	} else {
		$('#all-option').removeClass('selected');
		// get the current search string from the field
		var currentFilters = $('#freetext').val();
		// check if we are adding(1) or removing(2) from type parameter
		if (type) {
			// add the new text plus a space to the search string, from tag parameter
			var newFilters = currentFilters+tag+' ';
		} else {
			var re = new RegExp(tag+' ', 'gi');
			var newFilters = currentFilters.replace(re,'');
		}
	}
	$('#freetext').val(newFilters);
	$('#freetext').keydown();
	if (newFilters == '') {
		$('#all-option').addClass('selected');	
	}
}

function checkResults(term) {
	var results = 0;
	if ( term != "" ) {
		term = term.slice(0, -1);
		var aTerm = term.split(' ');
		$('#search-feedback').hide();
		var matches = 0;
		
		$('.searchtags').each( function() {
			var tags = $(this).html();
			var termFound = 0;
			for ( i=0; i < aTerm.length; i++ ) {
				if (tags.indexOf(aTerm[i]) > -1) {
					termFound = termFound+1;
				}
			}
			if (termFound == aTerm.length) {
				results = 1;
				matches = matches+1;
			}
		});
		if (results == 1) {
			$('#search-feedback').html('There are ' + matches + ' works matching your search');
		} else {
			$('#search-feedback').html('Sorry, there are no works matching this combination');
		}
	} else {
		$('#search-feedback').html('All works are listed below');
	}
	$('#search-feedback').fadeIn();
}	   

