$(document).ready(function() {

	function load_sucky_beers() {
		$('#sucky_beers').fadeTo(500, 0.1);
		$('#loading_sucky_beers').css('opacity', '0').show().fadeTo(500, 0.9);
		
		$('#sucky_beers').load('/dashboard/sucky_beers.partial', function() {
			$('#sucky_beers').fadeTo(500, 1);
			$('#loading_sucky_beers').fadeTo(500, 0);
		});
	}

	$('#base_beers .havent_tried').live('click', function() {
		var this_li = $(this).parents('li');
		this_li.fadeTo(500, 0.1);
		$.get('/dashboard/base_beer.partial', function(text) {
			var new_dom = $(text).css('opacity', 0.1);
			this_li.replaceWith(new_dom);
			new_dom.fadeTo(500, 1);
			
			$('.rater', new_dom).rater({
				url: function(rating_number, beer_id) {
					return "/beers/" + beer_id + "/rate/" + rating_number + ".js";
				}
			});
		});
	});



	$('#step_3 .havent_tried').live('click', function() {
		var this_li = $(this).parents('li');
		this_li.fadeTo(500, 0.1);
		$.get('/dashboard/sucky_beer.partial', function(text) {
			var new_dom = $(text).css('opacity', 0.1);
			this_li.replaceWith(new_dom);
			new_dom.fadeTo(500, 1);
		});
	});

	$('#favorite_beer input[name=q]').sexySearch({
		onselect: function(e, result) {
			if ($('#favorite_beer_not_found').is(':visible')) $('#favorite_beer_not_found').slideUp();
			$.post('/beers/' + result.id + '/rate/' + 11 + '.js', function() {
				$.get(result.path + '.partial', function(text){
					var new_dom = $(text).hide();
					$("#favorite_beer_results").append(new_dom);
					new_dom.slideDown();
					$('#favorite_beer input[name=q]').val('');
					
					load_sucky_beers();
				});
			});
		}
	}).attr("autocomplete", "off");
	
	var autocomplete_timout;
	$('#favorite_beer input[name=q]').bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
		clearTimeout(autocomplete_timout);
		autocomplete_timout = setTimeout(function() {
			if ($('#favorite_beer input[name=q]').val() != '' && !$('.ac_results').is(':visible'))
				$('#favorite_beer_not_found').slideDown();
		}, 3000);
	}).blur(function() {
		clearTimeout(autocomplete_timout);
	});
	
	$('form#favorite_beer').submit(function() {
		$('#favorite_beer_not_found').slideDown();
		return false;
	});
	
	$('#sucky_beers a.i_hate_this').live('click', function() {
		$.post(this.href + '.js');
		$('#sucky_beers li').not($(this).parents('li')).fadeTo(500, 0.35);
		return false;
	});
});
