
/* Namespace for constants */
var PollConst = new Object();
/* HTML ids */
PollConst.content_id = 'poll-content';
PollConst.message_id = 'poll-message';
PollConst.message_text_id = 'poll-message-text';
PollConst.form_id = 'theform';
PollConst.question_text_id = 'question-text';


/* Get elements so that I don't have to do it in every function call */
//var g_content_div = document.getElementById(PollConst.content_id);
//var g_message_div = document.getElementById(PollConst.message_id);


function Poll(form_cb, answers_cb, error_cb) {
    this._form_cb = form_cb;
    this._answers_cb = answers_cb;
    this._error_cb = error_cb;
    _this = this;

    this._callback = function(req) {
        if (req.readyState != 4)
            return;
        if (req.status == 200) {
            var question = null;
            try {
                question  = parse_poll_xml(req.responseXML);
                _this._form_cb(question);
                display_content();
            } catch(error) {
                 _this._error_cb('An error has occured: ' + error.message);
            }
        } else {
            _this._error_cb('Sorry got a ' + req.status +
                    ' error from the Poll server.');
        }
    }
}

Poll.prototype.process = function(sitegroup) {
    var poll = new PollTransport(this._callback);
    poll.process(sitegroup);
}


function Voter(answers_cb, error_cb) {
    this._answers_cb = answers_cb;
    this._error_cb = error_cb;
    _this = this;

    this._callback = function(req) {
        if (req.readyState != 4)
            return;
        if (req.status == 200) {
            var question = null;
            try {
                question  = parse_poll_xml(req.responseXML);
                _this._answers_cb(question);
                display_content();
            } catch(error) {
                 _this._error_cb('An error has occured: ' + error.message);
            }
        } else {
            _this._error_cb('Sorry got a ' + req.status +
                    ' error from the Poll server.');
        }
    }
}

Voter.prototype.process = function(sitegroup, questionid, answerid) {
    var poll = new PollTransport(this._callback);
    poll.vote(sitegroup, questionid, answerid);
}


function PollResults(answers_cb, error_cb) {
    this._answers_cb = answers_cb;
    this._error_cb = error_cb;
    _this = this;

    this._callback = function(req) {
        if (req.readyState != 4)
            return;
        if (req.status == 200) {
            var question = null;
            try {
                question  = parse_poll_xml(req.responseXML);
                _this._answers_cb(question);
                display_content();
            } catch(error) {
                 _this._error_cb('An error has occured: ' + error.message);
            }
        } else {
            _this._error_cb('Sorry got a ' + req.status +
                    ' error from the Poll server.');
        }
    }
}

PollResults.prototype.process = function(sitegroup, questionId) {
    var poll = new PollTransport(this._callback);
    poll.process(sitegroup, questionId);
}


function PollTransport(callback) {
    this._callback = callback;

    this._req = null;
    var _this = this;

    if (window.XMLHttpRequest) {
        this._req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        this._req = new ActiveXObject('Microsoft.XMLHTTP');
    } else {
        error_cb('Your web browser does not support the ' +
                'XMLHttpRequest object.')
    }

    this._callback_proxy = function() {
        _this._callback(_this._req);
    }
}

PollTransport.prototype.process = function(sitegroup, questionId) {
    if (!sitegroup) {
        sitegroup = '292509166';
    }
    var path = '/poll/poll_api.pd?mode=question&sitegroup=' + sitegroup;
    if (questionId) {
        path += '&qid=' + questionId;
    }
    if (polltype) {
       path += '&polltype=' + polltype;
    }
    this._req.open('GET', path);
    this._req.onreadystatechange = this._callback_proxy;
    this._req.send(null);
}

PollTransport.prototype.vote = function(sitegroup, questionId, answerId) {
    display_message('Processing vote...');
    this._req.open('POST', '/poll/poll_api.pd?mode=vote');
    this._req.setRequestHeader('content-type',
            'application/x-www-form-urlencoded');
    this._req.onreadystatechange = this._callback_proxy;
    this._req.send('qid=' + questionId + '&aid=' + answerId
            + '&sitegroup=' + sitegroup);
}


function Question() {
    this.question_id = null;
    this.question = null;
    this.total_votes = 0;
    this.answers = new Array();
}


function Answer() {
    this.answer_id = null;
    this.answer = null;
    this.url = null;
    this.votes = null;
}


function parse_poll_xml(xmldoc) {
    if (xmldoc.getElementsByTagName('pollerror').length) {
        var element = xmldoc.getElementsByTagName('error').item(0);
        throw element.firstChild.nodeValue;
    }

    if (xmldoc.getElementsByTagName('noquestion').length) {
        hide_poll();
        return;
    }

    var element = xmldoc.getElementsByTagName('question').item(0);
    var question = new Question();
    question.question_id = parseInt(element.getAttribute('id'));
    question.question = element.firstChild.nodeValue;

    var total = 0;
    var elements = xmldoc.documentElement.getElementsByTagName('answer');
    for (var i = 0; i < elements.length; i++) {
        var answer = new Answer();
        element = elements.item(i);
        answer.answer_id = parseInt(element.getAttribute('id'));
        answer.url = unescape(element.getAttribute('url'));
        answer.votes = parseInt(element.getAttribute('votes')) || 0;
        total += answer.votes;
        answer.answer = element.firstChild.nodeValue;
        question.answers.push(answer);
    }
    question.total_votes = total;
    return question;
}

var ag = {
addEventListener : function (element, event, handler) {
    if (element.addEventListener) {
        element.addEventListener(event, handler, false);
    } else {
        element.attachEvent('on' + event, handler);
    }
}
}

function draw_ymirf_horizontal_graph(question, dest_object, width) {
    //set_question_text(question.question);

    var total = question.total_votes;
    var output = '<table border="0" cellspacing="0" cellpadding="0">';
    for (var i = 0; i < question.answers.length; i++){
        var answer = question.answers[i];
        var percent = Math.round(answer.votes * 100 / total) || 0;
        var mywidth = Math.round(width * (percent/100));
        var text = answer.answer;
        if (answer.url) {
            text = '<a href="' + answer.url + '">' + text + '</a>';
        }
        
        output += '<tr><td>' + text + '</td>'
                + '<td class="pct">' + percent + '%</td>'
                + '<td><div class="poll-result-bar" style="width:'
                + percent + 'px"><br></div>'
                + '</td></tr>';
    }
    output += '</table><br/>Total participants: <b>' + total + '</b>';
    dest_object.innerHTML = output;
}



function draw_horizontal_graph(question, dest_object, width) {
    set_question_text(question.question);
    var total = question.total_votes;
    var output = '<table border="0" cellspacing="0" cellpadding="0">';
    for (var i = 0; i < question.answers.length; i++){
        var answer = question.answers[i];
        var percent = Math.round(answer.votes * 100 / total) || 0;
        var mywidth = Math.round(width * (percent/100));
        var text = answer.answer;
        if (answer.url) {
            text = '<a href="' + answer.url + '">' + text + '</a>';
        }
        
        output += '<tr><td>' + text + '</td>'
                + '<td class="pct">' + percent + '%</td>'
                + '<td><div class="poll-result-bar" style="width:'
                + percent + 'px"><br></div>'
                + '</td></tr>';
    }
    output += '</table><br/>Total participants: <b>' + total + '</b>';

    // Camry Poll logic hack
    if (question.question.indexOf('Camry') != -1){
       output += '<br><br>The Correct answer is E '
               + '-- the Camry Hybrid\'s EPA Combined ratings are 43 '
               + 'percent better than the average 4 - cylinder midsize car.';
    }

    dest_object.innerHTML = output;
}

function build_ymirf_vote_form(question, dest_object) {
    //set_question_text(question.question);

    var output = '<input type="hidden" name="questionId" value="'
            + question.question_id + '"/>';
    for (var i = 0; i < question.answers.length; i++){
        var answer = question.answers[i];
        output += '<div class="vote">' 
                + '<input type="radio" name="answerId" '
                + 'value="' + answer.answer_id + '"/>'
                + '<p>';
        var text = answer.answer;
        output += text + '</p></div>';
    }
    dest_object.innerHTML = output;
}


function build_vote_form(question, dest_object) {
    set_question_text(question.question);

    var output = '<input type="hidden" name="questionId" value="'
            + question.question_id + '"/>';
    output += '<table border="0" cellspacing="0" cellpadding="0">';
    for (var i = 0; i < question.answers.length; i++){
        var answer = question.answers[i];
        output += '<tr><td class="poll-radio-cell">' 
                + '<input type="radio" name="answerId" '
                + 'value="' + answer.answer_id + '"/></td>'
                + '<td class="poll-answer-cell">';
        var text = answer.answer;
        if (answer.url) {
            text = '<a href="' + answer.url + '">' + text + '</a>';
        }
 
        output += text + '</td></tr>';
    }
    output += '</table>';
    dest_object.innerHTML = output;
}


function default_error_handler(msg) {
    return display_message(msg);
}

function draw_ymirf_graph_callback(question) {
    draw_ymirf_horizontal_graph(question,
            document.getElementById(PollConst.content_id), 200);
}

function draw_graph_callback(question) {
    draw_horizontal_graph(question,
            document.getElementById(PollConst.content_id), 200);
}


function build_ymirf_form_callback(question) {
    build_ymirf_vote_form(question, document.getElementById(PollConst.form_id));
}

function build_form_callback(question) {
    build_vote_form(question, document.getElementById(PollConst.form_id));
}


function vote_ymirf_submit_handler() {
    var selectedId = null;
    var answerId = document.theform.answerId
    for (var i = 0; i < answerId.length; i++) {
        if (answerId[i].checked) {
            selectedId = answerId[i].value;
        }
    }

    if (selectedId == null) {
        alert('Please make a selection before voting.');
        return false;
    }

    var questionId = document.theform.questionId.value;
    var voter = new Voter(draw_ymirf_graph_callback, default_error_handler);
    voter.process('292509166', questionId, selectedId);
    return true;
}


function vote_submit_handler() {
    var selectedId = null;
    var answerId = document.theform.answerId
    for (var i = 0; i < answerId.length; i++) {
        if (answerId[i].checked) {
            selectedId = answerId[i].value;
        }
    }

    if (selectedId == null) {
        alert('Please make a selection before voting.');
        return false;
    }

    var questionId = document.theform.questionId.value;
    var voter = new Voter(draw_graph_callback, default_error_handler);
    voter.process('292509166', questionId, selectedId);
    return true;
}

/* Show a new message in the message div and hide the content div */
function display_message(message) {
    var element = document.getElementById(PollConst.message_text_id);
    element.removeChild(element.firstChild);
    element.appendChild(document.createTextNode(message));

    document.getElementById(PollConst.content_id).style.display = 'none';
    document.getElementById(PollConst.message_id).style.display = 'block';
}


/* Show the content div and hide the message div */
function display_content() {
    document.getElementById(PollConst.content_id).style.display = 'block';
    document.getElementById(PollConst.message_id).style.display = 'none';
}


/* Insert a text node representing the text of the question into a
 * container element.
 */
function set_question_text(text) {
    var element = document.getElementById(PollConst.question_text_id);
    if (element.firstChild) {
        element.removeChild(element.firstChild);
    }
    element.appendChild(document.createTextNode(text));
}


function hide_poll() {
    document.getElementById('poll').style.display = 'none';
}


function show_poll() {
    document.getElementById('poll').style.display = 'block';
}

