/* @todo ADD HANDLING FOR poll-mid TO HAVE A MIN-HEIGHT FOR BROWSERS THAT DON'T SUPPORT THAT RULE */

var Polls = new Class({
    
    submitting: false, // Indicator of whether answer is currently being sent or not
    
    initialize: function() {
        
        var polls = $$("div.poll"); // Find all polls
        
        this.polls = []; // Indexed array of poll objects
        
        polls.each(function(item, index) {
            
            this.polls.push({}); // Push new empty ibject
            
            this.polls[index].tallyShowing = false; // Indicator of whether the tally is showing
            
            // SET OBJECTS
            
            // Loading indicator
            
            this.polls[index].loading = item.getElement(".loading");
            this.polls[index].loadingFx = new Fx.Style(item.getElement(".loading"), "opacity", {duration: 200}).set(0);
            
            // Message/success/error
            
            this.polls[index].msgFx = new Fx.Slide(item.getElement(".status"), {duration: 200}).hide();
            this.polls[index].success = item.getElement(".status .success");
            this.polls[index].error_already_voted = item.getElement(".status .already-voted");
            this.polls[index].error_server = item.getElement(".status .server");
            
            // Tally
            
            this.polls[index].tallyNoGraph = item.getElement(".tally-no .tally-graph");
            this.polls[index].tallyNoText = item.getElement(".tally-no .tally-percent");
            this.polls[index].tallyYesGraph = item.getElement(".tally-yes .tally-graph");
            this.polls[index].tallyYesText = item.getElement(".tally-yes .tally-percent");
            this.polls[index].tallyFx = new Fx.Slide(item.getElement(".poll-tally"), {duration: 200}).hide();
            
            // SET BUTTON EVENTS
            
            // Vote buttons
            
            var yesBtn = item.getElement("a.poll-yes");

            yesBtn.addEvent("click", function(evt) {
                this.submitAnswer(evt, index);
            }.bind(this));

            var noBtn = item.getElement("a.poll-no");

            noBtn.addEvent("click", function(evt) {
                this.submitAnswer(evt, index);
            }.bind(this));
            
            // Show/hide tally button
            
            this.polls[index].tallyBtn = item.getElement("a.poll-tally-show");
            
            this.polls[index].tallyBtn.addEvent("click", function(evt) {
                this.toggleTally(evt, index);
            }.bind(this));
            
        }, this);
                
    },
    
    // Submit ajax answer request and handle status indication
    
    submitAnswer: function(evt, index) {
        
        evt = new Event(evt).stop();
        
        // If currently submitting, do not proceed
        
        if (this.submitting) {
            return false;
        } else {
            this.submitting = true;
        }
        
        var object = this;
        var url = evt.target.href;
        var indicate = this.polls[index];
        
        indicate.loading.setStyle('visibility', 'visible');
        indicate.loadingFx.start(1);
        
        new Ajax(url, {
            onComplete: function (test) {
                
                object.submitting = false;
                
                indicate.loadingFx.start(0); // Hide loading indicator
                
                // Get response object
                
                var response = Json.evaluate(this.response.text, true);
                
                if (!response.status) response.status = "error_server"; // Default status
                
                // Set status message
                
                switch (response.status) {
                    
                    case "success":
                        indicate.success.setStyle("display", "block");
                        break;
                        
                    case "error_already_voted":
                        indicate.error_already_voted.setStyle("display", "block");
                        break;
                        
                    case "error_server":
                        indicate.error_server.setStyle("display", "block");
                        break;
                    
                }
                
                function hideIt() { indicate.msgFx.slideOut().chain(function() { object.reset(); }); } // Hide message and reset polls
                
                // Show message
                
                indicate.msgFx.slideIn().chain(function() { hideIt.delay(5000); }); // Delay 5 seconds
                
                // Show tally
                
                object.updateTally(response, index);
                
                if (!indicate.tallyShowing) {
                    object.toggleTally(null, index);
                }
                
            }
        }).request();
    },
    
    // Tally toggle
    
    toggleTally: function(evt, index) {
        
        if (evt != null) evt = new Event(evt).stop();
        
        if (this.polls[index].tallyShowing) {
            this.polls[index].tallyShowing = false;
            this.polls[index].tallyFx.slideOut();
            this.polls[index].tallyBtn.removeClass("hide");
            this.polls[index].tallyBtn.addClass("show");
        } else {
            this.polls[index].tallyShowing = true;
            this.polls[index].tallyFx.slideIn();
            this.polls[index].tallyBtn.removeClass("show");
            this.polls[index].tallyBtn.addClass("hide");
        }
        
    },
    
    // Update tally
    
    updateTally: function(data, index) {
        
        // Calculate percentages
        var total = data.poll_option_1_cnt.toInt() + data.poll_option_2_cnt.toInt();
        if (total > 0) {
            var noPct = Math.round((data.poll_option_1_cnt/total)*100);
            var yesPct = Math.round((data.poll_option_2_cnt/total)*100);
        } else {
            var noPct = 0;
            var yesPct = 0;
        }
        
        // Update tally graphs and text
        
        this.polls[index].tallyNoGraph.setStyle("width", noPct+"%");
        this.polls[index].tallyNoText.setText(noPct+"%");
        this.polls[index].tallyYesGraph.setStyle("width", yesPct+"%");
        this.polls[index].tallyYesText.setText(yesPct+"%");
    },
    
    // Set all indicators to their default visibility/display
    
    reset: function() {
        
        this.polls.each(function(item) {
            item.loading.setStyle("display", "block");
            item.loading.setStyle("visibility", "hidden");
            item.success.setStyle("display", "none");
            item.error_already_voted.setStyle("display", "none");
            item.error_server.setStyle("display", "none");
        });
        
    }
    
});

window.addEvent("domready", function() { new Polls; });