
$(document).ready(function(){
	$("div.imageRating li").bind("mouseenter",
		function()
		{
			$(this).nextAll().removeClass("hover");
			$(this).addClass("hover");
			$(this).prevAll().addClass("hover");
		}
	);

	$("div.imageRating ul").bind("mouseleave",
		function()
		{
			$(this).children().removeClass("hover");
		}
	);
	
	
	//	note, to keep the local page in sync, the 'ratingUpdated' event on the parent container (of the UL with stars in it)
	//	gets fired. see gallery.js for an example of handling this event
	$("div.imageRating li").click(
		function()
		{
			var imageID = extractID($(this).parent().attr("class"));
			var stars = $(this).prevAll().size() + 1;
			var parentDiv = $(this).parent().parent();
			
			//	set in-progress status
			updateRatingString(imageID,999);
			
			//	get post info
			var postInfo = {
				"Action":"ImageRating",
				"imageID":imageID,
				"rating":stars
			};
			var token = getFormToken();
			postInfo[token["Name"]] = token["Value"];
			
			//	ajax call
			$.post("/imageactions/",postInfo,function(response,status)
			{
				if(status == "success" && response == "SUCCESS")
				{
					setRatingView(imageID,stars);
					parentDiv.trigger('ratingUpdated',[stars,imageID]);
				}
				else
				{
					updateRatingString(imageID,-1);
				}
			},"text");
		}
	);
	
});


//	update the string
function updateRatingString(imageID,rating)
{
	var ratingString;
	var ratingElement = $("div.imageRating ul.rating_" + imageID).prev();
	if (rating < 0)
	{
		//	error
		ratingString = "Error...Please try Again";
		ratingElement.removeClass("inProgress").addClass("error");
	}
	else if (rating == 0)
	{
		//	unrated
		ratingString = "Click to Rate";
		ratingElement.removeClass("inProgress").removeClass("error");
	}
	else if (rating == 999)
	{
		//	in progress
		ratingString = "...Updating...";
		ratingElement.removeClass("error").addClass("inProgress");
	}
	else
	{
		//	rated
		ratingString = "Your Rating";
		ratingElement.removeClass("error").removeClass("inProgress");
	}
	ratingElement.html(ratingString);
}


//	make the component reflect the current status
function setRatingView(imageID,stars)
{
	//	works with unrated images
	if (stars == undefined)
	{
		stars = 0;
	}
	
	//	update the string describing the rating
	updateRatingString(imageID,stars);
	
	//	update the status of the stars
	$("div.imageRating ul.rating_" + imageID + " li").each(
		function()
		{
			if ($(this).prevAll().size() < stars)
			{
				$(this).removeClass("off").addClass("on");
			}
			else
			{
				$(this).removeClass("on").addClass("off");
			}
		}
	);
}
