// 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;

// 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;
		//alert(pollId);
//		var polls = "http://polls.bauerpublishing.com/superpoll.php?pid="+pollId+"&jsoncallback=?";
		var polls = "http://superpoll/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) {
	//alert("injecting: " + data);
	var link = false;
	if ((!saveInfoInCookies) || ($.cookie(data.pid)!='true')){ link = true; }
	var html = "<div id=\""+data.pid+"\"><p>"+data.question+"</p><div class=\"option\">";
	if (link){ html += "<a href='javascript:vote(\""+data.pid+"\","+0+")' id='"+data.pid+"opt0'>"; }
//	html +=	"<img src=\"http://polls.bauerpublishing.com/uploads/"+data.image_1+"\" width=\"90\" height=\"120\" /><br/>"+data.answer_1;
	html +=	"<img src=\"http://polls.bauerpublishing.com/uploads/"+data.image_1+"\" width=\"90\" height=\"120\" /><br/>"+data.answer_1;
	if (link){ html += "</a>"; }
	
	html +=	"</div>";
	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>";
	
	html +=	"<div class=\"option\">";
	if (link){ html += "<a href='javascript:vote(\""+data.pid+"\","+1+")' id='"+data.pid+"opt1'>"; }
	html +=	"<img src=\"http://polls.bauerpublishing.com/uploads/"+data.image_2+"\" width=\"90\" height=\"120\" /><br/>"+data.answer_2;
	if (link){ html += "</a>"; }
	html +=	"</div></div><div class=\"tinyClearBoth\"></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);
	}
	// Make sure the whitespace is actually the right color (it's not always 
		// white!)
		/*
var thisThing = $(this);
		while (true) {
			// Find the background color of this node or its first parent with a 
			// background color set. When you find it, set the background color of the
			// whitespace to be the same color
			var color = $(thisThing).css("background-color");
			if (color.search('rgb') >= 0) {
				$(this).find('.ws').css("background-color", color);
				$(this).find('.result .label').css("background-color", color);
				break;
			} 
			else {
				// Didn't find it - if there's a parent above this, try that. Otherwise, we're white
				if ($(thisThing).parent().length != 0) thisThing = $(thisThing).parent().get(0);
				else break;
			}
		}
*/
}

function injectMultiPoll(divObj, data){
	var link = false;
	if ((!saveInfoInCookies) || ($.cookie(data.pid)!='true')){ link = true; }
	var html = "<div id=\""+data.pid+"\"><p>"+data.question+"</p><div class=\"option\">";
	if (link){
		jQuery.each(data.results, function(curr_idx, curr_question){
			html += "<a href='javascript:vote(\""+data.pid+"\","+curr_question.answer_id+")' id='"+data.pid+"opt"+curr_question.answer_id+"'>"; 
			html +=	curr_question.answer + "</a>" + "<br />";
		});
	}
	else{ html += "<h3>You've already voted in this poll.  Thanks!</h3>"; }
	html +=	"</div></div><div class=\"tinyClearBoth\"></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("http://superpoll/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).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});
	});
}
