$(document).ready(function(){ 

//$(".tabItems").pngFix(); 
//$(document).pngFix(); 
//$(".fixPng").pngFix(); 

buildStarRating = function(){
	//also refresh FancyBox
	enableFancyBox();
	
	var starsTitles = {
		1: 'Very poor',
		2: 'Poor',
		3: 'Average',
		4: 'Good',
		5: 'Excellent'
	}
	
	//prepare DOM for plugin
	$(".starsDiv").each(function(){
		var $this = $(this);
		var html = '';
		
		for (i = 1; i <= 5; i++)
		{
			var checked = '';
			
			if (i - 0.5 <= $this.attr('__average')) //need for round
			{
				checked = ' checked="checked" ';
			}
			
			html += $.sprintf('<input type="radio" name="newrate" value="%d" title="%s" %s />', i, starsTitles[i], checked);	
		}
		
		html = $.sprintf('<div __parent="%s" class="stars-wrapper">%s</div>', $this.attr('id'), html);
		
		$this.html(html);
	});

	//call plugin
	$(".stars-wrapper").each(function(){
		var $this = $(this);
		var $parent = $('#' + $this.attr('__parent'))
		
		$this.stars({
			oneVoteOnly: true,
			cancelShow: false,
			showTitles: true,
			disabled: ($parent.attr('__disabled') == 'true' ? true : false),
//			split: 2,
			callback: function(ui, type, value)
			{
				var modelName = $parent.attr('__modelName');
				var modelID = $parent.attr('__modelID');
				
//				$.alertf('Model: %s, Model ID: %s, Rate: %s.', $parent.attr('__modelName'), $parent.attr('__modelID'), value);

		        var result = $.ajax({
		            type: "POST",
		            url: "/ajax/add_rating.php",
		            data:
			            {
			            	'modelName': modelName,
			            	'modelID'  : modelID,
			            	'value'    : value
			            },
		            async: false
		        }).responseText;
		        
		        if (result.toString().indexOf('OK|') == 0)
		        {
					result = result.split('|');
					$('#' + $.sprintf('votes_%s_%d', modelName, modelID)).html(result[1]);
					$('#' + $.sprintf('average_%s_%d', modelName, modelID)).html(result[3]);
					$('#' + $.sprintf('average_caption_%s_%d', modelName, modelID)).html(starsTitles[Math.round(result[3])]);
//					$this.remove();
		        }
		        else
		        {
					alert(result);
		        }
			}
		});
	});
	
	$(".starsDiv").show();
}

buildStarRating();

}); 

