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);
}

jQuery(function($) {
	$.footnoteLinks();
	$('#branding').supersleight();
	if ( $('.section.main .figure:first img').length > 1 ) {
		$('.section.main .figure:first')
			.append( $('<a id="prev" href=""></a>').click(function(){return false;}) )
			.append( $('<a id="next" href=""></a>').click(function(){return false;}) )
			.cycle({
				timeout:       10000,  // milliseconds between slide transitions (0 to disable auto advance) 
			  speed:         1000,  // speed of the transition (any valid fx speed value) 
			  next:          '#next',  // id of element to use as click trigger for next slide 
			  prev:          '#prev',  // id of element to use as click trigger for previous slide 
			  height:       '428px', // container height 
			  sync:          1,     // true if in/out transitions should occur simultaneously 
			  pause:         true,     // true to enable "pause on hover" 
			  slideExpr:     'img'  // expression for selecting slides (if something other than all children is required)     
			});
	};

	$('#newsletter-signup form').submit(function(event) {	
		event.preventDefault();

		var $this = $(this);

		// Grab form action
		var form_act = $this.attr('action');
		
		// Hack together id for email field
		emailId = form_act.replace("http://mailer.deepcalm.com/t/r/s/", "");
		emailId = emailId.replace("/", "");
		emailId = emailId + "-" + emailId;
		
		// 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 = $this.serialize();
		
		// Add form action to end of serialized data
		final = str + "&action=" + form_act;
		
		$this.parent().addClass('working');
		
		// Submit the form via ajax
		$.ajax({
			url: "/proxy.php",
			type: "POST",
			data: final,
			success: function(html){
				// If successfully submitted hides the form
				$this
					.slideUp('medium')
					.parent().removeClass('working').end()
					.replaceWith('<p>Thanks for subscribing!</p>')
					.slideDown('medium');
				}
			}
		);

		// disable the form from submitting
		// return false;
	});

});
