$(function(){
	enable_search();
	setup_search_form();
	shuffle_recipes();
	setup_results();
	$('form:first input[type=text]:first').focus();
});

function setup_results(){
	filter_recipes();
}

function enable_search(){
	$('#no_javascript').hide();
	$('#search_boxes').show();
}

function setup_search_form(){
	$('#receptenGallery a div.metadata').each(function(){
		$(this).text($(this).text().toLowerCase());
	});

	$('#fulltextsearch').keyup(function(){
		if($(this).val().length == 0){
			update_fulltextsearch();
		}
	});

	$('#SearchForm').submit(function(){
		update_fulltextsearch();
		return false;
	});

	$('#SelectAllForm').submit(function(){
		$('select.search').each(function(){
			this.selectedIndex = 0;
		});
		$('#fulltextsearch').val('');
		$('#receptenGallery a').show();
		show_no_results('');
		return false;
	});

	$('select.search').change(filter_recipes);
}

function update_fulltextsearch(){
	var $this = $('#fulltextsearch');

	$('select.search').each(function(){
		this.selectedIndex = 0;
	});

	if($this.val() != $this.data('last_val')){
		if($this.val().length == 0){
			$('#receptenGallery a').show();
		}
		else{
			$('#receptenGallery a').hide();
			$("#receptenGallery a div.metadata:contains('" + $this.val().toLowerCase() + "')").each(function(){
				$(this).parent().show();
			});
		}
		$this.data('last_val', $this.val());
	}

	show_no_results('search');
}

function filter_recipes(){
	var product = $('select#product option:selected').val();
	var group = $('select#type option:selected').val();
	var level = $('select#moeilijkheidsgraad option:selected').val();

	$('#fulltextsearch').val('');
	$('#receptenGallery a').each(function(){
		var $this = $(this);
		var filter_match = 0;
		var groups = $this.attr('meta_groups').split('|');

		if(product.length > 0){
			if($this.attr('meta_product').indexOf(product) >= 0){
				filter_match++;
			}
		}
		else{
			filter_match++;
		}

		if(group.length > 0){
			for(i = 0; i < groups.length; i++){
				if(group == groups[i]){
					filter_match++;
					break;
				}
			}
		}
		else{
			filter_match++;
		}

		if(level.length > 0){
			if(parseInt($this.attr('meta_level')) == parseInt(level)){
				filter_match++;
			}
		}
		else{
			filter_match++;
		}

		if(filter_match == 3){
			$this.show();
		}
		else{
			$this.hide();
		}
	});

	show_no_results('filters');
}

function show_no_results(type){
	$('.no_results').hide();	

	if($('#receptenGallery a:visible').length == 0){
		switch(type){
			case 'filters': $('#no_results_filters').show(); break;
			case 'search': $('#no_results_search').show(); break;
		}
	}
}

function shuffle_recipes(){
	$('#receptenGallery a').shuffle();
}

