$(function() {
	$('ul.rate_chooser li').mouseover(starUpdate).mouseout(starUpdate).click(ajaxRate);
});

function ajaxRate(event) {
	$('ul.rate_chooser li').unbind('mouseover').unbind('mouseout').unbind('click');
	var url_arr = $(this).children('a').attr('href').split('/');
	var rating = url_arr.pop();
	var offerId = url_arr.pop();
	$('#rate_chooser img.loader').show();
	$.post('/offers/rate/', {rating: rating, offer_id: offerId}, function(data){
		if (data.success) {
			$('#rate_chooser .replace').html('<div class="flash success" id="flashMessage">Your rating has been saved</div>');
			$('#rate_chooser img.loader').hide();
		} else {
			$('ul.rate_chooser li').mouseover(starUpdate).mouseout(starUpdate).click(ajaxRate);
		}
	}, 'json');
	event.preventDefault();
}

function starUpdate(event) {
	if (event.type == 'mouseover') {
		imageUrl = '/img/rating/star.png';
	} else if (event.type == 'mouseout') {
		imageUrl = '/img/rating/star_black.png';
	} else {
		return false;
	}
	$(this).children('a').children('img').attr({src: imageUrl});
	$(this).prevAll().children('a').children('img').attr({src: imageUrl});
}