jQuery(document).ready(function() {

	if(jQuery('#sp-post-ratings-page-load-query').length > 0) {
		jQuery.post(
			jQuery('#sp-post-ratings-page-load-query').val(),
			{},
			updateRatingView,
			'json'
		);
	}
	jQuery('.sp-rating-link').click(function(event) {
		event.preventDefault();
		// Fade out the hidden stuff
		jQuery('.sp-post-rating-hide-on-rating').fadeOut('medium', 
			function() { 
				var element = jQuery(this);
				var parent = element.parent();
				var parentContainer = jQuery('<span class="sp-post-rating-fade-out-on-rating"></span>').hide();
				
				// Iterate over each child element, appending it directly to the parent
				element.children().each(
					function() {
						var child = jQuery(this).clone();
						jQuery(this).remove();
						parentContainer.append(child);
					}
				);
				
				// Finally prepend the new container to the parent
				parent.prepend(parentContainer);
				element.remove();
			});
		jQuery('.sp-post-rating-fade-out-on-rating').fadeOut('medium');
		
		//The URL to send our request to
		var theURL = jQuery(this).attr('href');
		
		// Do AJAX stuff here
		jQuery.post(
			theURL,
			{
				'is-post-rating-ajax':'1'
			},
			function (data, status) {
				setTimeout(function() {
					updateRatingView(data, status);
					jQuery('.sp-post-rating-fade-out-on-rating').removeClass('sp-post-rating-fade-out-on-rating').addClass('sp-post-rating-result').addClass('sp-post-rating-fader');
					jQuery('.sp-post-rating-fader').fadeIn('medium').removeClass('sp-post-rating-fader');
				}, 2000);
			},
			'json'
		);
	});
});

function updateRatingView( data, status ) {
	jQuery('.sp-post-rating-thumb-up-percentage').text(data.rate1Percentage);
	jQuery('.sp-post-rating-thumb-up-number').text(data.rate1);
	jQuery('.sp-post-rating-thumb-down-percentage').text(data.rate2Percentage);
	jQuery('.sp-post-rating-thumb-down-number').text(data.rate2);
	jQuery('.sp-post-rating-thumb-total-number').text(data.total);
	jQuery('.sp-post-rating-thumb-score').text(data.score);
}