var title = 'Anonymous Reader Poll';
var pollId = 'roundtablePoll';
var resultsUrl = 'http://services.nejm.org/webpolls/nejmpoll/getpollresults.ashx?poll=1';
var voteUrl = 'http://services.nejm.org/webpolls/nejmpoll/recordVote.ashx?poll=1&votes=';
var results = null;
var pollClosed = true;
var pollData = {
	"closed": false,
	"questions": [
		{ 
			"question": "1. Should health care professionals participate in execution by lethal injection?",
			"answers": [ "Yes", "No" ]
		},
		{
			"question": "2. Would you participate in execution by lethal injection?",
			"answers": [ 
				"YES, and I am a health care professional",
				"YES, but I am not a health care professional",
				"NO, and I am a health care professional",
				"NO, but I am not a health care professional"
			]
		}
	]
};

$(function() {
	$('.videoLink').click(function() { 
		var top = Math.floor((window.screen.height - 426) / 2);
		var left = Math.floor((window.screen.width - 716) / 2);
		var url = this.href;
		window.open(url,'', 
		    'left=' + left + ',top=' + top + ',width=716,height=426,' +
			'scrollbars=no,toolbar=no,menubar=no,status=no');
		if($.mmsIsSafari2())
		    this.href = "#pfHeader";
		return false;
	});

    $('#' + pollId).replaceWith(processPoll(pollData));
	$.ajax({ dataType: 'jsonp', url: resultsUrl, success: processResults });
	
    if($.browser.safari)
        $('label').css('cursor', 'default');
	
	$('li:first-child').addClass('first');
	$('li:last-child').addClass('last');
});

var processResults = function(data) { 
    results = data.answers;
    if(pollClosed || $.cookie('perspectiveRoundtablePollTaken'))
        showResults($('#' + pollId + '1'), !pollClosed);
};

var processPoll = function(data) {
	var poll = $('<div id="' + pollId + '1" class="' + pollId + ' ' + pollId + 'Open"></div>')
		.append($('<h2></h2>')
			.append($('<span></span>').text(title)))
		.append($('<div class="content"></div>')
		    .append($('<form id="' + pollId + 'Form"></form>'))
			.append($('<p class="vote"></p>')
			    .append($('<img class="voteButton" src="img/voteButtonDisabled.png" alt="Vote">')))
			.append('<p class="thanks">Thank you for voting!</p>')
			.append('<p class="responses"></p>'));

    var form = poll.find('#' + pollId + 'Form');
    $.each(data.questions, function(i) {
		var questionId = pollId + 'q' + i;
    	form.append($('<p class="question"></p>').text(this.question));
	    var answers = $('<ul class="answers" id="' + questionId + '"></ul>');
	    
	    if(i == data.questions.length - 1)
	        answers.addClass('lastAnswers');
		
	    $.each(this.answers, function(j) {
		    var answerId = questionId + 'a' + j;
		    answers.append($('<li></li>')
			    .append($('<input type="radio" value="' + j + '" name="' + questionId + '">')
			        .attr('id', answerId))
			    .append($('<label>' + this + '</label>').attr('for', answerId))
			    .append($('<div class="resultBar"></div>')
			    	.append($('<div class="bar"></div>'))
				    .append($('<div class="pct"></div>'))));
        });
        form.append(answers);
	});

    if(pollClosed)
        poll.find('.thanks').text('Poll closed February 28th, 2008');

	poll.find('.thanks, .responses, .resultBar').css('display', 'none');
	poll.find('input').bind('click', questionAnswered);
	poll.find('.vote').bind('click', poll, vote);
	return poll;
};

var getPollAnswers = function() {
    return $('.content input').serializeArray();
};

var questionAnswered = function() {
    if(results && getPollAnswers().length == results.length)
        enableVoteButton();
};

var disableVoteButton = function() {
    $('.content .voteButton').attr('src', 'img/voteButtonDisabled.png');
};

var enableVoteButton = function() {
    $('.content .voteButton').attr('src', 'img/voteButton.png');
};

var vote = function(e) {
    disableVoteButton();
    if(results) {
	    var answers = $.mmsMakeMap(getPollAnswers());
	    var unansweredQuestions = [];
	    $.each(results, function(i) {
	        var question = pollId + 'q' + i;
	        if(!answers[question])
	            unansweredQuestions.push(question);
	    });
    	
	    if(unansweredQuestions.length == 0) {
	        var i = 0;
	        var votes = []; 
            $.each(answers, function() {
                votes.push(parseInt(this) + 1);
                results[i++][this]++;
            });
            
            $.cookie('perspectiveRoundtablePollTaken', 'true', { expires: 365 });
	        $.ajax({ dataType: 'jsonp', url: voteUrl + votes.join(',') });
	        showResults(e.data);
	    }
	    else {
	        var defaultBackground = e.data.find('.content').css('background-color');
	        if(!$.mmsIsSafari2())
	            $('#' + unansweredQuestions.join(', #'))
	                .css('background-color', '#ff0')
	                .animate({ backgroundColor: defaultBackground }, 1000);
	    }
	}
	else
	    setTimeout(function() { vote(e); }, 250);
};

var showResults = function(poll, showNewUserLink) {
    var totalVotes = 0;
    $.each(results[0], function() { totalVotes += this });
    poll.find('.responses').text('(' + totalVotes + ' responses)');
	
    var speed = 750;
    var pcts = poll.find('.pct');
    var bars = poll.find('.bar');
	
    $('.resultBar').show();
    var startWidth = bars.width();
    $('.resultBar').hide();
	
    bars.width(0);
	
    var flatResults = [];
    $.each(results, function() { flatResults = flatResults.concat(this); });
	
	if(showNewUserLink)
	    poll.find('.content').append(
            $('<p class="newUser">New user? Click here to vote!</p>')
            .click(function() { poll.replaceWith(processPoll(pollData)); }));
	
	poll.find('input').attr('disabled', 'disabled');
    poll.find('.vote').mmsFadeHide(speed / 4);
    poll.find('.resultBar').mmsFadeShow(speed, function() {
    	pcts.add(bars).fadeIn(speed);
	    pcts.each(function(i) {
	        var pct = Math.round(flatResults[i] / totalVotes * 100)
		    $(this).text(pct + '%'); 
	    });
	    bars.each(function(i) {
		    $(this).animate({ 
		        'width': parseInt(flatResults[i] / totalVotes * startWidth)
		    }, speed); 
	    });
	    poll.find('.thanks, .responses, .newUser').mmsFadeShow(speed);
	    poll.find('.resultBar').css('width', '100%');
    });
};

var eventTag = function(ev, imgYear) {
    var eventString = 'ev=' + ev;
    if(imgYear)
        eventString += '&year=' + imgYear;

    ntptEventTag(eventString);
}