﻿$(function(){
	$('div.star_rating_sleeve').each(function(){starRatingInit.call(this)});
});

function starRatingInit() {
	var currentRating = $('select',this).attr('value');
	var thisId = $('select',this).attr('id');
	$('select,input',this).remove();
	$('<input type="hidden" id="'+thisId+'" value="" /><ul><li><span>1 stars of 5</span></li><li><span>2 stars of 5</span></li><li><span>3 stars of 5</span></li><li><span>4 stars of 5</span></li><li><span>5 stars of 5</span></li></ul><p class="current_rating"></p>').appendTo(this);
	$(this).hover(ratingOver,ratingOut);
	$('li',this).hover(starOver,starOut).click(starSelect).slice(0,currentRating).addClass('on');
}

function ratingOver() {
	$('li',this).removeClass('on');
}
function ratingOut() {
	var currentRating = $('input[type="hidden"]',this).attr('value') || 0;
	$('li',this).slice(0,currentRating).addClass('on');
	$('p.current_rating',this).text(currentRating ? currentRating+' out of 5 stars' : '');
}
function starOver() {
	var currentRating = $(this.parentNode).children().index(this)+1;
	$(this).prevAll('li').andSelf().addClass('over').parents('div.star_rating_sleeve')
		.children('p.current_rating').text(currentRating+' out of 5 stars');
}
function starOut() {
	var currentRating = $('>li.on',this.parentNode).length;
	$(this.parentNode).children('li').removeClass('over').parents('div.star_rating_sleeve')
		.children('p.current_rating').text(currentRating ? currentRating+' out of 5 stars' : '');
}
function starSelect() {
	var currentRating = $(this.parentNode).children().index(this)+1;
	$('>li',this.parentNode).removeClass('over').parents('div.star_rating_sleeve').children('input[type="hidden"]').attr('value',currentRating).end()
		.children('p.current_rating').text(currentRating+' out of 5 stars');
	$(this).siblings('li').removeClass('on').end().prevAll('li').andSelf().addClass('on');
	//Ajaxy call for star rating.

	       controlName = "rateAStoryControler"; 
	
	       handlerData =  getHandlerData(controlName);
           handlerName =    getHandlerName(controlName);
           var handlerDataArray = getHandlerDataArray(controlName);          
           
           handlerDataArray = updateArrayValue(handlerDataArray, "RATING",currentRating);
           processedHandlerData = writeoutArray(handlerDataArray);
           invokeActionProvider(starSelectCallback, processedHandlerData,  handlerName);


}

function starSelectCallback(obj)
{
    //TODO: Write a logic to notify the user that the story has been rated.
}