/*
	jPoll jQuery plugin version 1.0
	
	Copyright (c) 2009 Dan Wellman
  
	Dual licensed under the MIT and GPL licenses:
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html
	
*/

(function(jQuery) {
	
	//define jPoll object with some default properties
	jQuery.jPoll = {
		defaults: {
			ajaxOpts: {
				url: "js/ajax/poll.php"
			},
			groupName: "choices",
			groupIDs: ["Dale Earnhardt Jr.", "Danica Patrick"],
			groupIDsUnique: ["1","2"],
			pollHeading: "Neither Danica Patrick nor Dale Earnhardt Jr. has won this season. Which will get back to Victory Lane first?",
			rowClass: "row",
			errors: true
		}
	};
  
	//extend jquery with the plugin
	jQuery.fn.extend({
		jPoll:function(config) {
																
			//use defaults or properties supplied by user
			config = jQuery.extend({}, jQuery.jPoll.defaults, config);
			
			//init widget
			jQuery("<h2>").text(config.pollHeading).appendTo(jQuery(this));
			jQuery("<form>").attr({
				id: "pollForm",
				action: config.ajaxOpts.url
		  }).appendTo(jQuery(this));
			jQuery('<input type="hidden" id="poll_id" name="poll_id" value="'+config.ajaxOpts.id+'">').appendTo(jQuery(this).find("form"));
			for(var x = 0; x < config.groupIDs.length; x++) {
				jQuery("<div>").addClass(config.rowClass).appendTo(jQuery(this).find("form"));
				jQuery("<input type='radio' name='" + config.groupName + "' id='" + config.groupIDsUnique[x] + "'>").addClass("choice").appendTo(jQuery(this).find("form").children(":last")).click(function() {
					(jQuery(".error").length != 0) ? jQuery(".error").slideUp("slow") : null ;
				});
				jQuery("<label>").text(config.groupIDs[x]).attr("for", config.groupIDs[x]).appendTo(jQuery(this).find("form").children(":last"));
			}
			jQuery("<div>").attr("id", "buttonRow").addClass(config.rowClass).appendTo(jQuery(this).find("form"));
			jQuery("<button type='submit'>").text("Vote!").appendTo("#buttonRow").click(function(e) {
				e.preventDefault();
				//poll id
				var current_poll;
				(jQuery('#poll_id').val()) ? current_poll = jQuery('#poll_id').val() : null ;
				
				//record which radio was selected
				var selected;
				jQuery(".choice").each(function() {
					(jQuery(this).attr("checked") == true) ? selected = jQuery(this).attr("id") : null ;
				});
				
				//print message if no radio selected and errors enabled
				if (config.errors == true) {
					(selected == null && jQuery(".error").length == 0) ? jQuery("<p>").addClass("error").text("Please make a selection!").css({display:"none"}).insertAfter("#pollForm").slideDown("slow") : null ;
				}
				
				
				//add additional request options
				var addOpts = {
					type: "post",
					data: "&poll="+current_poll+"&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
						jQuery("div#poll_container").find("h2").text("Results, out of " + total + " votes:");
										
						//remove form
						jQuery("form#pollForm").slideUp("slow");
						
						//create results container
						jQuery("<div>").attr("id", "poll_results").css({ display:"none" }).insertAfter("#pollForm");
										
						//create results
						for (var x = 0; x < data.length; x++) {
							
							//create row elment
							jQuery("<div>").addClass("row").attr("id", "row" + x).appendTo("#poll_results");
							
							//create label and result
							jQuery("<label>").text(data[x].choice).appendTo("#row" + x);
							jQuery("<div>").attr("title", Math.round(data[x].votes / total * 100) + "%").addClass("poll_result").css({ display:"none" }).text(Math.round(data[x].votes / total * 100) + "%").appendTo("#row" + x);
						}
						
						//show results container
						jQuery("#poll_results").slideDown("slow", function() {
						
							//animate each result
							jQuery(".poll_result").each(function(i) {
								jQuery(this).animate({ width: Math.round(data[i].votes / total * 100) }, "slow");
							});	
							
							//create and show thanks message
							jQuery("<p>").attr("id", "thanks").text("Thanks for voting!").css({ display:"none" }).insertAfter("#poll_results").fadeIn("slow");		
						});							
					}
				};
				//merge ajaxOpts widget properties and additional options objects
				ajaxOpts = jQuery.extend({}, addOpts, config.ajaxOpts);
				
				//make request if radio selected
				return (selected == null) ? false : jQuery.ajax(ajaxOpts) ;
			});
			
			//return the jquery object for chaining
			return this;
		}
  });
})(jQuery);

