/* Movie rating stars
 * by Johnny <contact@WarcraftMovies.com>
 */

function Rating() {
    this.ratings = [0, 0, 0, 0];
    
    // Show how many points thats about to be selected
    this.show = function(category, points) {
	for (var point=0; point < 5; ++point) {
	    var id = 'rating' + category + '.rate' + (point+1);
	    if (point < points) document.getElementById(id).src = "images/rating-on.gif";
	    else document.getElementById(id).src = "images/rating-off.gif";
	}
    }

    // Show stored amount of selected points
    this.clear = function(category) {
	for (var point=0; point < 5; ++point) {
	    var id = 'rating' + category + '.rate' + (point+1);
	    if (point < this.ratings[(category-1)]) document.getElementById(id).src = "images/rating-on.gif";
	    else document.getElementById(id).src = "images/rating-off.gif";
	}
    }

    // Save amount of selected points
    this.set = function(category, points) {
	if (! commentFocus) {
	    document.getElementById('comment').value = '';
	    commentFocus = true;
	}
	if (this.ratings[(category-1)] == points) // 2nd set = clear point
	    this.ratings[(category-1)] = 0;
	else // Store new point
	    this.ratings[(category-1)] = points;
	this.clear(category);
    }

    // Send rating and/or comment
    this.submit = function() {
	var totalPoints = 0;
	var zeros = 0;
	for (var n=0; n < 4; n++) {
	    point = this.ratings[n];
	    if (point == 0) zeros++;
	    else totalPoints += point;
	}
	if ((totalPoints > 0) && (zeros > 0)) { // Got some ratings with missing fields
	    alert("Please vote on all categories to rate.\nClear your votes to only leave a comment");
	    this.ratings = [0, 0, 0, 0];
	    for (var nr=1; nr <= 4; nr++)
		this.clear(nr);
	} else { // Submit form
	    if (totalPoints > 0) { // Set form fields
		with(document.ratingForm) {
		    rating1.value = this.ratings[0];
		    rating2.value = this.ratings[1];
		    rating3.value = this.ratings[2];
		    rating4.value = this.ratings[3];
		}
	    } 
	    document.ratingForm.submit();
	}
    }
}
// Cache images to reduce delays
(new Image()).src = "images/rating-on.gif";

// Init
var rating = new Rating;

