$(document).ready(function() {

	var custom_msg_default = "So there's this site called the Dare Club and I've been having huge fun doing challenging stuff. You should join, it's awesome.";
	
	$('#send').click(function() {
		var friend1 = trim($('#friends_1_email').val());
		var friend2 = trim($('#friends_2_email').val());
		var friend3 = trim($('#friends_3_email').val());
		var msg = trim($('#custom_msg').val());
		if(friend1 == '' && friend2 == '' && friend3 == '') {
			alert('Please enter the email address for at least one friend.');
		} else if(msg == '') {
			if(confirm('Please enter a customized message, or click OK to use the default.')) {
				$('#custom_msg').val(custom_msg_default);
			}
		} else {
			return true;
		}
		return false;
	});

	$('#num_chars').html($('#custom_msg').val().length.toString());
	
	//
	// keyup, keypress, and blur events to limit characters entered in the
	// customized message textarea
	//
	$('#custom_msg').keyup(function() {
		var text = $(this).val();
		var charCount = 0;
		var maxChars = parseInt($('#max_chars').html());
		if($(this).val() != '') {
			charCount = $(this).val().length;
		}
		if(charCount > maxChars) {
			$(this).val(text.substring(0, maxChars));
			charCount = maxChars;
		}
		$('#num_chars').html(charCount.toString());
	});
	$('#custom_msg').keypress(function() { 
		$(this).trigger('keyup');
	});
	$('#custom_msg').blur(function() { 
		$(this).trigger('keyup');
	});
	
	//
	// keyup, keypress, and blur events to show friends email addresses as they
	// are typed in
	//
	$('.friend').keyup(function() {
		var friend1 = trim($('#friends_1_email').val());
		var friend2 = trim($('#friends_2_email').val());
		var friend3 = trim($('#friends_3_email').val());
		var emailList = '';
		if(friend1 != '') {
			
			emailList = friend1;
		}
		if(friend2 != '') {
			if(emailList == '') {
				emailList = friend2;
			} else {
				emailList += ', ' + friend2;
			}
		}
		if(friend3 != '') {
			if(emailList == '') {
				emailList = friend3;
			} else {
				emailList += ', ' + friend3;
			}
		}
		$('#to_email').html(emailList);
	});
	$('.friend').keypress(function() { 
		$(this).trigger('keyup');
	});
	$('.friend').blur(function() { 
		$(this).trigger('keyup');
	});
	
});