// Functions for Polls

// TODO: Wrap in object for namespace

function PollGet(poll_id, div_name) {
    // ? do we need to ave a cookie per poll for polls on different pages or multiple polls on a single page?
    if (!cookie_is_set("poll_"+poll_id)) {
        // Get the Poll
        PollGet_send(poll_id, div_name);
    }
    else {
        // Get the Poll results
        PollResults_send(poll_id, div_name);
    }    
}

function PollSubmit(form_id, poll_id, div_name) {
    // TODO: Check for a selection - if no selection then do nothing
    // TODO: Get selected option
    var pollForm = document.forms[form_id];
    var poll_answer_radios = pollForm.elements["choice"];
    var poll_answer;
    var answer_set = false;
    for (i = 0; i < poll_answer_radios.length; i++) {
        if (poll_answer_radios[i].checked) {
            poll_answer = poll_answer_radios[i].value;
            answer_set = true;
            break;
        }
    }

    if (answer_set) {
        PollSubmit_send(poll_id, poll_answer, div_name);
    }
    else {
        alert("Please select an answer.");
    }
}

function PollGet_send(poll_id, div_name) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    var fnWhenDone = function (oXML) { PollGet_done(div_name, oXML.responseText); };
    var str = "cmd=get&pollId=" + poll_id;
    myConn.connect("/NGPoll/servlet/PollService", "POST", str, fnWhenDone);
}

function PollGet_done(div_name, response_text) {
    // TODO: get status
    UpdateDiv(div_name, response_text)
}

function PollSubmit_send(poll_id, answer_id, div_name) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    var fnWhenDone = function (oXML) { PollSubmit_done(poll_id, answer_id, div_name, oXML.responseText); };
    var str = "cmd=submit&pollId=" + poll_id + "&answerId=" + answer_id;
    myConn.connect("/NGPoll/servlet/PollService", "POST", str, fnWhenDone);
}

function PollSubmit_done(poll_id, answer_id, div_name, response_text) {
    // TODO: get status
    UpdateDiv(div_name, response_text)
    cookie_set("poll_"+poll_id, answer_id, 1)
}

function PollResults_send(poll_id, div_name) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    var fnWhenDone = function (oXML) { PollResults_done(div_name, oXML.responseText); };
    var str = "cmd=results&pollId=" + poll_id;
    myConn.connect("/NGPoll/servlet/PollService", "POST", str, fnWhenDone);
}

function PollResults_done(div_name, response_text) {
    // TODO: get status
    UpdateDiv(div_name, response_text)
}
