﻿(function ($) {
    jQuery.fn.googlechartspoll = function (options) {
        topself = this;

        google.load('visualization', '1', { 'packages': ['corechart'], 'callback': function () {

            $(topself).each(function () {

                var $chart = null;
                var data = null;
                var height = null;
                var width = null;
                var colours = null;
                var backgroundColor = null;
                var tooltipsize = null;
                var legendsize = null;
                var legendfontcolor = "000000";
                var legend = "right";
                var pieslicetext = "percentage";
                var $poll = $(this);
                var $chart_holder = $poll.find(".poll-chart");
                $poll.append("<div class='loader'></div>");
                var $loader = $poll.find(".loader");

                if ($chart_holder.find("img").length > 0) {
                    $loader.height($chart_holder.height());
                    $loader.css({ left: $chart_holder.position().left + "px", top: $chart_holder.position().top + "px" });
                    $loader.width($chart_holder.width()).fadeIn();
                }
                else {
                    $loader.width($chart_holder.width())
                    $loader.height($poll.find("fieldset").height() - $poll.find("p").height());
                }

                $poll.find('input.poll-submit').click(function (e) {
                    if ($(this).parent().find(".results-page-mode").length == 0) {
                        e.preventDefault();
                        $(this).attr("disabled", "disabled").blur();
                        var args = $(e.currentTarget).parents('fieldset').find('input').serialize();
                        var pollID = $poll.find("a").attr("id").split("_")[1];
                        processJSON(pollID, args, true);
                    }
                });

                preparePieChart();

                //Assign a new data table to the data object and set up columns
                function preparePieChart() {
                    data = new google.visualization.DataTable();
                    data.addColumn('string', 'Title');
                    data.addColumn('number', 'Value');

                    //Create a new pie chart
                    $chart = new google.visualization.PieChart($chart_holder[0]);
                    if ($poll.find("img").length > 0) {
                        var pollID = $poll.find("a").attr("id").split("_")[1];
                        var args = "resultsOnly=true";
                        $loader.fadeIn("slow");
                        processJSON(pollID, args, true);
                    }
                };

                //Function for processing JSON calls
                function processJSON(pollID, args, hideButton) {
                    $.getJSON('/poll/poll-json-results.aspx?pollID=' + pollID + "&" + args, function (data) {
                        var json_obj = data;
                        drawChart(json_obj);
                        if (hideButton) { $poll.find(".poll-submit").fadeOut().remove(); }
                    });
                }

                //Add the data rows, populate results template and draw the chart (based on image attributes)
                function drawChart(json_obj) {
                    stealAttributes();
                    data.removeRows(0, data.getNumberOfRows());
                    data.addRows(json_obj.graph_rows);
                    $loader.fadeOut();
                    $chart.draw(data, { chartArea: { left: -0, width: 381, height: 132 }, pieSliceTextStyle: { fontSize: 12 }, height: height, width: width, is3D: true, titleColor: json_obj.graph_title_color, legendFontSize: legendsize, colors: colours, backgroundColor: backgroundColor, legendBackgroundColor: backgroundColor, tooltipTextStyle: { fontSize: 14 }, legendTextStyle: { color: "#" + legendfontcolor }, legend: legend, pieSliceText: pieslicetext });
                };

                //Function to steal attributes from the image output
                function stealAttributes() {
                    var img = $poll.find("img.chart-results-image");
                    var attr = "";
                    if (img.length == 0) {
                        attr = $poll.find("a").attr("href");
                    }
                    else {
                        attr = img.attr("src");
                    }
                    var dimensions = getQuerystringVal(attr, "chs");
                    width = dimensions.split("x")[0];
                    height = dimensions.split("x")[1];
                    if (width == '154') {
                        legend = 'none';
                        pieslicetext = 'label';
                    }
                    colours = getQuerystringVal(attr, "chco").split("|");
                    tooltipsize = parseInt(getQuerystringVal(attr, "tts"), 10);
                    legendsize = parseInt(getQuerystringVal(attr, "ls"), 10);
                    if (getQuerystringVal(attr, "chdls") != "") {
                        legendfontcolor = getQuerystringVal(attr, "chdls");
                    }
                    backgroundColor = getQuerystringVal(attr, "chf").split(",")[2];
                };

            }); //End of each  

        }
        }); //End of google.load 
    };
})(jQuery);

function getQuerystringVal(string, key, default_) {
    if (default_ === null) { default_ = ""; }
    key = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(string);
    if (qs === null) {
        return default_;
    }
    else {
        return qs[1];
    }
}
