include('ajax');

// These should be set on the page that is utilizing the rating helper
var current_rating = 0;
var current_feedback = null;
var process_rating_url = null;

// Control the status of the rating stars
function setStars(num)
{
	for (i = 1; i <= 5; i++)
	{
		var star = document.getElementById('rating_star_' + i);
		// We will round up or down based on quarters of a point according to this schedule:
		// 0.01 - 0.24 ~= 0.0
		// 0.25 - 0.74 ~= 0.5
		// 0.75 - 0.99 ~= 1.0
		if (num >= (i - 0.25)) star.className = 'rating_star_full';
		else if (num >= (i - 0.75)) star.className = 'rating_star_half';
		else star.className = 'rating_star_none';
	}
}

// Handle hover events on the rating stars
function ratingHover(element)
{
	var feedback = document.getElementById('rating_feedback');
	// Clear the hovered rating if no element passed
	if (element == undefined)
	{
		setStars(current_rating);
		feedback.innerHTML = current_feedback;
	}
	// If one of the stars is being hovered on, activate it and the ones below it
	else if (element.id.substr(0, 12) == 'rating_star_')
	{
		var hover_rating = parseInt(element.id.substring(element.id.length - 1, element.id.length));
		setStars(hover_rating);
		feedback.innerHTML = rating_messages[hover_rating];
	}
}

// Handle click events on the rating stars
function ratingSave(element)
{
	if (element.id.substr(0, 12) == 'rating_star_' && process_rating_url != undefined)
	{
		ratingDisable();
		var save_rating = parseInt(element.id.substring(element.id.length - 1, element.id.length));
		var req = new Object;
		req.method = 'POST';
		req.url = process_rating_url;
		req.args = 'rating=' + save_rating;
		req.onSuccess = function(response)
		{
			var feedback = document.getElementById('rating_feedback');
			feedback.innerHTML = response;
		}
		ajaxRequest(req);
	}
}

// Disable all further events on the rating stars
function ratingDisable()
{
	for (i = 1; i <= 5; i++)
	{
		var star = document.getElementById('rating_star_' + i);
		star.onclick = null;
		star.onmouseover = null;
		star.onmouseout = null;
	}
}
