(function($) {
	
	//define jPoll object with some default properties
	$.jPoll = {
		defaults: {
			ajaxOpts: {
				url: "/scripts/poll"
			},
			groupName: "choices",
			groupIDs: ["choice0", "choice1", "choice2", "choice3", "choice4"],
			pollHeading: "Please choose your favourite:",
			pollId: 1,
			rowClass: "row",
			errors: true
		}
	};
  
	//extend jquery with the plugin
	$.fn.extend({
		jPoll:function(config) {
																
			//use defaults or properties supplied by user
			config = $.extend({}, $.jPoll.defaults, config);
			//init widget
			$("<h2>").text(config.pollHeading).appendTo($(this));
			$("<form>").attr({
				id: "pollForm",
				action: config.ajaxOpts.url
		  }).appendTo($(this));
			for(var x = 0; x < config.groupIDs.length; x++) {
				$("<div>").addClass(config.rowClass).appendTo($(this).find("form"));
				$("<input type='radio' name='" + config.groupName + "' id='" + config.groupIDs[x] + "'>").addClass("choice").appendTo($(this).find("form").children(":last")).click(function() {
					($(".error").length != 0) ? $(".error").slideUp("slow") : null ;
				});
				$("<label>").text(config.groupIDs[x]).attr("for", config.groupIDs[x]).appendTo($(this).find("form").children(":last"));
			}
			$("<div>").attr("id", "buttonRow").addClass(config.rowClass).appendTo($(this).find("form"));
			$("<button type='submit'>").text("Votez!").addClass("votebutton").appendTo("#buttonRow").click(function(e) {
				e.preventDefault();
				
				//record which radio was selected
				var selected;
				$(".choice").each(function() {
					($(this).attr("checked") == true || $(this).attr("checked") == "checked") ? selected = $(this).attr("id") : null ;
				});
				
				//print message if no radio selected and errors enabled
				if (config.errors == true) {
					(selected == null && $(".error").length == 0) ? $("<p>").addClass("error").text("Faites un choix.").css({display:"none"}).insertAfter("#pollForm").slideDown("slow") : null ;
				}
//				alert("Merci d'avoir pris le temps de voter.");
				//add additional request options
				var addOpts = {
					type: "post",
					data: "&poll_id=" + config.pollId + "&choice=" + selected,
					dataType:"json",
					success: function(data) {
						//add all votes to get total
						var total = 0;
						for (var x = 0; x < data.length; x++) {
						 total += parseInt(data[x].votes);
						}
						//change h2
						$("div#pollContainer").find("h2").text("Resultats, sur " + total + " votes:");
										
						//remove form
						$("form#pollForm").slideUp("slow");
						
						//create results container
						$("<div>").attr("id", "resultats").css({ display:"none" }).insertAfter("#pollForm");
										
						//create results
						for (var x = 0; x < config.groupIDs.length; x++) {
							$("<div>").addClass("row").attr("id", "row" + x).appendTo("#resultats");
							$("<label>").appendTo("#row" + x).text(config.groupIDs[x]);
							$("<div>").attr({title: Math.round(data[x].votes / total * 100) + "%", id: 'rowcount' + x}).addClass("resultats").css({ display:"none" }).appendTo("#row" + x);
						}
						
						//show results container
						$("#resultats").slideDown("slow", function() {
						
							//animate each result
//							$(".resultats").each(function(i) {
	                                                for (var i = 0; i < config.groupIDs.length; i++) {
								var num = Math.round(data[i].votes / total * 100);
								//$(this).css('width' ,num);
								$("#rowcount" + i).css('display' ,'block');
//								$(this).html(config.groupIDs[i]);
								$("#rowcount" + i).animate({ width: num }, "slow");
							}
//							});	
							
							//create and show thanks message
							$("<p>").attr("id", "thanks").text("Merci pour le vote!").css({ display:"none" }).insertAfter("#resultats").fadeIn("slow");		
						});							
					},
					error: function (request, status, error) {
					        alert("ERREUR: " + request.responseText);
					}
				};
				//merge ajaxOpts widget properties and additional options objects
				ajaxOpts = $.extend({}, addOpts, config.ajaxOpts);
				
				//make request if radio selected
				return (selected == null) ? false : $.ajax(ajaxOpts);
			});
			
			//return the jquery object for chaining
			return this;
		}
  });
})(jQuery);

