function rate(rating) {	
	 
	

	$.post(voteHandler,
		   {rating: rating},
		   rateSuccessHandler,
		   'json'
		);
}

function rateSuccessHandler(result) {
			
	 var avgRating = result.avg_rating;
	 var votes = result.votes;
	 var userRating = result.user_rating;
	 
	 if (avgRating > 0 && votes > 0) {
		 $('#avg_rating').html(avgRating); 
		 $('#votes_count').html("(based on " + votes + " votes)"); 
		 $('#user_rating').html("Your rating is: " + userRating);
	 } else {
		 $('#avg_rating').html("N/A");
		 $('#votes_count').html("(Not rated yet)");
	 }
	 
	 Cookie.set("phone_rating_" + productId, userRating, 3600 * 24);
	 
	if (woopraEnabled) { 
		woopraTracker.postRating(userRating, result.object);		
	}
	
	if (result.facebook == 1) {
		
		 FB.ui(
				   {
				     method: 'stream.publish',
				     message: 'My rating of  ' + result.object + ' on www.mymobiles.com is ' + userRating,
				     attachment: {
				       name: result.object,				     
				       href: result.link,					     
				       description: result.description,	
					   media:  [{ 
					        'type': 'image', 
					        'src': result.picture, 
					        'href':  result.link}] 

				     },	       
				     action_links: [],
				     user_message_prompt: 'Share your opinion'
				   },
				   function(response) {
				    
				   }
				 );

	}
}

$(function() {
	var cookieValue = Cookie.get("phone_rating_" + productId);

	var rated = cookieValue != null; 
	
	if (cookieValue != null) {
		$('#user_rating').html("Your rating is: " + cookieValue);
	}

	
	$("#rating_c").children().not(":radio").hide();

	$("#rating_c").stars({
		cancelShow: false,
		oneVoteOnly: true,
		captionEl: null,
		disabled: rated,
		callback: function(rated, ui, type, value){
		
			if (rated) {
				return;
			}
			rate(value);
		}.curry(null, [rated])
	});
	
});	



