/**
 * $ jQuery Rating
 * Version 1.0 (2008-08-13)
 *
 * $Id$
 *
 * Copyright (c) 2008 Flink BV - www.flink.nl
 *
 */
$.fn.rating = function(options)
{
	var options = $.extend({}, {
			input: '#rating', // reference to (hidden) input field
			maxScore: 10, // maximum score
			origScore: 0, // default score
			starWidth: 20, // width of star in pixels
			margin: 0, // right margin in pixels of each star
			multiply: 2, // multiply score by this number
			precision: 1, // score precision: divisible by this number
			decimals: 1 // amount of decimals
		}, options);

	$.each(this, function()
	{
		var $input = $(options.input),
			$this = $(this),
			$hover = $('.hover', $this),
			origWidth = $hover.width(),
			origScore = options.origScore,
			width = 0,
			score = 0;

		function calcScore(w)
		{
			if (w<=0) score = 0;
			else score = (w - ((w / (options.starWidth + options.margin)) * options.margin)) / options.starWidth;
			if (options.multiply) score*= options.multiply;
			score-= score % options.precision;
			score+= options.precision;
			if (score>options.maxScore) score = options.maxScore;
			$('.score', $this).text(score.toFixed(options.decimals));
		}

		function calcWidth(s)
		{
			width = (options.starWidth * (s / options.multiply));
			width += Math.floor(s / options.multiply) * options.margin;
			$hover.width(width);
		}

		$('.rating', $this).css('cursor', 'pointer').mousemove(function(e){
			calcScore(e.clientX-$(this).offset().left);
			calcWidth(score);
		}).mousedown(function(e){
			calcScore(e.clientX-$(this).offset().left);
			calcWidth(score);
			$input.val(score);
			$('.rating', $this).unbind('mousemove').unbind('mouseout');
		}).mouseout(function(e){
			var $elm = $(e.relatedTarget ? e.relatedTarget : e.toElement);
			if ($elm.is('.rating') || $elm.parent('.rating').length) return;
			$hover.width(origWidth);
			$('.score', $this).text(origScore.toFixed(options.decimals));
		});
	});
	return this;
};
