/*********************************************\
|* Poll                                      *|
|* Copyright (c) 2007 Werner BEROUX          *|
|*                                           *|
|* Web: http://www.beroux.com/               *|
\*********************************************/

// Config
var pollServerScript = '/poll.php';
var imagesDir = '/images';
var maxBarWidth = 110;
var zeroBarWidth = 4*2;

function getXhr() {
	var xhr = null; 
	
	if (window.XMLHttpRequest) // Firefox and Opera
		xhr = new XMLHttpRequest(); 
	else if (window.ActiveXObject) { // Internet Explorer 
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	else { 
		alert("AJAX is not supported by your browser."); 
		xhr = false; 
	}
	return xhr;
}

var pollXmlResponse;

function displayPoll(pollID, lang) {
	var xhr = getXhr();
	
	document.write('<div id="poll'+pollID+'"></div>');
	
	xhr.onreadystatechange = function() {
		updatePoll(pollID, lang, xhr);
	}
	xhr.open("POST", pollServerScript, true);
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr.send("poll_id="+pollID+"&lang="+lang);
}

function sendVote(pollID, lang, answers) {
	// Find the checked answer
	var answerID = -1;
	for (var i=0; i<answers.length; i++) {
		if (answers[i].checked) {
			answerID = parseInt(answers[i].value);
			break;
		}
	}
	
	// No answer checked?
	if (answerID == -1) {
		alert("Please select an answer first.");
		return;
	}
	
	// Send the vote
	var xhr = getXhr();
	xhr.onreadystatechange = function() {
		updatePoll(pollID, lang, xhr);
	}
	xhr.open("POST", pollServerScript, true);
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr.send("poll_id="+pollID+"&lang="+lang+"&votefor="+answerID);

	// Display the result
	showPollResult(pollID, lang, pollXmlResponse, answerID);
}

function updatePoll(pollID, lang, xhr) {
	// Info received?
	if (xhr.readyState == 4 && xhr.status == 200) {
		// Invalid reply? Display it
		if (xhr.responseXML == null)
		{
			document.getElementById('poll'+pollID).innerHTML = xhr.responseText;
		}
		else
		{
			// Read the response
			pollXmlResponse = xhr.responseXML.documentElement;
			var userHasVoted = pollXmlResponse.getElementsByTagName("user_voted")[0].firstChild.nodeValue == 'true';
			if (userHasVoted)
				showPollResult(pollID, lang, pollXmlResponse, -1);
			else
				showPollQuestions(pollID, lang, pollXmlResponse);
		}
	}
}

function showPollQuestions(pollID, lang, xmlResponse) {
	// Read the response
	var title = xmlResponse.getElementsByTagName("title")[0].firstChild.nodeValue;
	var xmlAnswers = xmlResponse.getElementsByTagName("answer");

	// Update the HTML
	var html =	'<form class="poll">' +
					'<div class="poll_title"><strong>' + title + '</strong></div>' +
					'<table class="poll_answer" border="0">';
	// Display the poll's answer proposal
	for (i=0; i<xmlAnswers.length; ++i)
	{
		var answerID = xmlAnswers[i].attributes[0].nodeValue;
		var answerCaption = xmlAnswers[i].getElementsByTagName("caption")[0].firstChild.nodeValue;
		html +=		'<tr>' +
						'<td valign="top"><input type="radio" id="poll_answer_'+answerID+'" name="answer" value="'+answerID+'" /></td>' +
						'<td><label for="poll_answer_'+answerID+'">'+ answerCaption + '</label></td>' +
					'</tr>';
	}
	html +=			'</table>';
		
	// Vote button
	var vote
	var result;
	var showPollResults;
	if (lang == 'fr') {
		vote = 'Voter';
		result = 'R&eacute;sultats';
		showPollResults = 'Voir les r&eacute;sulats du sondage';
	}
	else {
		vote = 'Vote';
		result = 'Results';
		showPollResults = 'Show poll results';
	}
	html +=			'<div class="poll_vote"><input type="button" value="'+vote+'" onclick="javascript:sendVote('+pollID+', \''+lang+'\', this.form.answer);"></div>' +
					'<div class="poll_show_result"><a href="javascript:showPollResult('+pollID+', \''+lang+'\', pollXmlResponse, -1);" title="'+ showPollResults +'">'+result+'</a></div>' +
				'</form>';
	document.getElementById('poll'+pollID).innerHTML = html;
}

function showPollResult(pollID, lang, xmlResponse, votedAnswerID) {
	// Read the response
	var userHasVoted = xmlResponse.getElementsByTagName("user_voted")[0].firstChild.nodeValue == 'true';
	var title = xmlResponse.getElementsByTagName("title")[0].firstChild.nodeValue;
	var xmlAnswers = xmlResponse.getElementsByTagName("answer");

	// Update the HTML
	var html =	'<form class="poll">' +
					'<div class="poll_title"><strong>' + title + '</strong></div>';
	// Display the poll's result
	var maxVotes = 0;
	var totalVotes = 0;
	for (i=0; i<xmlAnswers.length; ++i)
	{
		var answerID = parseInt(xmlAnswers[i].attributes[0].nodeValue);
		var answerVotes = parseInt(xmlAnswers[i].getElementsByTagName("votes")[0].firstChild.nodeValue);
		if (answerID == votedAnswerID)
			++answerVotes;
		if (answerVotes > maxVotes)
			maxVotes = answerVotes;
		totalVotes += answerVotes;
	}
	for (i=0; i<xmlAnswers.length; ++i)
	{
		var answerID = parseInt(xmlAnswers[i].attributes[0].nodeValue);
		var answerCaption = xmlAnswers[i].getElementsByTagName("caption")[0].firstChild.nodeValue;
		var answerVotes = parseInt(xmlAnswers[i].getElementsByTagName("votes")[0].firstChild.nodeValue);
		if (answerID == votedAnswerID)
			++answerVotes;
		html +=		'<div class="poll_answer">'+answerCaption+'</div>';
		html +=		'<div class="poll_result">'+voteBar(answerVotes, maxVotes, totalVotes)+'</div>';
	}
	html +=		'<div align="right">Total Votes: '+totalVotes+'</div>';
	html +=		'</form>';
	document.getElementById('poll'+pollID).innerHTML = html;
}

function voteBar(votes, maxVotes, totalVotes) {
	var percents;
	var width;
	if (totalVotes == 0) {
		percents = 0;
		width = 0;
	}
	else {
		percents = Math.round(votes * 100 / totalVotes);
		width = Math.round(votes * maxBarWidth / maxVotes) - zeroBarWidth;
	}
	var lcap = '<img src="'+imagesDir+'/vote_lcap.gif" alt="" height="12" width="4">';
	var rcap = '<img src="'+imagesDir+'/vote_rcap.gif" alt="" height="12" width="4">';
	var bar = '';
	if (width > 0) {
		bar = '<img style="width: ' + width + 'px; height: 12px;" src="'+imagesDir+'/voting_bar.gif" alt="'+percents+'% [&nbsp;'+votes+'&nbsp;]" height="12" width="' + width + '" title="'+percents+'% [&nbsp;'+votes+'&nbsp;]">';
	}
	return lcap + bar + rcap + '&nbsp;<strong>'+percents+'%</strong>';
}
