// How long should the animation take?
var totalMStoAnimate = 500;
// Should we save that the user has voted on this poll in a cookie?
var saveInfoInCookies = true;
// The maximum height of the result bar is 115px
var totalMaxResultHeight = 115;

//pollServer is defined by the calling page
//var pollServer = "http://poll-stage.bauerpublishing.com";

// On page load, set up the polls
$(document).ready(function() {
	setUpPolls();
});

function setUpPolls() {
	$(".jQueryPoll").each(function (i) {
		// Get the ID on this poll
		var pollId = this.id;
		var polls = pollServer + "/pub/superpoll.php?pid="+pollId+"&jsoncallback=?";
		$.getJSON(polls, function(data){
			jQuery.each(data.polls, function(index, poll){
				if (poll.is_multipoll == 1){ injectMultiPoll(pollId, poll); }
				else{ injectPoll(pollId, poll); }
				$("#"+pollId).html($("#"+pollId).html() + "<div class=\"poll-spacer\">&nbsp;</div>");
			}); 			
		});
	});	
}


function injectPoll(divObj,data) {
	var link = false;
	if ((!saveInfoInCookies) || ($.cookie(data.pid)!='true')){ link = true; }
	var html = "<div class='poll_box' id=\""+data.pid+"\"><div class='top'></div>";
	html += "<div class='mid'><div class='mid_inside pic'>";
	html += "<div class='pic_question'>"+data.question+"</div>";
	
	/*Question One*/
	if (data.image_1 || data.image_2){
		html += "<div class='pic_answer'>";
		html += "<div class='pic_pic one'>";
		if (link){ html += "<a href='javascript:vote(\""+data.pid+"\","+0+")' id='"+data.pid+"opt0'>"; }
		html +=	"<img src=\""+pollServer+"/uploads/"+data.image_1+"\" width=\"90\" height=\"120\" class=\"option\" />";
		if (link){ html += "</a>"; }
		html +=	"</div>";
	}
	else{
		html += "<div class='nopic_answer'>";
	}
	html += "<ul><li class='option'>";
	if (link){ html += "<a href='javascript:vote(\""+data.pid+"\","+0+")' id='"+data.pid+"opt0'>"; }
	html += data.answer_1;
	if (link){ html += "</a>"; }
	html += "</li></ul></div>";

	/*Poll results area*/
	html +=	"<div class='pollResultArea' >";
	html += "<div class='result' id='"+data.pid+"res0'><div class='ws'>&nbsp;</div><div class='label'>&nbsp;</div></div>";
	html += "<div class='between'>&nbsp;</div>";
	html += "<div class='result' id='"+data.pid+"res1'><div class='ws'>&nbsp;</div><div class='label'>&nbsp;</div></div>";
	html += "</div>";
	
	/*Question two, I am going to programmer hell for not DRYing this up*/
	if (data.image_1 || data.image_2){
	 	html += "<div class='pic_answer'>";
		html += "<div class='pic_pic two'>";
		if (link){ html += "<a href='javascript:vote(\""+data.pid+"\","+1+")' id='"+data.pid+"opt0'>"; }
		html +=	"<img src=\""+pollServer+"/uploads/"+data.image_2+"\" width=\"90\" height=\"120\" class=\"option\" />";
		if (link){ html += "</a>"; }
		html +=	"</div>";
	}
	else{
		html += "<div class='nopic_answer'>";
	}
	html += "<ul><li class='option'>";
	if (link){ html += "<a href='javascript:vote(\""+data.pid+"\","+1+")' id='"+data.pid+"opt0'>"; }
	html += data.answer_2;
	if (link){ html += "</a>"; }
	html += "</li></ul></div>";
	
	html += "</div></div><div class='bot'></div>";


	$("#"+divObj).html($("#"+divObj).html() + html);

	
	if (saveInfoInCookies && ($.cookie(data.pid)=='true')) {
		// Get total votes for both options and possibly total votes for the poll. If
		// the latter are not returned, they can obviously be easily calculated
		var totalOpt1 = parseInt(data.tally_1);
		var totalOpt2 = parseInt(data.tally_2);
		var totalResults = totalOpt1 + totalOpt2;
		
		// Display the results
		displayResults(data.pid, totalOpt1, totalOpt2, totalResults, false);
	}
	
}

function injectMultiPoll(divObj, data){
	var link = false;
	if ((!saveInfoInCookies) || ($.cookie(data.pid)!='true')){ link = true; }
	var html = "<div class='poll_box' id='"+data.pid+"'><div class='top'></div>";
	html += "<div class='mid'><div class='mid_inside'>";
	html += "<div class='pic_question'>"+data.question+"</div>";
	html += "<div class='text_answer_one'>";
	if (link){
		html  += '<ul>';
		jQuery.each(data.results, function(curr_idx, curr_question){
			html += "<li><a href='javascript:vote(\""+data.pid+"\","+curr_question.answer_id+")' id='"+data.pid+"opt"+curr_question.answer_id+"'>"; 
			html +=	curr_question.answer + "</a>" + "</li>";
		});
		html += "</ul>";
	}
	else{ html += "<h3>You've already voted in this poll.  Thanks!</h3>"; }
	html +=	"</div></div></div><div class='bot'></div></div>";

	$("#"+divObj).html($("#"+divObj).html() + html);

}



// Vote for an element in a poll. This function call is inserted by the set up 
// utility above
// Note: AJAX calls will have to be added when that's ready to be implemented
function vote(pollId, idx) {
	//TODO: decide whether to show results or not!
	$.getJSON(pollServer + "/pub/superpoll.php?jsoncallback=?",
						{"pid": pollId, "action": "doVote", "cid": idx},
						function(data){ 
							if (typeof data.polls != 'undefined'){
								if (data.polls.tally_1){
									var totalOpt1 = parseInt(data.polls.tally_1);
									var totalOpt2 = parseInt(data.polls.tally_2);
									var totalResults = totalOpt1 + totalOpt2;
									
									// Display the results
									displayResults(pollId, totalOpt1, totalOpt2, totalResults, true);
									
									// Make this poll unclickable
									$("#"+pollId+" .option a").removeAttr("href");
								}
							}
							else{
								$("#"+pollId+" .text_answer_one").html("<h3>Your vote has been recorded.  Thanks!<h3>");
							}
							// If we're cookie-ing, we should save that the person already answered this
							// poll
							if (saveInfoInCookies) $.cookie(pollId, 'true', {expires:1000});
 						});
	
}


// Displays results
// Note: I have assumed that the data will already have been retrieved by the
// time this funciton is called. However, it can easily be modified to get the 
// data to display, if necessary
function displayResults(pollId, totalOpt1, totalOpt2, totalResults, animate) {
	// What percentage of people voted for each option?
	perc1 = totalOpt1 / totalResults;
	perc2 = totalOpt2 / totalResults;

	// Set the label
	$("#"+pollId+"res0 .label").html(Math.round(perc1*100)+"%");
	$("#"+pollId+"res1 .label").html(Math.round(perc2*100)+"%");
	
	if (animate) {
		// Animate the bar up up up
		$("#"+pollId+"res0 .ws").animate({
			height: Math.round(totalMaxResultHeight*perc2)+"px"
		}, totalMStoAnimate);
		$("#"+pollId+"res1 .ws").animate({
			height: Math.round(totalMaxResultHeight*perc1)+"px"
		}, totalMStoAnimate);
	}
	else {
		// Just set it, no animation necessary
		$("#"+pollId+"res0 .ws").css("height",Math.round(totalMaxResultHeight*perc2)+"px");
		$("#"+pollId+"res1 .ws").css("height",Math.round(totalMaxResultHeight*perc1)+"px");
	}
}


// For testing, this will clear cookies
function clearCookies() {
	$(".jQueryPoll").each(function (i) {
		$.cookie(this.id, 'false', {expires:1000});
	});
}

