// plugin definition
$.fn.rater = function(options) {
    var opts = $.extend({}, $.fn.rater.defaults, options);
	return this.each(function() {
        var $this = $(this);
		var $id = $this.attr('id');
		var $on = $this.find('#On' + $id);
        var $off = $this.find('#Off' + $id);
        opts.size = $on.height();
        opts.rating = $on.width() / opts.size;
		
		$off.mousemove(function(e) {
            var left = e.clientX - $off.offset().left;
            var width = $off.width() - ($off.width() - left);
            width = Math.ceil(width / (opts.size / opts.step)) * opts.size / opts.step;
            $on.width(width);
            var r = Math.round($on.width() / $off.width() * (opts.ratings.length * opts.step)) / opts.step;
            $this.attr('title', opts.ratings[r - 1] == undefined ? r : opts.ratings[r - 1]);
        }).hover(function(e) { $on.addClass('ui-rater-starsHover'); }, function(e) {
            $on.removeClass('ui-rater-starsHover'); $on.width(opts.rating * opts.size);
        }).click(function(e) {
            var r = Math.round($on.width() / $off.width() * (opts.ratings.length * opts.step)) / opts.step;
            $.fn.rater.rate($this, $id, r, opts);
        }).css('cursor', 'pointer'); $on.css('cursor', 'pointer');
    });
};

$.fn.rater.defaults = {
    ratings: ['not that good', 'average', 'good', 'very good', 'masterpiece'],
    step: 1
};

$.fn.rater.rate = function($this, id, rating, opts) {
    var $on = $this.find('#On' + id);
    var $off = $this.find('#Off' + id);
    $off.fadeTo(600, 0.4, function() {
        $.get("/saveRate.php",
				{ id: id, rating: rating },
				function(msg){
					//alert(msg);
					t = msg.split(';;');
					opts.rating = parseFloat(t[1]);
                    $off.unbind('click').unbind('mousemove').unbind('mouseenter').unbind('mouseleave');
                    $off.css('cursor', 'default'); $on.css('cursor', 'default');
                    $off.fadeTo(600, 0.1, function() {
                        $on.removeClass('ui-rater-starsHover').width(opts.rating * opts.size);
                        // if desired enable lines below to see rating count as well, but create div with class ui-rater-rateCount before
						//var $count = $this.find('.ui-rater-rateCount');
                        //$count.text(parseInt(t[0]));
                        //$this.find('.ui-rater-rateCount').html(t[0]+' ratings');
                        $this.find('.ui-rater-rateCount').html('<span class="orange">You rated ' + t[1] + '</span>');
                        //$this.find('.ui-rater-rating').html('<b>Avg. '+parseInt(t[2]).toFixed(1)+'</b>');
                        $this.find('.ui-rater-rating').html('<b>Avg. ' + t[2] + '</b>');
                        $off.fadeTo(500, 1);
                        $this.attr('title', 'your rating: ' + t[1]);
						$on.attr('class', 'ui-rater-starsRated');
                    });
					document.location.href = '/songs/' + t[3];
                }
			);
    });
};

