$(document).ready(function(){

	var rating = 0;
	var item;
	var itemId;
	var widget = document.getElementsByName('rating');
	var numStars = widget.length;
	if (numStars > 0) { 
		//see which rating is selected
		for(var i = 0; i < numStars; i++) {
			if(widget[i].checked) {
				rating = widget[i].value;
			}
		}
	}
	$("span").click(function(e){ 
		//user has selected a new rating
		var rating = $(this).find("input:radio").attr("value");
		var thisStar;
		//cycle through all stars, changing class of each
		$(this)
			.parent('.stars').each(function(s) { 
				var widgetId = $(this).attr('id'); 
				var idParts = widgetId.split('-'); 
				item = idParts[1];
				itemId = idParts[2];
			})
			.find('input:radio').each(function(i) {
				thisStar = $(this).attr('value');
				if (thisStar <= rating) { 
					$(this).parent('span').attr('class','star-on');
				}
				else { 
					$(this).parent('span').attr('class','star-off');
				}
			});
		
		//change value of span#yourRatingValue
		$('#yourRatingValue').text(rating);

		//save new rating in database
		var params = "item=" + item + "&itemId=" + itemId + "&rating=" + rating;
		$.ajax({ 
			type: "POST",
			url: "http://" + location.host + "/scripts/ajaxStars.php",
			data: params,
			dataType: "text",
			success: function(result){
				if (trim(result) == '-1') { 
					$('#yourRating').text('You must sign in to rate a ' + item);
				}
				else if (trim(result) > 0) {
					//result is the updated avg rating for this item
					$('#avgRatingValue').text(result);
				}
			}
		});
	});
});

