﻿function Ratings()
{
	var self = this;
	
	this.init = function()
	{
		$("span.userrate").css({cursor:'pointer'});
		$("span.userrate").bind("mouseover", self.Over);
		$("span.userrate").bind("mouseout", self.Out);
		$("span.userrate").bind("click", self.Click);
	}
	
	this.Over = function()
	{
		$(this).bind("mousemove", self.Move);
	}
	
	this.Out = function()
	{
		$(this).unbind("mousemove", self.Move);
	}
	
	this.Move = function(e)
	{
		var pos = e.pageX - $(this).offset().left;
		var heartWidth = 19;
		var rating = Math.floor(pos / 19) + 1;
		$(this).attr("class", "Sprite ratings");
		$(this).addClass("Rating-" + rating);
	}

	this.Click = function () {
	    var _class = String($(this).attr("class"));
	    var matches = _class.match(/Rating-([0-9])/);
	    var rating = Number(matches[1]);
	    var topic = $(this).attr("rel");
	    if (rating > 0) {

	        // Update
	        var ajaxPrefix = (document.domain == "internal.idstudios.net") ? 'http://internal.idstudios.net/randomhouse.com.au/' : "http://" + document.domain + "/";
	        $.ajax({
	            url: ajaxPrefix + 'includes/ajax/rating.aspx?topic=' + topic + '&rating=' + rating,
	            success: function (response) {
	                $("span.Update-Rating").attr("class", "Sprite Update-Rating");
	                $("span.Update-Rating").addClass("Rating-" + response);
	            },
	            error: function (response) {
	                alert("error saving rating");
	            }
	        });

	        // Disable mouse
	        $(this).css({ cursor: 'default' });
	        $(this).unbind("click", self.Click);
	        $(this).unbind("mousemove", self.Move);
	        $(this).unbind("mouseover", self.Over);
	        $(this).unbind("mouseout", self.Out);
	    }
	}
}

$(document).ready(function()
{
	var r = new Ratings();
	r.init();
});
