﻿(function($) {
	$(function(){
		$('div.story_rating_sleeve').each(function(){starRatingInit.call(this)});

	    $('.starRating li a').click(function() {
	        var score = $(this).text();
            var targetroot = Config.get('rooturl');
            var target =  '/AJAX/rating.aspx?storycode=' + Config.get('storycode');
	        $.post(targetroot + target, {
	        rating: score
	        },
	        function(reply) {
	            $('.story_rating .score').text(reply);
	        });
	    });

	});

	function starRatingInit(){
		var currentRating = $('select>[@selected]',this).attr('value');
		var thisId = $('select',this).attr('id');
		$('select,input',this).remove();
		$('<input type="hidden" id="'+thisId+'" value="" /><span class="inline_rating"><ul class="starRating"><li><a href="#" title="1 star out of 5" class="one_star">1</a></li><li><a href="#" title="2 stars out of 5" class="two_stars">2</a></li><li><a href="#" title="3 stars out of 5" class="three_stars">3</a></li><li><a href="#" title="4 stars out of 5" class="four_stars">4</a></li><li><a href="#" title="5 stars out of 5" class="five_stars">5</a></li></ul></span><p class="current_rating meta"></p>').appendTo('.story_rating_sleeve div');
		$('a',this).hover(starOver,starOut).click(starSelect).focus(starOver).blur(starOut).slice(0,currentRating);
	}
	function starOver(){
		var currentRating = $(this.parentNode.parentNode).children().index(this.parentNode)+1;
		$(this).prevAll('li').andSelf().addClass('over').parents('div.story_rating_sleeve div')
			.children('p.current_rating').text(currentRating+' out of 5 stars');
	}
	function starOut(){
		$(this).parent().parent().parent().next().text('');
	}
	function starSelect(){
		var currentRating = $(this.parentNode.parentNode).children().index(this.parentNode)+1;
		return false;
	}
})(jQuery);