﻿/// <reference path="jquery-1.2.6-vsdoc.js"/>

(function(jQuery) {

    jQuery.fn.survey = function(options) {

        var settings = jQuery.extend({}, jQuery.fn.survey.defaults, options);
        var base = this;

        function getScript(url, s, e) {
            jQuery.ajax({ url: url, dataType: 'script', success: s, error: e });
        }
        function getResults(submit) {
            jQuery('.answers', base).hide('slow');
            jQuery('.loading', base).show('fast');
            var requestUrl = settings.url + '?id=' + settings.surveyId + '&jsonTag=json_var';
            if (submit) {
                var answer = jQuery('input[name=' + base[0].id + 'selectedAnswer]:checked').val();
                
                requestUrl += '&op=vote&answer=' + answer;
            }
            //alert(submit +'-'+requestUrl);
            getScript(requestUrl,
                    function() {
                        try {
                            jQuery('.error', base).fadeOut().html(json_var.error).fadeIn('slow');
                            jQuery('.numVotes', base).html(json_var.total);
                            jQuery.each(json_var.answers, function(i, item) {
                                var _perc = 0;
                                if (json_var.total != 0)
                                    _perc = Math.round(item.votes * 100 / json_var.total) + '%';
                                else
                                    _perc = '0%';
                                jQuery('#answer_' + base[0].id + item.id).html(_perc);
                                jQuery("#answer_" + base[0].id + item.id).animate({ width: _perc }, { queue: false, duration: 2000 });
                            });
                            jQuery('.graphic', base).show('slow');
                            jQuery('.loading', base).hide('fast');
                        }
                        catch (e) { jQuery('.loading', base).hide().show('slow').html('Erro de comunicação!'); }
                    },
                    function() { jQuery('.loading', base).hide().show('slow').html('Erro de comunicação!'); }
                );
                };

        if (settings.generateHtml) {
            base.html('<h5 class="question"></h5><div class="loading" style="display:none;">A carregar...</div><div class="answers"><input title="Votar" type="button" value="Votar" class="submit" /><input title="Resultados" type="button" value="Resultados" class="results" /></div><div class="graphic" style="display:none"><div><span class="labelNumVotes">Número de Votos: </span><span class="numeroVotacoes numVotes"></span><p class="error"></p><input title="Voltar" type="button" value="Voltar" class="goBack" /></div></div>');
        }

        jQuery('.answer', base).hide('fast');
        jQuery('.loading', base).show('fast');

        jQuery('.goBack', base).click(function() {
            jQuery('.graphic', base).hide('slow');
            jQuery('.answers', base).show('slow');
            jQuery('.error', base).html('');
        });

        getScript(settings.url + "?id=" + settings.surveyId + "&jsonTag=json_var",
        function() {
            try {
                jQuery('.question', base).html(json_var.title);                
                var htmlAnswers = "";
                var htmlResults = ""; 
                jQuery.each(json_var.answers, function(i, item) {
                    htmlAnswers += '<input type="radio" id="lab_' + base[0].id + item.id + '" name="' + base[0].id + 'selectedAnswer" ' + (i == settings.defaultIndex ? 'checked="checked"' : '') + ' value="' + item.id + '" /> <label for="lab_' + base[0].id + item.id + '">' + item.answer + '</label><br/>';
                    htmlResults += '<li>' + item.answer + '</li><li id="answer_' + base[0].id + item.id + '" class="bar" style="width:0%">0%</li>';
                });
               
                jQuery('.answers', base).prepend("<div>" + htmlAnswers + "</div>");
                jQuery('.graphic', base).prepend("<ul>" + htmlResults + "</ul>");

                jQuery('.answers', base).show('fast');
                jQuery('.loading', base).hide('fast');
            }
            catch (e) { jQuery('.loading', base).hide().show('slow').html('Erro de comunicação!'); }
        },
        function() { jQuery('.loading', base).hide().show('slow').html('Erro de comunicação!'); }
    );

        jQuery('.results', base).click(function() {
            getResults(false);
            return false;
        });

        jQuery('.submit', base).click(function() {
            getResults(true);
            return false;
        });

        return jQuery(this);
    }
    jQuery.fn.survey.defaults = { url: 'http://vota.sapo.pt/polljson.php', surveyId: 0, generateHtml: false, defaultIndex: -1 };
})(jQuery);
