/*



OPTIONS ------------------------------

- value			=	media dei voti
- votes 		= 	numero di voti
- editable		=	booleana che definisce se l'utente può votare

*/

(function($)
{
	$.fn.extend(
	{
		rating : function (value, votes, editable)
		{
            // DEFINE VARIABLES /////////////////////
            var o = {
                    value		:	0,
                    votes		:	0,
                    editable	:	false
            };

            if (value) o.value = value;
            if (votes) o.votes = votes;
            if (editable) o.editable = editable;

            // STORE VARIABLES ////////////////////////

            $(this).data( 'data' , o );
            //console.log("1:",o,$(this).data( 'data' ));
            var tpl = '<ul class="rating"><li class="one"><a title="1">1</a></li><li class="two"><a title="2">2</a></li><li class="three"><a title="3">3</a></li><li class="four"><a title="4">4</a></li><li class="five"><a title="5">5</a></li></ul>';
            $(this).html(tpl);

            $(this).setValue(o.value, o.votes);

            // ACTION //////////////////////////

            if(!editable) return false;

            var A = $(this).find('a');

            A.css('cursor', 'pointer');

            A.hover(
                    function(){ $(this).closest('ul').addClass( "stars-hover-"+$(this).html() ); },
                    
                    function(){ $(this).closest('ul').removeClass( "stars-hover-"+$(this).html() ); });
			
		    A.click(function(e){
				var myvote = parseInt($(e.target).html());
				//console.log($(e.target).html(), myvote);
				if( myvote > 0 ) {
					var parent = $(e.currentTarget).closest('ul').parent();
					
					var data = parent.data('data');
					var value = data.value;
					var votes = data.votes;
		
					var newvotes = votes + 1;
					var newvalue = ( value * votes + myvote ) / newvotes;
					
					parent.setValue(newvalue, newvotes);
				}
			});
		},
		setValue : function (_value, _votes)
		{
			
			/*var o = $(this).data( 'data' );
			console.log("2:",o,$(this).data( 'data' ));
			o.value = value;
            o.votes = votes;
				
			$(this).data( 'data' , o );
			*/
			var o = {
                    value		:	_value,
                    votes		:	_votes
            };
			var roundedvalue = Math.round(o.value);
			
			var starClass = "stars-"+roundedvalue;
			
			$(this).find(".rating").removeClass().addClass("rating "+starClass);
			// Stelle disabilitate
			$(this).find(' .rating li').addClass("ui-state-hightlight ui-icon ui-icon-star");
			//Stelle attive
			$(this).find(' .rating li:lt('+ roundedvalue +')').removeClass().addClass("ui-state-active ui-icon ui-icon-star");
			
		}
	});
})(jQuery);
