var dpbis_tagvotes = (function ($) {
	function vote_(d, s) {
		setVotes(d.postId, d.commentId, d.tagId, d.votes, d.isme);
	}
	
	function number_format(i) {
		if (i > 1000) {
			return Math.floor(i / 1000) + ',' + (i - (Math.floor(i / 1000) * 1000));
		} else {
			return i;
		}
	}
	
	function setVotes(postId, commentId, tagId, votes, isme) {
		var ref = $('#tagvotes_p' + postId + ((commentId) ? ('_c' + commentId) : '') + ' li.tagvotes' + tagId);
		if (!ref) { return false; }
		
		var tag = false;
		var tmp = ref.text().indexOf('(');
		if (tmp > -1) {
			tag = ref.text().substring(0, (tmp - 1));
		} else {
			tag = ref.text();
		}
		
		ref.html(tag + ((votes > 0) ? ('&nbsp;(' + number_format(votes) + ')') : ''));
		
		if (isme) {
			ref.addClass('isme');
		} else {
			ref.removeClass('isme');
		}
	}
	
	var _ = {
		vote: function (postId, commentId, tagId, dir) {
			$.post($('#header').children('a').attr('href') + '/wp-content/plugins/tagvotes/vote.php', {
				'p': postId,
				'c': commentId,
				't': tagId,
				'd': dir,
				'json': null
			}, vote_, 'json');
		},
		
		ulc: function (tagId, o) {
			if (!o) { o = this; }
			
			var ul = $(o).parent('ul').attr('id');
			var commentId = ((ul.indexOf('_c') > -1) ? ul.substring(ul.indexOf('_c') + 2) : 0);
			var postId = ul.substring(ul.indexOf('_p') + 2, ((commentId) ? ul.indexOf('_c') : ul.length));
			var dir = ($(o).hasClass('isme') ? -1 : 1);
			
			_.vote(postId, commentId, tagId, dir);
			
			setVotes(postId, commentId, tagId, (_.getVotes(postId, commentId, tagId) + dir), dir == 1);
			
			return false;
		},
		
		getVotes: function (postId, commentId, tagId) {
			var ref = $('#tagvotes_p' + postId + ((commentId) ? ('_c' + commentId) : '') + ' li.tagvotes' + tagId);
			if (!ref) { return false; }
			
			var tmp = ref.text().indexOf('(');
			if (tmp > -1) {
				return (ref.text().substring((tmp + 1), ref.text().length - 1)).replace(',', '') * 1;
			} else {
				return 0;
			}
		}
	}
	
	return _;
})(jQuery);