dojo.hostenv.loadModule("dojo.io.*");
dojo.hostenv.loadModule("dojo.graphics.*");
dojo.require("dojo.cd.vehiclepage");
dojo.require("dojo.json");

var pollVote = function()
{
   var object = this;
    this.can_vote = 0;
    this.responseHandler = function(txt,action)
    {
        var jsonObject = dojo.json.evalJSON(txt).poll; 
        
        poll_div = document.createElement("div");
        poll_div.setAttribute("id","poll_div") ;
        
        if(jsonObject.status==0)
        {
            for ( i=1; i<=jsonObject.num_options; i++ )
            {
                vote_percent = 0;
                if (jsonObject.total_votes > 0)
                {
                    vote_percent = (jsonObject.votes[i] / jsonObject.total_votes) * 10000;
                    vote_percent = Math.ceil(vote_percent)/100;
                }
                option_text = document.createTextNode(jsonObject.options[i] +" - ("+ vote_percent +"%)");
                option_img = document.createElement("img");
                    option_img.setAttribute("src", "http://images.cardomain.net/sites/sounddomain/home/light_middle.gif");
                    option_img.setAttribute("height", "10");
                    option_img.setAttribute("width", vote_percent);
                option_p = document.createElement("p");
                    option_p.appendChild(option_text);
                poll_div.appendChild(option_p);
                poll_div.appendChild(option_img);
            }
            total_text = document.createTextNode("Total Votes: "+ jsonObject.total_votes);
            total_div = document.createElement("p");
            total_div.setAttribute("id","showing_results") ;
            total_div.appendChild(total_text);
            poll_div.appendChild(total_div);
            if (action=="results")
            {
                document.getElementById("poll_back").style.display="block";
            }
            document.getElementById("poll_results").style.display="none";
        } else {
                document.getElementById("poll_question").style.display="none";
                new_text = document.createTextNode("Thank you for voting!");
                new_p = document.createElement("p");
                new_p.appendChild(new_text);
                poll_div.appendChild(new_p);
        }
            document.getElementById("poll_form").style.display="none";
            document.getElementById("display_poll").appendChild(poll_div);
            document.getElementById("display_poll").style.display = "block";
    }

    this.vote = function(form) {
        var options = {
            mimetype: "text/plain",
            formNode: form,
            load: function(type, txt, e) {
                object.responseHandler(txt,"vote");
            },
            error: function(t, e) {
                dj_debug( txt );
            }
        };
        dojo.io.bind(options);
        return false;
    }

    this.results = function(form) {
        var options = {
            mimetype: "text/plain",
            formNode: form,
            load: function(type, txt, e) {
                object.responseHandler(txt,"results");
            },
            error: function(t, e) {
                dj_debug( txt );
            }
        };
        dojo.io.bind(options);
        return false;
    }

    this.enableVote = function()
    {
        this.can_vote = 1;
    }
    
    this.run = function(form)
    {
        if (form.vote.value != "no")
        {
            if (this.can_vote == 1)
            {
                return this.vote(form);
            } else {
                alert('Please select an answer before voting.');
                return false;
            }
        } else {
            return this.results(form);
        }
    }
}

var BallotBox = function(pageId, voteSectionId, alertElementId) {
    var object = this;
    this.alert = new dojo.cd.vehiclepage.alertMessage(alertElementId);
    this.href = '/webservices/community/rating/history?page_id=' + pageId;
    this.voteSectionId = voteSectionId;
    this.pageId = pageId;
    this.votes = new Object();
    this.numberOfVotesCast = 0;
    this.numberOfVoteResponses = 0;
    this.allVotesSucceeded = true;
    
    this.responseHandler = function(txt)
    {
        var jsonObject = dojo.json.evalJSON(txt); 
        
        if (jsonObject.response=="Success")
        {
            this.alert.hide();
            this.alert.clear();
            for(category in jsonObject.vote_history)
            {
                document.getElementById('selected-rating-'+category).style.width = (jsonObject.vote_history[category] * 15) + 'px';
                dj_debug(category +' '+ jsonObject.vote_history[category]);

            }
            dojo.cd.vehiclepage.showBallot(this.voteSectionId);
        } else {
            this.alert.hide();
            this.alert.clear();
            if (jsonObject.error=="unknown_page_id"){
                this.alert.setMessage("Unknown Page ID");
            } else if (jsonObject.error=="no_page_id") {
                this.alert.setMessage("No Page ID");
            } else if (jsonObject.error=="not_logged_in") {
                this.alert.setMessage("You Are Not Logged In");
            }
            this.alert.show();
        }
    }

    this.show = function()
    {
        this.alert.clear();
        this.alert.setMessage("Loading your current votes...");
        this.alert.show();

        var options = {
            url: this.href,
            mimetype: "text/html",
            load: function(type, txt, e) {
                object.responseHandler(txt);
            },
            error: function(type, data, evt) {
                dj_debug("an error occured!");
                dj_debug(data);
            }
        };
        dojo.io.bind(options);

        return false;
    }

    this.hide = function() {
        dojo.cd.vehiclepage.hideBallot(this.voteSectionId);
    }

    this.setVote = function(category, vote) {
        this.votes[category] = vote;
    }

    this.saveVotes = function() {
        var voter = new VehicleVoteCaster(this.pageId, this);
        this.alert.setMessage("Your votes are being submitted...");
        this.alert.show();

        this.numberOfVotesCast = 0;
        this.numberOfVoteResponses = 0;
        this.allVotesSucceeded = true;
        var href = "/webservices/community/rating/vote?page_id=" 
                + this.pageId;
        dj_debug("Saving votes");
        for(category in this.votes) {
            href = href + "&votes=cat_" + category + ":" + this.votes[category];
            this.numberOfVotesCast++;
        }
		if (this.numberOfVotesCast == 0){
			this.alert.setMessage("You did not cast any votes.");
			return false;
		}
        dj_debug("Casting vote via " + href);
        voter.rateHandler(href);
        dj_debug("Finished saving votes");
    }

    this.voteStatusCallback = function(result) {

        dj_debug("Voting result of " + result);
        dj_debug("Cast " + this.numberOfVotesCast + " votes.");

        if(result) {
            this.alert.setMessage("Thank you for voting.");
        }
        else {
            this.alert.setMessage("An error has occurred casting your vote.  Please try again.");
        }
        this.alert.show();
        
    }
}

var VehicleVoteCaster = function(pageId, statusCallbackObject) {
    var object = this;
    this.pageId = pageId;
    this.statusCallback = statusCallbackObject;
   
    this.rateHandler = function(href) {
        dj_debug("Submitting votes");
        var options = {
            url: href,
            mimetype: "text/html",
            load: function(type, txt, e) {
                var jsonObject = dojo.json.evalJSON(txt); 
                if (jsonObject.response=="Success") {
                    object.statusCallback.voteStatusCallback(true);
                    dj_debug("Saw success when voting");
                }
                else {
                    object.statusCallback.voteStatusCallback(false);
                    dj_debug("Saw error when voting");
                }
            },
            error: function(t, e) {
                dj_debug( txt );
            }
        };
        dojo.io.bind(options);
        return false;
    }

}

