/*
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"
            },
            groupName: "choices",
            groupIDs: ["choice0", "choice1", "choice2", "choice3", "choice4"],
            pollHeading: "Please choose your favourite:",
            rowClass: "row",
            errors: true,
            readOnly: false,
            maxWidth: 1,
            questionId: 0,
            containerId: "pollContainer"
        }
    };
    //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
            }).appendTo($(this));
            if (config.readOnly == false) {
                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] + "' value='" + 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]).appendTo($(this).find("form").children(":last"));
                }
                $("<div>").attr("id", "buttonRow").addClass(config.rowClass).appendTo($(this).find("form"));
                $("<button type='submit'>").text("Responder!").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;
                        this.checked == true ? selected = this.id : null;
                        //($(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("Selecciona una opcion primero").css({ display: "none" }).insertAfter("#pollForm").slideDown("slow") : null;
                    }

                    //add additional request options
                    var addOpts = {
                        type: "post",
                        contentType: "application/json; charset=utf-8",
                        data: "{'choice': '" + selected + "', 'questionId':'" + config.questionId + "'}", //"&choice=" + selected,
                        dataType: "json",
                        success: function (data) {

                            //add all votes to get total

                            var total = 0;
                            for (var x = 0; x < data.d.length; x++) {
                                total += parseInt(data.d[x].votes);
                            }

                            if (total <= -1000) {//non visible results
                                $("div#"+config.containerId).find("h2").text("");
                                $("form#pollForm").slideUp("slow");
                                $("<div>").attr("id", "results").css({ display: "none" }).insertAfter("#pollForm");
                                $("#results").slideDown("slow", function () {
                                    //create and show thanks message
                                    if (config.readOnly == false) {
                                        if(total==-1000)
                                            $("<p>").attr("id", "thanks").text("Gracias por votar!").css({ display: "none" }).insertAfter("#results").fadeIn("slow");
                                        else if (total==-1001)
                                            $("<p>").attr("id", "thanks").text($('<div/>').html("Ya hab&iacute;as votado en esta encuesta &#161;Gracias!").text()).css({ display: "none" }).insertAfter("#results").fadeIn("slow");
                                    }
                                });
                            }
                            else {
                                //change h2
                                $("div#" + config.containerId).find("h2").text("Resultados, de un total de " + total + " votos:");
                                //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.d.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);
                                    var percent = Math.round(data.d[x].votes / total * 100);
                                    $("<div>").attr("title", percent + "%").addClass("result").css({ display: "none" }).appendTo("#row" + x).html(data.d[x].votes + " (" + percent + "%)"); //.html(data.d[x].votes > 0 ? data.d[x].votes + " (" + percent + "%)" : "");
                                }

                                //show results container
                                $("#results").slideDown("slow", function () {
                                    //animate each result
                                    $(".result").each(function (i) {
                                        $(this).show().animate({ width: Math.round(data.d[i].votes / total * 100) * config.maxWidth }, "slow");
                                    });

                                    //create and show thanks message

                                    if (config.readOnly == false)
                                        $("<p>").attr("id", "thanks").text("Gracias por votar!").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);
                });
            }
            else {
                var addOpts = {
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    data: "{" + "'questionId':'" + config.questionId + "'}", //"&choice=" + selected,
                    dataType: "json",
                    success: function (data) {

                        //add all votes to get total

                        var total = 0;
                        for (var x = 0; x < data.d.length; x++) {
                            total += parseInt(data.d[x].votes);
                        }
                        //change h2
                        $(config.containerId).find("h2").text("Resultados, de un total de " + total + " votos:");
                        //remove form
                        $(config.containerId + " form#pollForm").slideUp("slow");
                        //create results container
                        $("<div>").attr("id", "results").css({ display: "none" }).insertAfter(config.containerId + " #pollForm");
                        //create results
                        for (var x = 0; x < data.d.length; x++) {

                            //create row elment
                            $("<div>").addClass("row").attr("id", "row" + x).appendTo(config.containerId + " #results");

                            //create label and result
                            $("<label>").text(config.groupIDs[x]).appendTo(config.containerId + " #row" + x);
                            var percent = 0;
                            if (total > 0)
                                percent = Math.round(data.d[x].votes / total * 100);
                            $("<div>").attr("title", percent + "%").addClass("result").css({ display: "none" }).appendTo(config.containerId + " #row" + x).html(data.d[x].votes + " (" + percent + "%)");  //data.d[x].votes > 0 ? data.d[x].votes + " (" + percent + "%)" : "");
                        }

                        //show results container
                        $(config.containerId + " #results").slideDown("slow", function () {
                            //animate each result
                            $(config.containerId + " .result").each(function (i) {
                                var width = 0;
                                if (total > 0)
                                    width = Math.round(data.d[i].votes / total * 100) * config.maxWidth;
                                $(this).show().animate({ width: width }, "slow");
                            });

                            //create and show thanks message
                            //$("<p>").attr("id", "thanks").text("Gracias por votar!").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 $.ajax(ajaxOpts);
            }
            //return the jquery object for chaining
            return this;
        }
    });
})(jQuery);


