/**
 * ajaxpoll
 *
 * @author Mike Bosworth
 * @classDescription A common poll implemented to be backwards compatible with existing site specifc polls.
 **/

/* ---[ SETUP NAMESPACE ]--- */
if(typeof(mdp) != 'object'){
	var mdp = {};
}

var ajaxPoll = function(_pollId, _maxWidth, options){

    /* ---[ CLASS VARIABLES ]--- */

	/* public */
    this.ID = _pollId;
    this.MAX_WIDTH = parseInt(_maxWidth, 10) || 250;
    this.TOTAL_ANSWERS = 0;
    this.ANIMATE = true;

    /* private */
    var self = this;

    /* ---[ CONSTRUCTOR ]--- */
    this.init = function(){
        debug("init");

        /* initialization code */
        if(options == null){
            options = {};
        }
        options.restrict = options.restrict != null ? options.restrict : true;
        options.autoSubmit = options.autoSubmit != null  ? options.autoSubmit  : false;
        options.pageRefresh = options.pageRefresh != null  ? options.pageRefresh  : false;
        options.bypass = options.bypass != null  ? options.bypass : false;
        options.parentElement = options.parentElement != null  ? options.parentElement : "#pollwrap";
        options.debug = options.debug != null  ? options.debug : false;
        if (self.ID != "" || self.ID != undefined) {
            RemotePollService.getPoll(self.ID, self.createPoll);
        }
    };

    /* ---[ PUBLIC METHODS ]--- */
    this.createPoll = function(remoteResult) {
        debug("createPoll");
        if (remoteResult.statusCode == 0) {

            options.parentElement = $(options.parentElement);
            var pj = eval('(' + remoteResult.result + ')');
            options.parentElement.html('');

            /* remove the no JS nag */
            var voted = $.cookie(pj.cookieId);
            var pollName = (typeof(pj.name) == 'undefined') ? "No Title" : pj.name ;
            var pollContentHead = $("<h2>").html(pollName);
            var pollQuestion = (typeof(pj.question) == 'undefined') ? "No Question" : pj.question ;
            var pollContentQuestion = $("<p>").attr({"class":"bold"}).html(pollQuestion);
            var pollContentWrap = $("<div>").attr({'id':'pollContent'});

            pollContentQuestion.appendTo(options.parentElement);
            pollContentWrap.appendTo(options.parentElement);

            if (voted == "true") {
                self.ANIMATE = false;
                renderResults(pj);
            } else {
                self.renderForm(pj);
            }
        }
        else{
            alert("Failed To Retreive Poll Results : " + remoteResult.statusMessage);
        }
    };

    this.renderForm = function(pj){
        debug("renderForm");
        var pollContent = $('#pollContent');
        pollContent.html("");
        
        /* iterate through the questions */
        for (var i = 0; i < pj.answers.length; i++) {
            var qwrap = $("<div>").attr({'class':'qwrap','id':'qwrap' + i});
            var queswrap = $("<div>").attr({'class':'ques'});
            var radwrap = $("<div>").attr({'class':'radio'});
            /* this crazy way of creating the radio button is required by IE7 */
            var rad = $("<input type='radio' name='pollchoice'>").attr({'name':'poll','class':'radio', 'id':'pq' + i});
            rad.appendTo(radwrap);
            radwrap.appendTo(queswrap);

            var ques = $("<label>").attr({'class':'questext', 'for':'pq' + i}).html(pj.answers[i].answer);
            var clear = $("<div>").attr({'class':'clearall'});

            clear.appendTo(pollContent);
            qwrap.appendTo(pollContent);
            queswrap.appendTo($('#qwrap' + i));
            ques.appendTo($('#qwrap' + i));
        }
        $("<div>").attr({'class':'clearall'}).appendTo(options.parentElement);

        var submitvote = $("#submitvote");
        var submit = $("<a>").attr({
            'href': 'javascript:void(0)',
            'id': 'submitvote',
            'class': 'ML10 MT10 largeBtnLeft'
        }).click(function(){
            if(self.submitVote()){
                $("#submitvote").remove();
                $("#viewresults").remove();
            }
        }).appendTo(options.parentElement);
        $("<span>").addClass("largeBtn").html("Vote").appendTo(submit);

        if(options.bypass){
            $("<a>").attr({
                'href': 'javascript:void(0)',
                'id': 'viewresults',
                'class': 'ML10 MT10'
            }).html("Results").click(function(){
                self.handleResults();
                $("#submitvote").remove();
                $("#viewresults").remove();
            }).appendTo(options.parentElement);
        }
        $("<div>").attr({'class':'clearall'}).appendTo(options.parentElement);
    };

    this.submitVote = function() {
        debug("submitVote");
        var s = this;
        this._answerId = null;
        this.bhgpollradios = new Array();
        this.inputelements = document.getElementsByTagName("input");

        $("#pollContent input.radio").each(function(index){
            if(this.checked){
                s._answerId = index;
            }
        });

        if (s._answerId == null) {
            alert("Please select an option");
        } else {
            if(self.ID != ''){
                RemotePollService.castVote(self.ID, s._answerId, self.submitVoteCallback);
                return true;
            }
            else{
                alert("Failed To Submit Poll: Missing Poll Id!");
            }
        }
        return false;
    };

    this.submitVoteCallback = function(remoteResult) {
        debug("submitVoteCallback");
        if (remoteResult.statusCode == 0) {
            self.handleResults();
        }
        else{
            alert("Failed To Submit Vote : " + remoteResult.statusMessage);
        }
    };

    this.handleResults = function(){
        debug("handleResults");
        if (self.ID != "" || self.ID != undefined) {
            var handler;
            if(options.pageRefresh){
                handler = self.pageRefresh;
            }
            else{
                handler = self.displayPollResults;
            }
            RemotePollService.getPoll(self.ID, handler);
        }

    };

    this.pageRefresh = function(remoteResult){
        debug("pageRefresh");
        if (remoteResult.statusCode == 0) {
            var pj = eval('(' + remoteResult.result + ')');
            $.cookie(pj.cookieId, 'true', {path:"/"});
            history.go(0);
        }
        else{
            alert("Failed To Retreive Poll Results : " + remoteResult.statusMessage);
        }
    };

    this.getPollObjectForResults = function() {
        debug("getPollObjectsForResults");
        if (self.ID != "" || self.ID != undefined) {
            console.log(RemotePollService);
            console.log(self.ID);
            console.log(self.displayPollResults);
            RemotePollService.getPoll(self.ID, self.displayPollResults);
        }
        else{
            alert("Failed To Retrieve Poll Results: Poll Id Is Not Specified.");
        }
    };

    this.displayPollResults = function(remoteResult) {
        debug("dispalyPollResults");
        if (remoteResult.statusCode == 0) {
            var pj = eval('(' + remoteResult.result + ')');

            /*set poll cookie*/
            $.cookie(pj.cookieId, 'true', {path:'/'});

            if(pj.answers != null){
                renderResults(pj);
            }
            else{
                alert("Bad Data Returned!");
            }
        }
        else{
            alert("Failed To Retreive Poll Results : " + remoteResult.statusMessage);
        }
    };

    /* ---[ PUBLIC METHODS ]--- */

    function renderResults(pj){
        debug("renderResults");
        $('#pollContent').html("");

        for (var i = 0; i < pj.answers.length; i++) {
            self.TOTAL_ANSWERS += parseInt(pj.answers[i].answerCount);
        }

        /* loop through he answers and their questions */
        for (var i = 0; i < pj.answers.length; i++) {
            var ques = $("<div>").attr({'class':'que','id':'que' + i}).html(pj.answers[i].answer);
            var clear = $("<div>").attr({'class':'clearall','style':'height:10px;'});
            var percVote = Math.round((pj.answers[i].answerCount / self.TOTAL_ANSWERS) * 100);

            var bar = $("<div>").attr({'class':'quebar','id':'quebar' + i}).css('width', 0).html(percVote + "%");
            var barwrap = $("<div>").attr({'class':'barwrap'});

            bar.appendTo(barwrap);
            barwrap.appendTo(ques);
            ques.appendTo($('#pollContent'));
            clear.appendTo($('#pollContent'));

            var maxWidth = (parseInt(barwrap.width(), 10) > 1) ? parseInt(barwrap.width(), 10) : self.MAX_WIDTH;
            var barWidth = Math.round((percVote * maxWidth) / 100);

            if (self.ANIMATE) {
                bar.animate({'width':barWidth},1000);
            } else {
                bar.css('width',barWidth + "px");
            }
        }

        if(!options.restrict){
            $("<br>").attr({'class':'clearall'}).appendTo(options.parentElement);
            var submit = $("<a>").attr({
                'href': 'javascript:void(0)',
                'id': 'submitvote',
                'class': 'ML10 MT10'
            }).click(function(){
                $('#submitvote').remove();
                self.renderForm(pj);
            }).appendTo(options.parentElement);
            $("<span>").html("Vote").appendTo(submit);
            $("<div>").attr({'class':'clearall'}).appendTo(options.parentElement);
        }
    }

    function debug(msg){
        if(options.debug){
            if(typeof(console) == 'object'){
                console.log(msg);
            }
            else{
                alert(msg);
            }
        }
    }

    /* ---[ RUN ]--- */
    this.init();
};
