$(function() {
	
	var allow_submit = false;
	
	$("#disease_name").autocomplete(Drupal_base_path + 'avian_autocomplete.php', {extraParams: { 'v': '10' }, cacheLength: 10, matchContains: 1, scrollHeight: 150, delay: 10});
	
	$("#location_name").autocomplete(Drupal_base_path + 'avian_autocomplete.php', {extraParams: { 'v': '6' }, cacheLength: 10, matchContains: 1, scrollHeight: 150, delay: 10});
	
	$("#clinical_sign_name").autocomplete(Drupal_base_path + 'avian_autocomplete.php', {extraParams: { 'v': '2' }, cacheLength: 10, matchContains: 1, scrollHeight: 150, delay: 10});
	
	$('#disease_name, #location_name, #clinical_sign_name').result(function(event, data, formatted) {
			allow_submit = (!data) ? false : true;
			
			if (allow_submit) {
				$('#search-error').fadeOut();
			}
	});
	
	// don't submit blank forms
	$('#form1, #form2, #form3').submit(function() {
			$(this).find("input[type='text']").search();
			if (!allow_submit) {
				var error_msg;
				
				if ($(this).find("input[type='text']").val() == '') {
					$('#search-error').text('Please enter some search text.').show(150);
				} else {
					$('#search-error').text('Your search text was not found. Try again or click on "' + $(this).find('a').text() + '" for a list.').show(150);
				}
				
				return false;
			}
			return allow_submit;
	});
	
	$('#search-picker').before(
		$('<ul></ul>')
			.attr('id', 'search-types')
	).after(
		$('<div></div>')
			.attr('id', 'search-error')
			.hide()
	);
		
	var search_picks = $("#search-picker .search-pick");
	var hover_timer = null;
	
	search_picks.find('form').end().find('h2').each(function(index) {
			$('#search-types').append(
				$('<li></li>')
					.text($(this).text())
					.data('num', index)
					.click(function(ev) {
						var tgt = $(ev.target);
						if (tgt.hasClass('active')) {
							return;
						}
						
						$('#search-error').fadeOut();
						tgt.siblings().removeClass('active');
						tgt.addClass('active');
						search_picks.find('form').hide();
						search_picks.find('form').eq(tgt.data('num')).fadeIn(150).find("input:first").focus();
					})
					.mouseover(function(ev) {
						var tgt = $(ev.target);
						hover_timer = setTimeout(function() {
								$('#search-types li').eq(tgt.data('num')).trigger('click');
						}, 500);
					})
					.mouseout(function() {
						if (hover_timer) {
							clearTimeout(hover_timer);
						}
					})
			);
			$(this).remove();
		});
	
	
	$('#search-types li:eq(0)').trigger('click');
	
	$('#search-picker .activesearch li:even').addClass('even')
});
