var vote_control_prefix = '#vote_img_';
var vote_control_href_prefix = '#vote_';
var vote = false;

function _doVote(vote_type_id, entity_id, entity_type)
{
	var ajaxOpts = {
		type: "post",
		url: "http://www.skidki.ua/vote_postback.php",
		async: false,
		data: 'vote_type_id=' + vote_type_id + '&entity_id=' + entity_id + '&entity_type=' + entity_type,
		success: function(data) {
			vote = data;
		}
	};
	
	$.ajax(ajaxOpts);
}


function do_vote(element_index) {
	var href = $('#vote_1').attr('href');
	var re = new RegExp("[0-9]+");
	var re_type = new RegExp("[a-z_]+");
	var entity_id = href.match(re);
	var entity_type = href.match(re_type);
	
	_doVote(element_index, entity_id, entity_type);
	
	for (var i = 1; i <= (element_index + 1); i++)
	{
		var element_name = vote_control_prefix + i;
		$(element_name).attr('src', 'http://www.skidki.ua/img/star_full.gif');
		
		var href_element_name =  vote_control_href_prefix + i;
		var inner_content = $(href_element_name).contents();
		$(href_element_name).replaceWith(inner_content);

		$(element_name).unbind();
	}
	for (var i = element_index + 1; i <= 5; i++)
	{
		var element_name = vote_control_prefix + i;
		$(element_name).attr('src', 'http://www.skidki.ua/img/star_empty.gif');
		
		var href_element_name =  vote_control_href_prefix + i;
		var inner_content = $(href_element_name).contents();
		$(href_element_name).replaceWith(inner_content);
		
		$(element_name).unbind();
	}
	
	$('#average_vote').text(vote);
}

function over_star(element_index)
{
	for (var i = 1; i <= element_index; i++)
		$(vote_control_prefix + i).attr('src', 'http://www.skidki.ua/img/star_full.gif');
}

function out_star(element_index)
{
	for (var i = 1; i < 6; i++)
		$(vote_control_prefix + i).attr('src', 'http://www.skidki.ua/img/star_empty.gif');
}

$(document).ready(function()
{
	$(vote_control_prefix + 1).bind("mouseover", function() { over_star(1); });
	$(vote_control_prefix + 2).bind("mouseover", function() { over_star(2); });
	$(vote_control_prefix + 3).bind("mouseover", function() { over_star(3); });
	$(vote_control_prefix + 4).bind("mouseover", function() { over_star(4); });
	$(vote_control_prefix + 5).bind("mouseover", function() { over_star(5); });
	$(vote_control_prefix + 1).bind("mouseout", function() { out_star(1); });
	$(vote_control_prefix + 2).bind("mouseout", function() { out_star(2); });
	$(vote_control_prefix + 3).bind("mouseout", function() { out_star(3); });
	$(vote_control_prefix + 4).bind("mouseout", function() { out_star(4); });
	$(vote_control_prefix + 5).bind("mouseout", function() { out_star(5); });
	
	$(vote_control_prefix + 1).bind("click", function() { do_vote(1); });
	$(vote_control_prefix + 2).bind("click", function() { do_vote(2); });
	$(vote_control_prefix + 3).bind("click", function() { do_vote(3); });
	$(vote_control_prefix + 4).bind("click", function() { do_vote(4); });
	$(vote_control_prefix + 5).bind("click", function() { do_vote(5); });
			
});
