$(document).ready(function(){
	starRating.create('.stars');
});

var ajaxData = null;

var starRating = {
	create: function(selector){
		$(selector).each(function(){
			var $list = $('<div></div>');
			$(this)
				.find('input:radio')
				.each(function(i){
					var rating = $(this).parent().text();
					var $item = $('<a href="#"></a>')
						.attr('title', rating)
						.addClass(i % 2 == 1 ? 'rating-right' : '')
						.text(rating);
					
					starRating.addHandlers($item);
					$list.append($item);
			
					if ($(this).is(':checked')) {
						$item.prevAll().andSelf().addClass('rating');
					};
				});
			// Hide the original radio buttons
			$(this).append($list).find('label').hide();
		});
	},	
	addHandlers: function(item){
		$(item).click(function(e){
							   
			// Handle the click
			var $star = $(this);
			var $allLinks = $(this).parent();
			var $itemID = $allLinks.parent().attr('id');
			var $voteStatus = null;
			
			$itemID = $itemID.split("-");
			
			$starVal = $star.attr('title');
			$starVal = $starVal.slice(0, -6);
			set_rating('index.php', 'sr', 'business', $itemID[2], $starVal);
			
			if (ajaxData != 2 || ajaxData != 0) {
				
				// Set the radio button value
				$allLinks
				  .parent()
				  .find('input:radio[value=' + $star.text() + ']')
				  .attr('checked', true);
				  
				// Set the ratings
				$allLinks.children().removeClass('rating');
				$star.prevAll().andSelf().addClass('rating');
			
			}
						
			// prevent default link click
			e.preventDefault();
		})
		.hover(function(){
			$(this).prevAll().andSelf().addClass('rating-over');
		}, function(){
			$(this).siblings().andSelf().removeClass('rating-over');
		});
	}
};

function set_rating(target, call, method, id, rating) {
	$.ajax({
		url: '/'+target,
		type: "GET",
		data: ({
			call: call,
			method: method,
			i: id,
			rating: rating
		}),
		async: false,
		success: function(data) {
			if (data == 0) {
			} else if (data == 1) {
				$(this).modal({
					width: 415,
					height: 520,
					src: '/modal_boxes/submit_a_review.php?bizid=' + id + '&rating=' + rating
				}).open();
			} else if (data == 2) { 
				$(this).modal({
					width: 375,
					height: 165,
					src: '/modal_boxes/please_login.php'
				}).open();
			};
			ajaxData = data;
		}
	});
};

