/**
 * Vote handler for feed_items
 * 
 * @author Matthias Mullie <matthias@netlash.com>
 */

/**
 * JS_NETLASH Object
 */
if (!JS_NETLASH) { var JS_NETLASH = new Object(); }

/**
 * JS_NETLASH - Rating object
 */
JS_NETLASH.rating =
{
	// init
	init: function()
	{
		$('.rating').bind('click', function(evt)
		{
			// prevent default action (= following the link in href)
			evt.preventDefault();

			// ajax call to cast the vote
			$.ajax(
			{
				url:		'/ajax.php?module=feed&action=rating',
				type:		'post',
				dataType:	'json',
				cache:		false,
				data:		'rating=' + $(this).html() +'&item_id=' + $(this).attr('rel'),

				// success making call
				success:	function(json)
				{
					// update rating view
					$('.rating[rel=' + json.content.itemId + ']').each(function(i)
					{
						$(this).removeClass('rating_even_active').removeClass('rating_uneven_active').removeClass('rating_even_inactive').removeClass('rating_uneven_inactive');
						if (parseInt($(this).html()) <= parseInt(json.content.rating))
						{
							if (i % 2 == 1) $(this).addClass('rating_even_active');
							else $(this).addClass('rating_uneven_active');
						}
						else
						{
							if (i % 2 == 1) $(this).addClass('rating_even_inactive');
							else $(this).addClass('rating_uneven_inactive');
						}
					});
				},

				// error making call - something went horribly wrong!
				error:		function(xhr,err,e)
				{
					// give notice
					alert(err + ' ' + e, 'Critical Error');
				}
			});
		});
	}
}

/**
 * Main Run : Init objects when document is loaded
 */
$(document).ready(function() {
	JS_NETLASH.rating.init();

	// hover animation (previous stars must also be lit)
	$('.rating').hover(
		// mouse over
		function()
		{
			// add class on hovered item
			$(this).addClass('rating_hover');

			// add class on previous items
			$('.rating[rel=' + $(this).attr('rel') + ']').each(function(i)
			{
				if (i % 2 == 1) $(this).addClass('rating_even_hover');
				else $(this).addClass('rating_uneven_hover');

				if ($(this).hasClass('rating_hover'))
				{
					$(this).removeClass('rating_hover');
					return false;
				}
			});
		},

		// mouse out
		function()
		{
			// remove class on hovered item
			$(this).removeClass('rating_even_hover').removeClass('rating_uneven_hover');

			// remove class on previous items
			$('.rating[rel=' + $(this).attr('rel') + ']').each(function(i)
			{
				if (!($(this).hasClass('rating_even_hover') || $(this).hasClass('rating_uneven_hover'))) return false;
				$(this).removeClass('rating_even_hover').removeClass('rating_uneven_hover');
			});
		}
	);
});
