$(function() {
	$(".poll a.vote").parents("form").submit(function() {
		var allPollsVoted = true;
		var polls = $("ul.poll", $(this));
		if ( $("input[name=email]", $(this)).length ) {
			var email = $("input[name=email]", $(this)).val();
			var emailRE = new RegExp("(^|[^\"'=\\[>:a-zA-Z0-9\\-_\\.])([a-zA-Z0-9\\-_\\.]+@([a-zA-Z0-9\\-]+\\.)+[a-zA-Z0-9\\-]+)");
			if ( ! email.match(emailRE) ) {
				alert("Please fill in the email field with a valid email address.\n\nWe need to send you an email so you can confirm your vote.");
				return false;
			}
		}
		$(polls).each(function() {
			allPollsVoted = allPollsVoted && ( $("input[name=answer]", $(this)).length > 0 );
		});
		if ( !allPollsVoted ) {
			if ( $(polls).length == 1 ) {
				alert("You haven't voted yet!");
			} else {
				alert("You haven't registered a vote for each question yet!");
			}
		}
		return allPollsVoted;
	});
	
	$(".poll a.vote").click(function(e) {
		e.preventDefault();
		var form = $(this).parents("form");
		var pollIdInput = $("input[name=pollId]", $(form));
		var pollId = 0;
		if ( $(pollIdInput).length ) {
			pollId = $(pollIdInput).val();
		}
		var isSinglePoll = $("ul.poll", $(form)).length == 1;
		var isValidatedByEmail = $("input[name=email]", $(form)).length > 0;
		var hasSuggestionBox = $("input[name=suggestionBox]", $(form)).length > 0;
		var rel = $(this).attr("rel").split(";");
		var question = rel[0].split("=")[1];
		var answer = rel[1].split("=")[1];
		var maxAnswers = rel[2].split("=")[1];
		if ( maxAnswers == null || maxAnswers.length == 0 ) {
			maxAnswers = 1;
		} else {
			maxAnswers = parseInt(maxAnswers);
		}
		var numAnswers = $("input[name=answer]", $(this).parents("ul")).length;
		if ( numAnswers == maxAnswers ) {
			alert("You can only vote for " + maxAnswers + ".");
		} else {
			var voteElement = $('<input type="hidden" name="answer" value="' + answer + ';' + question + '"/>');
			$(this).append($(voteElement));
			
			if ( isSinglePoll && question == pollId && maxAnswers == 1 && ! isValidatedByEmail && ! hasSuggestionBox ) {
				$(form).submit();
			} else {
				var voteLink = $(this);
				$(voteLink).hide();
				var removeVoteLink = $('<a href="#" class="vote voted">Remove Vote</a>');
				$(removeVoteLink).click(function(e) {
					e.preventDefault();
					$(removeVoteLink).remove();
					$(voteElement).remove();
					$(voteLink).show();
				});
				$(voteLink).after($(removeVoteLink));
			}
		}
		return false;
	});
});
