/*
    Modified by David Kovacs

    Based on:
    
    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: "poll.php"
            },
            pollId: 1,
            choices: [{ id: 0, title: "choice0" }, { id: 1, title: "choice1" }, { id: 2, title: "choice2" }, { id: 3, title: "choice3" }, { id: 4, title: "choice4"}],
            pollHeading: "Please choose your favourite:",
            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
            $("<div>").addClass('question').text(config.pollHeading).appendTo($(this));
            $("<form>").attr({
                id: "pollForm",
                action: config.ajaxOpts.url
            }).appendTo($(this));

            if (config.resultsOnly) {
                $("<div>").attr("id", "results").addClass("pollResults").insertAfter("#pollForm");

                //add all votes to get total
                var total = 0;
                for (var x = 0; x < config.choices.length; x++) {
                    total += parseInt(config.choices[x].votes);
                }

                for (var x = 0; x < config.choices.length; x++) {
                    //create row elment
                    $("<div>").addClass("resultRow").attr("id", "row" + x).appendTo("#results");

                    //create label and result
                    $("<div>").attr("id", "reslabel" + x).addClass('label').text(config.choices[x].title).appendTo("#row" + x);
                    $("<span>").addClass('value').text(Math.round(config.choices[x].votes / total * 100) + "%").appendTo("#reslabel" + x);

                    $("<div>").attr("title", Math.round(config.choices[x].votes / total * 100) + "%").addClass("result").css({ display: "none" }).appendTo("#row" + x);
                }

                //animate each result
                $(".result").each(function(i) {
                    $(this).animate({ width: Math.round(config.choices[i].votes / total * 100) + "%" }, "slow");
                });

            }
            else {
                for (var x = 0; x < config.choices.length; x++) {
                    $("<div>").addClass(config.rowClass).appendTo($(this).find("form"));
                    $("<input type='radio' name='poll_" + config.pollId + "' id='choice_" + config.choices[x].id + "'>").addClass("choice").appendTo($(this).find("form").children(":last")).click(function() {
                        ($(".error").length != 0) ? $(".error").slideUp("slow") : null;
                    });
                    $("<label>").text(config.choices[x].title).attr("for", 'choice_' + config.choices[x].id).appendTo($(this).find("form").children(":last"));
                }
                $("<div>").attr("id", "buttonRow").addClass("buttonRow").appendTo($(this).find("form"));


                $("<input type='image'>").attr("src", config.voteButtonImage).addClass("voteButton").appendTo("#buttonRow").click(function(e) {
                    e.preventDefault();

                    //record which radio was selected
                    var selected = null;
                    $(".choice").each(function() {
                        ($(this).attr("checked") == true) ? selected = $(this).attr("id") : null;
                    });
                    if (selected != null) selected = selected.substring(7, selected.length);

                    //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;
                    }

                    //add additional request options
                    var addOpts = {
                        type: "post",
                        data: 'pollid=' + config.pollId + "&choice=" + selected,
                        dataType: "json",
                        success: function(data, textStatus, xhr) {                            

                            //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("Results, out of " + total + " votes:");

                            //remove form
                            $("#pollForm").slideUp("slow");

                            //create results container
                            $("<div>").attr("id", "results").addClass("pollResults").css({ display: "none" }).insertAfter("#pollForm");

                            //create results
                            for (var x = 0; x < data.length; x++) {

                                //create row elment
                                $("<div>").addClass("resultRow").attr("id", "row" + x).appendTo("#results");

                                //create label and result
                                $("<div>").attr("id", "reslabel" + x).addClass('label').text(config.choices[x].title).appendTo("#row" + x);
                                $("<span>").addClass('value').text(Math.round(data[x].votes / total * 100) + "%").appendTo("#reslabel" + 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");
                            });
                        },
                        error: function(xhr, textStatus, errorThrown) { alert(errorThrown); }
                    }; // end of addOpts

                    //merge ajaxOpts widget properties and additional options objects
                    ajaxOpts = $.extend({}, addOpts, config.ajaxOpts);

                    //make request if radio selected
                    return (selected == null) ? false : $.ajax(ajaxOpts);
                }); // end of votebutton click handler

            } // end of "(if !resultsOnly)"

            //return the jquery object for chaining
            return this;
        }
    });
})(jQuery);


