$(document).ready(function(){
	if ($('div.rating').size() > 0)
	{
		/**
		 * Apply rating handlers when applicable
		 */
		$('div.rating')
			.show()
			.find('input.custom-small-star, input.custom-large-star').rating({
				focus: function(value, link){ 
					var tip = $(this)
								.siblings()
								.filter('span')
								.not('.star-rating-control');
					
					var tipHtml = $.makeArray($('cufontext', tip).text());
						tipHtml = tipHtml.join(' ');
								
					tip[0].data = tip[0].data || tipHtml;
					tip.html(link.title);
					
					Cufon.replace(tip);
				}, 
				blur: function(value, link){ 
					var tip = $(this)
								.siblings()
								.filter('span')
								.not('.star-rating-control');
					
					$(tip).html(tip[0].data); 
					
					Cufon.replace(tip);
				},
				callback: function(value, link){
					var tip = $(this)
								.siblings()
								.filter('span')
								.not('.star-rating-control')
					,	obj = $(this).parent('div.rating');
					
					tip[0].data = tip.html();
					tip.html(link.title);
					
		    		if ($(obj).attr('rel') !== '')
		    		{
						/**
						 * Small or large variant?
						 */
						switch(true)
						{
							case $(obj).hasClass('custom-small-star'):
								var rateObjSize = 'small';
								break;
							case $(obj).hasClass('custom-large-star'):
								var rateObjSize = 'large';
								break;
							default:
								var rateObjSize = null;
								break;
						}
		    			
		    			var ajaxOptions = $(obj).attr('rel').split(':', 2);
		    				ajaxOptions = {'rateTargetId': 			ajaxOptions[0], 
		    							   'rateTargetType': 		ajaxOptions[1], 
		    							   'rateValue': 			value,
		    							   'rateObjectSize':		rateObjSize,
		    							   'rateObjectClasses':		$(obj).attr('class')
		    				};
		    							   		   
						$.ajax({
							type: 		"POST",
   							url: 		"/post/rating",
   							data: 		ajaxOptions,
   							cache: 		false,
   							async: 		true,
   							dataType: 	'html',
   							error:		function(XMLHttpRequest, textStatus, errorThrown){
   								alert(XMLHttpRequest.responseText);
   							},
   							success: 	function(html){
     							$(obj)
     								.replaceWith($(html));
     							
     							if($('div#ratingVoted' + ajaxOptions.rateTargetId).size() == 1)
     							{
     								$('div#ratingVoted' + ajaxOptions.rateTargetId )
     									.find('input')
     									.rating()
     									.hide();
     							
     								Cufon.replace('div#ratingVoted' + ajaxOptions.rateTargetId + ' span.star-rating-description');
     											
     								$('div#ratingVoted' + ajaxOptions.rateTargetId)
     									.show();
     							}
   							}
						});
		    		}
		  		}
			});
			
		/**
		 * Remove cancel buttons for rating system 
		 */
		$('div.rating-cancel')
			.remove();
	}	
});
