$().ready(function(){
	bindRatingEvents();
});

function bindRatingEvents(){

	// Display Stars (Hover)
	$("div.pe-rating div ol li a").mouseover(function () {
		var width = 75;		
		var rating = ($(this).parent("li").index() + 1);
		
		$(this).parent("li").parent("ol").parent("div").attr('class', 'fill ' + peRatingFindClass(rating));	
	});
		
	// Display Stars (Stop Hover)
	$("div.pe-rating div ol li a").bind("mouseleave",function(){
		var width = 75;
		var rating = $(this).parent("li").parent("ol").parent("div").children("input").val();
				
		$(this).parent("li").parent("ol").parent("div").attr('class', 'fill ' + peRatingFindClass(rating));	
	});
		
	// Set Hidden Value (Click on Star)
	$("div.pe-rating div ol li a").click(function () {
		$(this).parent("li").parent("ol").parent("div").children("input").val(($(this).parent("li").index() + 1));
		return false;
	});	
	
}
	
// Generate dyanmic background-position CSS
function peInputRatingCssBackgroundPosition(ratingPercentage,ratingWidth){
	// Five stars = 1; Two Stars = 0.4
	return (Math.round(ratingPercentage * ratingWidth) - ratingWidth) + "px -14px";				
}

// Rating of "4.5" returns class of "fill-45"
function peRatingFindClass(rating){	
	return "fill-" + zeroPad((Math.round(rating * 10)),2);	 	 
}

// Used to create CSS if number of stars or width of rating area should ever change
function peRatingBuildCSSClasses(){
	for(i = 0; i<= 50; i+= 1){	
		var percentage = Math.round(((Math.round(i * 10) / 100) / 5) * 100 ) / 100;
		var stars = (Math.round(i * 10) / 100);
	
		document.write("div.pe-rating div.fill.fill-" + zeroPad(i,2) + "{background-position: " + inputRatingCssBackgroundPosition(percentage,75) + "} /* " + stars + " || " + percentage + " */ <br />");
	}
}

// Leading zeros: 1 -> 01
function zeroPad(num,count){
	var numZeropad = num + '';
	while(numZeropad.length < count) {
		numZeropad = "0" + numZeropad;
	}
	return numZeropad;
}
