/*
	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

default:			
groupIDs: ["choice0", "choice1", "choice2", "choice3", "choice4"],						
groupIDs: ["Dasher", "Dancer", "Prancer", "Vixen", "Comet"],
groupIDs: ["Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen", "Rudolph"],

TO CHANGE POLL:
	- change "groupIDs" below to the desired list
	- change the "pollHeading" below to the desired question
	- (optional) zero out old data http://northpoletimes.com/poll/tool.php
	NOTE: zero'ing data is only necessary if poll choices are the same as previous ones
		aka a Yes/No poll with a new question...

*/
/* NOTE: url: "http://www.northpoletimes.com/poll/jPoll/poll.php" will not work when called from
	northpoletimes.com (no www.) due to cross domain restrictions.  The URL parameter *must* remain relative. 
	The correct url is:
		url: "/poll/jPoll/poll.php"
	(jr 20091212)
*/

(function($) {
	
	//define jPoll object with some default properties
	$.jPoll = {
		defaults: {
			ajaxOpts: {
				url: "/poll_ReindeerGames/jPoll/poll.php"
			},
			groupName: "choices",
			groupIDs: ["Europe", "Asia", "South America", "United States", "North Pole"],
			pollHeading: "If you could go anywhere you want, where would you go?",
			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,
				method: config.ajaxOpts.type
		  }).appendTo($(this));
			
			var query_string = "";
			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 ;
				});
				$("<input type='hidden' name='groupIDs[" + x + "]' id='groupIDs[" + x + "]' value='" + config.groupIDs[x] + "'>").appendTo($(this).find("form").children(":last"));
				$("<label>").text(config.groupIDs[x]).attr("for", config.groupIDs[x]).appendTo($(this).find("form").children(":last"));
				query_string += "&groupIDs[]=" + config.groupIDs[x];
			}
			$("<div>").attr("id", "buttonRow").addClass(config.rowClass).appendTo($(this).find("form"));
			$("<button type='submit'>").text("Vote!").appendTo("#buttonRow").click(function(e) {
				e.preventDefault();
				
				//record which radio was selected
				var selected;
				$(".choice").each(function() {
					($(this).attr("checked") == true) ? 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("Please make a selection!").css({display:"none"}).insertAfter("#pollForm").slideDown("slow") : null ;
					(selected == null && $(".error").length == 0) ? $("<p>").addClass("error").text("Please make a selection!").css({display:"none"}).insertAfter("#pollForm").slideDown("slow") : $("<p>").addClass("debug").text("You voted for: " + selected).css({display:"none"}).insertAfter("#pollForm").slideDown("slow") ;
				
				}
									
				var addOpts = {
					type: "post",
					data: query_string + "&choice=" + selected,
					dataType:"json",
					success: function(data) {
						
						var debug = "";  //debug var to output returned data
						//add all votes to get total
						var total = 0;
							for (var x = 0; x < data.length; x++) {
							total += parseInt(data[x].votes);
							debug += "data length = " + data.length + "\n" + data[x].choice + ": " + data[x].votes + ",\n";
							
						}
						//change h2
						//$("div#pollContainer").find("h2").text("Results, out of " + total + " votes:");
						//$("div#pollContainer").find("h2").text(debug + "\nasdf");
						$("div#pollContainer").find("h2").text("Poll Results:");
						
						//remove form
						$("form#pollForm").slideUp("slow");
						
						//create results container
						$("<div>").attr("id", "results").css({ display:"none" }).insertAfter("#pollForm");
										
						//create results
						for (var x = 0; x < data.length; x++) {
							
							//create row elment
							$("<div>").addClass("row").attr("id", "row" + x).appendTo("#results");
							
							//create label and result
							$("<label>").text(config.groupIDs[x]).appendTo("#row" + x);
							$("<div>").attr("title", Math.round(data[x].votes / total * 100) + "%").addClass("result").css({ display:"none" }).appendTo("#row" + x);
						}
						
						//show results container
						$("#results").slideDown("slow", function() {
						
							//animate each result
							$(".result").each(function(i) {
								$(this).animate({ width: Math.round(data[i].votes / total * 100) }, "slow");
							});	
							
							//create and show thanks message
							$("<p>").attr("id", "thanks").text("Thanks for voting!").css({ display:"none" }).insertAfter("#results").fadeIn("slow");		
						});							
					}
				};
				//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);
