function checkEmail(email) {	
	var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var emailVal = $("#" + email).val();
	return pattern.test(emailVal);
}

$(function() {
	$("#CampaignSuite input:submit").click(function() {
		// First, disable the form from submitting
		$('form#CampaignSuite').submit(function() { return false; });
		
		// Grab form action
		var formAction = $("form#CampaignSuite").attr("action");
		
		// Hacking together id for email field
		// Replace the xxxxx below:
		var id = "uthjjr";
		var emailId = id + "-" + id;
		
		// Validate email address with regex
		if (!checkEmail(emailId)) 
		{
			alert("Please enter a valid email address");
			return;
		}
		
		// Serialize form values to be submitted with POST
		var str = $("form#CampaignSuite").serialize();
		
		// Add form action to end of serialized data
		// CDATA is used to avoid validation errors
		//<![CDATA[
		var serialized = str + "&action=" + formAction;
		// ]]>
		
		if($("#CampaignSuite input[name=cm-fo-irvkd[]]:checked").length <= 0) {
			alert('Please select at least one subscription list to continue.');
			return;
		}
		
		if(!$("#privacy").attr('checked')) {
			alert('Please agree to our Privacy Policy.');
			return;
		}
		
		$('#submit_button').css('display', 'none');
		$('#submitting').css('display', 'block');
		
		// Submit the form via ajax
		$.ajax({
			url: "campaignsuite/CampaignSuite.php",
			type: "POST",
			data: serialized,
			success: function(data){
				// Server-side validation
				if (data.search(/invalid/i) != -1) {
					alert('The email address you supplied is invalid and needs to be fixed before you can subscribe to this list.');
					$('#submit_button').css('display', 'block');
					$('#submitting').css('display', 'none');
				} else {
					$("#CampaignSuite").slideUp('slow'); // If successfully submitted hides the form
					
					$("#confirmation").append('<ul></ul>');
					
					$.each($("#CampaignSuite input[name=cm-fo-irvkd[]]:checked"), function(i, obj) {
						var id = 'cm' + $(obj).val();
						var label = $('label[for=' + id + ']');
						var val = label.text();
						
						$("#confirmation ul").append('<li>'+val+'</li>');
					});
					
					
					$("#confirmation strong").append(' '+$('#name').val() + ' ' + $('#LastName').val());
					
					$("#confirmation").slideDown("slow");  // Shows "Thanks for subscribing" div
					$("#confirmation").tabIndex = -1;
					$("#confirmation").focus(); // For screen reader accessibility
				}
			}
		});
	});
});
