// JavaScript Document

function debug(message)
{
    $("#debug").text(message);
}

var ratingStar =
{
    hovering : false,
    starval  : 1,
    selectval: 1,
    realClass: "star",
    init     : function (limit_res)
    {

	$(this).each(function() {
	    this.starval = new Number (this.className.toString().match(/star_[0-9]+/).toString().match(/[0-9]+/));
	    this.realClass = this.className;
	});
	$(this).hover(
	    function()
	    {
		this.hovering = true;
	    },function()
	    {
		this.hovering = false;
		debug(this.starval);
		var c = $(this).parent().children(".star");
		c.each(function()
		{
		    this.className = this.realClass;
		});
	    }
	).mousemove(function(event)
	    {
		var w = $(this).width();
		var x = event.pageX;
		var dim = $(this).offset();
		var l = dim.left;
		var whole = 1;
		//if (!limit_res && x-l <= w/2) whole = 0; // removed because only dealing with whole stars
		debug("x="+x+"; starval="+this.starval+"; w="+w+"; l="+l);
		var c = $(this).parent().children(".star");
		var v = this.starval;
		c.each(function()
		{
		    //$(this).removeClass("star_half_filled");
		    if (this.starval < v) 
				$(this).addClass("star_filled");
		    else 
				$(this).removeClass("star_filled");
		});
		if (whole) {
		    $(this).removeClass("star_half_filled").addClass("star_filled");
		    this.selectval = this.starval;
		} else {
		    $(this).removeClass("star_filled").addClass("star_half_filled");
		    this.selectval = this.starval - 1;
		}
	    }
	).click(function() {
		var parentElem = $(this).parent();
		/*
		parentElem.empty();
		parentElem.append('<img src="/images/save_ajax.gif">');
		*/
		//parentElem = $(this).parent();
		if(confirm('Are you sure you would like to rate this post?')) {
			$.ajax({
				url: CCM_REL + '/tools/collection_rating_post.php',
				data: {ratingVal: this.selectval, cID: this.id},
				type: 'POST',
				timeout: 5000,
				error: function() {
					alert('Error saving rating'); 
				},
				success: function(res){
					parentElem.empty();
					parentElem.append(res);
				}
			});
		}
		//var url = document.location+"&ajaxtask=rate_stand&rating="+this.selectval;
	    //var c = $(this).parent().parent();
	    //c.load(url,initRatingStars);
		
	});
	
    } 
}

function initRatingStars()
{
    $.extend($('.rating_selector .star'),ratingStar).init(false);
}

$(document).ready(function()
{
    initRatingStars();
});