/*
	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($) {
	
	//define jPoll object with some default properties
	$.jPoll = {
		defaults: {
			ajaxOpts: {
				url: "/maps/poll.php"
			},
			pollid: 1,
			groupName: "choices",
			opts: ["opcion 1","opcion 2", "opcion 3", "opcion 4", "opcion 5"],
			pollHeading: "Esta es la pregunta default que podria tener 2 lineas:",
			rowClass: "pollrow",
			errors: true,
			title: "Take our Quiz",
			msgsel: "Please make a selection!",
			msgthanks: "Thanks for voting!",
			msg1 : "Results out of ",
			msg2 : " votes"
		}
	};
  
	//extend jquery with the plugin
	$.fn.extend({
		VResults: function (config) {
			config = $.extend({}, $.jPoll.defaults, config);
			var addOpts = {
				type: "post",
				data: "&pollid=" + config.pollid,
				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#polldiv").find("h2").text(config.msg1 + total + config.msg2);
					//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.opts[x]).appendTo("#row" + x);
						$("<div>").attr("title", Math.round(data[x].votes / total * 100) + "%").addClass("result").css({ display:"none" }).appendTo("#row" + x);
						$("<div>").addClass("percent").text(Math.round(data[x].votes / total * 100) + "%").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/2) }, "slow");
						});	
					});
				}
			};
			ajaxOpts = $.extend({}, addOpts, config.ajaxOpts);
			return $.ajax(ajaxOpts);
		},
		jPoll:function(config) {
																
			//use defaults or properties supplied by user
			config = $.extend({}, $.jPoll.defaults, config);
			
			//init widget
			//$("<div class='pollheader'>").html("<h2>"+config.title+"</h2>").appendTo($(this));
			$("<div class='pollheader'>").html(config.pollHeading).appendTo($(this));
			$("<form>").attr({
				id: "pollForm",
				action: '', //config.ajaxOpts.url,
				method: config.ajaxOpts.type
		    }).appendTo($(this));
			if($.cookie("NMD_POLL"+config.pollid)!=undefined) {
				$(this).VResults(config);
			} else {
			//$("<input type='hidden' name='pollid' value='"+config.pollid+"'>").prependTo($(this).find("form"));
			for(var x = 0; x < config.opts.length-1; x++) {
				$("<div>").addClass(config.rowClass).appendTo($(this).find("form"));
				$("<input type='radio' value='ch" + x + "' name='" + config.groupName + "' id='ch" + x + "'>").addClass("choice styled").appendTo($(this).find("form").children(":last")).click(function() {
					($(".error").length != 0) ? $(".error").slideUp("slow") : null ;
				});
				$("<label>").text(config.opts[x]).attr("for", "ch"+x).appendTo($(this).find("form").children(":last"));
			}
			$("<div>").attr("id", "buttonRow").addClass(config.rowClass).appendTo($(this).find("form"));
			$("<button type='submit'>").text("Votar!").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(config.msgsel).css({display:"none"}).prependTo("#polldiv").slideDown("slow") : null ;
				}
				//add additional request options
				var addOpts = {
					type: "post",
					data: "&pollid=" + 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#polldiv").find("h2").text(config.msg1 + total + config.msg2);
						//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.opts[x]).appendTo("#row" + x);
							$("<div>").attr("title", Math.round(data[x].votes / total * 100) + "%").addClass("result").css({ display:"none" }).appendTo("#row" + x);
							$("<div>").addClass("percent").text(Math.round(data[x].votes / total * 100) + "%").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/2) }, "slow");
							});	
							//create and show thanks message
							$("<p>").attr("id", "thanks").text(config.msgthanks).css({ display:"none" }).insertAfter("#results").fadeIn("slow");		
						});

		                var date = new Date();
		                date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
		                $.cookie("NMD_POLL"+config.pollid, '1', { path: '/', expires: date });

					}
				};
				//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);
