(function($) {
	
	//define jPoll object with some default properties
	$.jPoll = {
		defaults: {
			ajaxOpts: {
				url: "data/vote.php"
			},
			groupName: "choices",
			groupIDs: ["LinkedIn", "Twitter", "Online Story", "Print Publication", "Avnet.com", "Advertising Ad", "Other"],
			pollHeading: "Where did you hear about Avnet OnDemand?",
			rowClass: "row",
            formID:  "pollForm",
			errors: true ,
            resultMultiplier: 100
		}
	};
  
	//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: config.formID,
				action: config.ajaxOpts.url,
				method: config.ajaxOpts.type
		  }).appendTo($(this));
    
            $('<input type="hidden" value="' + config.pollID + '" id="poll_id">').appendTo($(this).find("form"));  

			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]).attr("class", 'pre_vote').appendTo($(this).find("form").children(":last"));
			}
			$("<div>").attr("id", "buttonRow_" + config.formID).addClass(config.rowClass).appendTo($(this).find("form"));
			$("<button type='submit'>").text("Vote!").appendTo("#buttonRow_" + config.formID).click(function(e) {
				e.preventDefault();
				
				//record which radio was selected
				var selected;
				$(".choice").each(function() {
					($(this).attr("checked") == true) ? selected = $(this).attr("id") : null ;
				});
                
                var poll_id = $("#poll_id").val();

				//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"}).insertBefore("#pollForm").slideDown("fast") : null ;
				}
				
				//add additional request options
				var addOpts = {
					type: "post",
					data: "&choice=" + selected + "&poll_id=" + poll_id,
					dataType:"json",
					success: function(data) {
		
						//add all votes to get total
						var total = 0;
						var maxvotes = 0;
						for (var x = 0; x < data.length; x++) {
							total += parseInt(data[x].votes);
							if (maxvotes<parseInt(data[x].votes)) maxvotes = parseInt(data[x].votes);
						}
						//change h2
                        $("div#pollContainer").find("h2").text("Results, out of " + total + " votes:");
						$("div#pollContent").find("h2").text("Results, out of " + total + " votes:");
										
						//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 * config.resultMultiplier) + "%").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 / maxvotes * config.resultMultiplier) }, "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;
		},
		jPollResultsToggle:function (){
			if ($(this).hasClass('expand')){
				$(this).removeClass('expand').addClass('collapse');
				$(this).next('div').find('.result-bar').hide();
				$(this).next('div').slideDown("slow", function() {
					$(this).find('.result-bar').each(function (){
						var tempWidth = $(this).width();
						$(this).width(0).show();
						$(this).animate({ width: tempWidth }, "slow");
					});
				});
			} else {
				$(this).removeClass('collapse').addClass('expand');
				$(this).next('div').slideUp("slow");
			}
		}
  });
})(jQuery);
