(function($) {

	$.fn.voting = function(options) {
		var settings = {
			'html' : '<dl class="voting"><dt class="pro">Pro</dt><dd class="pro">0</dd><dt class="con">Contra</dt><dd class="con">0</dd></dl><p style="clear:both;">Angaben in Prozent. Anzahl der abgegebenen Stimmen: <span class="votes">0</span>.</p>',
			'voteurl' : 'vote.php',
			'votesubject' : '',
			'votesubject_from' : 'id',
			'color_pro' : 'green',
			'color_con' : 'red',
			'bar_multiplier' : 2,
			'label_pro' : '<img src="thumbs_up.gif" alt="Pro" title="Pro" />',
			'label_con' : '<img src="thumbs_down.gif" alt="Contra" title="Contra" />'
		};

		return this
				.each(function() {
					if (options) {
						$.extend(settings, options);
					}
					var $this = $(this);

					var votesubject = settings.votesubject;
					if (votesubject == '') {
						if (settings.votesubject_from == 'id'
								&& $this.attr('id') != '') {
							votesubject = $this.attr('id');
						} else {
							votesubject = window.location.href;
						}
					}
					var voteurl = settings.voteurl + '?id=' + votesubject;

					function renderBargraph() {
						$this.find("dl.voting").horizontalBarGraph({
							animated : false,
							interval : 1 / settings.bar_multiplier,
							colors : [ settings.color_pro, settings.color_con ]
						});
					}
					
					function updateVotes(data) {
						if (data['result']) {
							$this.find('dd.pro').html(data['result']['pro']);
							$this.find('dd.con').html(data['result']['con']);
							$this.find('span.votes').html(data['result']['votes']);
						}
						renderBargraph();
						if (data['status']) {
							if (data['status'] == 'Voting not allowed') {
								alert("Unter der von Ihnen genutzten IP-Adresse wurde bereits eine Stimme abgegeben. Sie können nur 1x abstimmen.");
							} else if (data['status'] == 'Voting error') {
								alert("Bei der Stimmabgabe trat leider ein unbekannter Fehler auf.");
							} else if (data['status'] == 'Vote accepted') {
								alert("Ihre Stimme wurde gezählt.");
							}
						}
						
					}

					$this.html(settings.html);
					renderBargraph();
					$this.find('dt').css('cursor', 'pointer');
					$this.find('dt.pro').html(settings.label_pro).click(function() {
						jQuery.getJSON(voteurl + '&vote=pro', updateVotes);
					});
					$this.find('dt.con').html(settings.label_con).click(function() {
						jQuery.getJSON(voteurl + '&vote=con', updateVotes);
					});
					$.getJSON(voteurl, updateVotes);
					
				});

	};

}(jQuery));

