$(function() {

  // Flip adverts for correct region
	$('div.country-us').hide();
	$.getJSON("http://api.gothick.org.uk/hereorthere.php?callback=?", function(data) {
		if (data.country_code == 'GB') {
			$('div.country-uk').show();
			$('div.country-us').hide();
		} else {
			$('div.country-uk').hide();
			$('div.country-us').show();						
		}
	});

	$(".average-stars-wrapper").stars({
    inputType: "select"
	});
	
	$(".user-stars-wrapper").stars({
    inputType: "select",
    callback: function(stars, type, value, e) {
    	$.ajax(
    		stars.$form.attr('action'),
    		{
    			type: 'post',
    			data: {
    				'sentence_id': stars.$form.children('input[name=sentence]').val(),
    				'rating': type == 'cancel' ? '0' : value
    			},
    			success: function(data) {
    				// Our return value will be an entire new rating div, with which
    				// we'll replace the existing one.
    				var obj = $.parseJSON(data);
    				// Reset our rating count and average for this sentence.]
    				var rating = stars.$form.closest('.rating');
    				rating.find('.count').html(obj.new_rating_count);
						rating.find('.average-stars-wrapper').stars("select", obj.new_average_rating);
						rating.find('.average-description').html(obj.new_average_rating_description);
    			}
    		}
    	); 
    }
 	});
 	
 	
	$(".user-stars-wrapper").each(
		function() {
			$(this).stars({
				captionEl: $(this).find('.caption'),
				inputType: "select",
				callback: function(stars, type, value, e) {
					$.ajax(
						stars.$form.attr('action'),
						{
							type: 'post',
							data: {
								'sentence_id': stars.$form.find('input[name=sentence]').val(),
								'rating': type == 'cancel' ? 0 : value
							},
							success: function(data) {
								var obj = $.parseJSON(data);
								var rating = stars.$form.closest('.rating');
								rating.find('.count').html(obj.new_rating_count);
								rating.find('.average-stars-wrapper').stars("select", obj.new_average_rating);
								rating.find('.average-description').html(obj.new_average_rating_description);
							}
						}
					)
				}
			});
		}
	);

  $(".flash_notice").delay(1000).effect("fade", {}, 1000);
  $("#hitme").effect("bounce", { distance: 20, direction: 'down', times: 2 }, 300);
 	
});
