var votingStripe = null;
var canVote = true;
var MAX_STARS = 5;
var mustRestoreStars = false;

function setStars_(stripe, vote)
{
	for(var i=0; i<MAX_STARS; i++)
	{
		var starImage = 'star_off';
		if(i < vote && i + 1 > vote)
		{
			starImage = 'star_half';
		}
		else if(i < vote)
		{
			starImage = 'star_on';
		}
		
		document.images['star_' + stripe + '_' + i].src = 'images/' + starImage + '.gif';
	}
}

function restoreStars(stripe, vote)
{
	if(canVote || mustRestoreStars)
	{
		mustRestoreStars = false;
		
		setStars_(stripe, vote);
	}
}

function voteOver(stripe, vote)
{
	if(canVote)
	{
		setStars_(stripe, vote);
	}
}

function voteStripe(stripe, vote)
{
	if(canVote)
	{
		if(votingStripe == null)
		{
			votingStripe = stripe;
			
			var paramString = 'stripe=' + stripe +
				'&vote=' + vote
			;
			
			makeHTTPRequest(
				appBaseUrl + "async.php?page=voteStripe&" + paramString,
				'GET',
				null,
				voteOk,
				voteError
			);
		}
		else
		{
			voteInfo(stripe, "You're voting another tartan right now.");
		}
	}
	return false;
}

function voteInfo(stripe, text)
{
	$('vote_info_' + stripe).innerHTML = text;
	
	self.setTimeout(
		function(){resetVoteInfo(stripe);},
		5000
	);
}
function resetVoteInfo(stripe)
{
	$('vote_info_' + stripe).innerHTML = '';
}

function voteOk(req)
{
//	canVote = false;
	
	var responseCode = req.responseText;
	
	if(responseCode == "VOTED")
	{
		mustRestoreStars = true;
		
		voteInfo(votingStripe, "You can vote each tartan once a week.");
	}
	else if(responseCode == "LOGIN")
	{
		mustRestoreStars = true;
		
		voteInfo(votingStripe, "You must login to vote tartans.");
	}
	else if(responseCode == "NO")
	{
		mustRestoreStars = true;
		
		//other problems
	}
	else
	{
		$('stripe_vote_' + votingStripe).innerHTML = responseCode;
		
		voteInfo(votingStripe, "Vote submitted.");
		
		mustRestoreStars = false;
	}
	votingStripe = null;
}
function voteError()
{
	alert("Connection error. Please retry later.");
	
	votingStripe = null;
}