cookieName = 'tr_pollvotes';
cookieDuration = 365;

var handleFailure = function(o){
	if(o.responseText !== undefined){
        var div = document.getElementById('poll_container_' + poll_id);
		div.innerHTML = "There was an error fetching poll data from the server.  Please reload the page.";
	}
}

function pick_choice(e,ids){
    YAHOO.util.Event.preventDefault(e);
    var poll_id = ids['poll_id'];
    var choice_id = ids['choice_id'];
    var polloptions = document.getElementById('polloptions_' + poll_id);
    if (polloptions) {
        var inputs = polloptions.getElementsByTagName('input');
        if (inputs) {
            for (var i = 0; i < inputs.length; ++i) {
                if (inputs[i].type == 'radio' && inputs[i].name == ( 'pollopt_' + poll_id ) )
                    inputs[i].checked = inputs[i].value == choice_id;
            }
        }
    }
}

function voteResult(o) {
    if(o.responseText !== undefined){
        var poll_id = o.argument;
        var status = document.getElementById("poll_status_" + poll_id);
        var reply = YAHOO.lang.JSON.parse(o.responseText);
        if (reply['status']!=1) {
            status.innerHTML = "There was an error registering your vote: " + reply['error'];
        } else {
            vote_cookie(poll_id);
            var switch_view = document.getElementById('poll_switchview_' + poll_id);
            status.innerHTML = reply['message'];
            var poll_vote = document.getElementById('poll_vote_' + poll_id);
            poll_vote.innerHTML = "";
            load_results(poll_id)
            switch_view.innerHTML = "<a href=\"\" id=\"switch_view_" + poll_id + "\">Refresh results</a>";
            YAHOO.util.Event.addListener("poll_switchview_" + poll_id, "click", switch_to_results, poll_id);
        }
    }
}

function do_vote(e, poll_id) {
    YAHOO.util.Event.preventDefault(e);
    var polloptions = document.getElementById('polloptions_' + poll_id);
    var status = document.getElementById("poll_status_" + poll_id);
    var id = "";
    if (polloptions) {
        var inputs = polloptions.getElementsByTagName('input');
        if (inputs) {
            for (var i = 0; i < inputs.length; ++i) {
                if (inputs[i].type == 'radio' && inputs[i].name == ('pollopt_' + poll_id ) && inputs[i].checked )
                    id = inputs[i].value;
            }
        }
    }
    if (! ( id.length > 0 )) {
        status.innerHTML = "You have not selected an option.";
        return;
    }

    var request = YAHOO.util.Connect.asyncRequest(
        'POST', "/poll/vote.x", 
        {success:voteResult,failure:handleFailure, argument:poll_id},
        "id=" + id
    );
}

var fillBooth = function(o){
    var poll_id = o.argument;
    var div = document.getElementById('poll_container_' + poll_id);
    if(o.responseText !== undefined){
        var reply = YAHOO.lang.JSON.parse(o.responseText);
        if (reply['status']!=1) {
            div.innerHTML = "There was an error fetching poll data from the server: " + reply['error'];
        } else {
            var poll_vote = document.getElementById('poll_vote_' + poll_id);
            var status = document.getElementById("poll_status_" + poll_id);
            var switch_view = document.getElementById('poll_switchview_' + poll_id);
            if ( reply['state'] == 1 ) {
                poll_vote.innerHTML = "Voting is closed for this poll.";
                //status.innerHTML = "Voting is closed for this poll";
                load_results(poll_id);
            } else if (has_voted(poll_id)) {
                poll_vote.innerHTML = "You already voted in this poll.";
                //status.innerHTML = "You already voted in this poll";
                load_results(poll_id);
            } else {
                var newtext = "<h4>" + reply['question'] + "</h4>" + "<ul id=\"polloptions_" + poll_id + "\" class=\"polloptions\">";
                for (choice_name in reply['choices']) {
                    var choice_id = reply['choices'][choice_name];
                    newtext += "<li><input type=\"radio\" name=\"pollopt_" + poll_id + "\" value=\"" + choice_id + "\">" +
                        "<a href=\"#\" id=\"vote_for_" + choice_id + "\">"
                        + choice_name + "</a></li>";
                }
                newtext += "</ul>";
                div.innerHTML = newtext;
                for (choice_name in reply['choices']) {
                    var choice_id = reply['choices'][choice_name];
                    YAHOO.util.Event.addListener("vote_for_" + choice_id, "click", pick_choice, {poll_id:poll_id,choice_id:choice_id});
                }
                poll_vote.innerHTML = "<input id=\"vote_" + poll_id + "\" type=\"submit\" value=\"Vote!\">";
                YAHOO.util.Event.addListener("vote_" + poll_id, "click", do_vote, poll_id);
                switch_view.innerHTML = "<a href=\"\" id=\"switch_view_" + poll_id + "\">View results</a>";
                YAHOO.util.Event.addListener("switch_view_" + poll_id, "click", switch_to_results, poll_id);
                
            }
        }
    }
}

function load_poll(id) {
    var request = YAHOO.util.Connect.asyncRequest(
        'GET', "/poll/booth.x?id=" + id,
        { success:fillBooth, failure:handleFailure, argument:id }
    );
}


var fillResults = function(o){
	if(o.responseText !== undefined){
        var reply = YAHOO.lang.JSON.parse(o.responseText);
        if (reply['status']!=1) {
            div.innerHTML = "There was an error fetching poll data from the server: " + reply['error'];
        } else {
            var poll_id = o.argument;
            var div = document.getElementById('poll_container_' + poll_id);
            var total = document.getElementById('poll_total_' + poll_id);
            var newtext = "<h4>" + reply['question'] + "</h4><ul id=\"pollresults\">";
            for (i in reply['options']) {
                var option = reply['options'][i];
                newtext += "<li>" + option['name'] + " (" + option['count'] + " votes)" +
                "<div class=\"pollbar\"><img src=\"/img/blank.gif\" style=\"width: " + option['width'] + "%;\"/>" +  option['percent'] + "%</div>" +
                "</li>";
            }
            newtext += "</ul>"
            div.innerHTML = newtext;
            total.innerHTML = "Total votes: " + reply['total'] + ".";
            var switch_view = document.getElementById('poll_switchview_' + poll_id);
            var poll_vote = document.getElementById('poll_vote_' + poll_id);
            poll_vote.innerHTML = "";
            switch_view.innerHTML = "<a href=\"\" id=\"switch_view_" + poll_id + "\">Refresh results</a>";
            YAHOO.util.Event.addListener("poll_switchview_" + poll_id, "click", switch_to_results, poll_id);
        }
	}
}


function load_results(id){
	var request = YAHOO.util.Connect.asyncRequest(
        'GET', "/poll/results.x?id=" + id, 
        { success:fillResults, failure:handleFailure,argument:id }
    );
}

function switch_to_results(e,id) {
    YAHOO.util.Event.preventDefault(e);
    load_results(id);
    
}

function has_voted(id) {
    c = _readCookie(cookieName);
    if (c) {
        v = c.split(',');
        return in_array(v,id);
    } else {
        return false
    }
}

function vote_cookie(id) {
    c = _readCookie(cookieName);
    if (c)
        v = c.split(',')
    else
        v = new Array()
    v.push(id);
    _createCookie(cookieName,v.join(','),cookieDuration)
}

function _createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function _readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function in_array(array,search_term) {
  var i = array.length;
  if (i > 0) {
	 do {
		if (array[i] == search_term) {
		   return true;
		}
	 } while (i--);
  }
  return false;
}

