/*
 * $Id$
 *
 * Голосование
 */

var models_base = {
	'gallery': '/gallery/vote/',
	'entity' : '/entities/vote/',
	'user'   : '/accounts/user/vote/',
	'comment': '/comments/vote/',
	'entry'  : '/blog/entry/vote/',
	'mfile'  : '/mserver/mfile/vote/',
	'book'   : '/books/vote/',
	'game'   : '/games/vote/',
	'film'   : '/films/vote/'
};

function non() { }

function newvote(div_id, model_slug, user_id, direction){
	// по началу дисейблим все
	$('#' + div_id + ' .up').replaceWith('<a href="javascript:non();" class="up up-disabled"></a>');
	$('#' + div_id + ' .down').replaceWith('<a href="javascript:non();" class="down down-disabled"></a>');

	var url = models_base[model_slug] + user_id + '/' + direction + 'vote/';

	$.getJSON(url, function (jsonResult) {
		var object_rating = jsonResult.score;
		$('em#rating_' + model_slug + '_' + user_id).text(jsonResult.score);

		var class_name = 'neutral';
		if (object_rating < 0) {
			class_name = 'negative';
		} else if (object_rating > 0) {
			class_name = 'positive';
		}
		var rating_wrap = $('#rating_wrap_' + model_slug + '_' + user_id);
		rating_wrap.removeClass("positive neutral negative");
		rating_wrap.addClass(class_name);

		var el_up 	= $('#' + div_id + ' .up');
		var el_down = $('#' + div_id + ' .down');
		var up_enable_str = '<a href="#" onClick="javascript:return newvote(\'' + div_id + '\', \'' + model_slug + '\', \''+user_id+'\',\'up\')" class="up"></a>';
		var down_enable_str = '<a href="#" onClick="javascript:return newvote(\'' + div_id + '\',\'' + model_slug + '\', \''+user_id+'\',\'down\')" class="down"></a>'
		if (jsonResult.superuser_mode == true) {
			el_up.replaceWith(up_enable_str);
			el_down.replaceWith(down_enable_str);
		}

		if (jsonResult.rating_votes != '0' || jsonResult.free_voting) {
			if (jsonResult.vote.is_upvote || (!jsonResult.vote.is_upvote && !jsonResult.vote.is_downvote)) {
				el_down.replaceWith(down_enable_str);
			}
			if (jsonResult.vote.is_downvote || (!jsonResult.vote.is_upvote && !jsonResult.vote.is_downvote)) {
				el_up.replaceWith(up_enable_str);
			}
		}
		
		if (!jsonResult.superuser_mode) {
			try { update_rating_votes(parseInt(jsonResult.rating_votes), jsonResult.free_voting); } catch(e) {};
		}
	});

	return false;
}

$(document).ready(function(){
	$('.action-vote').live('click', vote);
});

function vote(event) {
	event.preventDefault();
	var self = $(this);
	if (self.hasClass('js-voting-disabled'))
		return false;
	var voting = self.parent();
	data = {
		app_label: voting.attr('data-applabel'),
		model: voting.attr('data-model'),
		object_id: voting.attr('data-objectid'),
		direction: self.attr('data-direction')
	}
	$.post('/voting/vote/', data, function(result){
		voting.replaceWith(result);
	});
}
