/**
 * andigg ( http://jquery.andelux.com/andigg )
 * plugin para votar
 * 
 * @version	1.0
 *
 * @author	Javier Pérez <javier.perez@andelux.com>
 * 
 */
(function($){
	$.fn.andigg = function(option){
		// Param plugin
		var param = jQuery.extend({
			returnValue:	false,
			type: 			'vote'	// vote, click
		}, option);
		
		$(this).each(function() {
			// El enlace
			var $this = $(this);
			
			// obtenemos el id de artículo del rel
			var rel = $(this).attr('rel');
			var id = rel.substring(rel.lastIndexOf('-')+1);

			// panel de contador de votos (A)
			var $panel = $('.votes-id-' + id);
			
			$this.mousedown(function(e){
				if (e.button == 1) {
					// middle click
					$(this).click();
					return false;
				}
				return true;
			});
			
			$this.click(function(){
				if (param.type == 'vote') {
					if ($this.hasClass('voted')) return false;
					var $text = $('.text-id-' + id, $panel);
					if ($text.length > 0) {
						$text.html('thanks!').css('color','#666');
					} else {
						$this.html('<span>thanks!</span>').css('color','#666');
					}
					$this.addClass('voted');
				}
				
				// Se produce el voto
				$.post(AND_BASE_URI + 'api/andigg.vote.json', {
					id: id,
					type: param.type
				}, function(d){
					if (!d) return;
					// Respuesta del servicio
					$panel.fadeOut('fast', function(){
						$panel.fadeIn('slow', function(){
							$('a', $panel).html(d.post_votes);
							$('.karma-id-'+id).html(d.post_karma);
							
							// Para los nuevos contenidos
							$('.total-id-' + id, $panel).html(d.post_votes);
							$('.karma-id-' + id, $panel).html(d.post_karma + 'k');
						});
					});
					// Texto de agradecimiento
					//var grate = d.grate ? d.grate : 'thanks!';
					//$('a.androidit[rel=article-'+id+']').html('<span>'+grate+'</span>').css('color','#666').data('voted', true);
				}, 'json');
				
				return param.returnValue;
			});
		});
		
	};
})(jQuery);
