/**
 * Contact Us form validation and submit
 */
$j(document).ready(function(){
	var validate = {
		// RFC 2822 validation from http://www.regular-expressions.info/email.html
		email: new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"),
		subject: new RegExp("^(?!invalid).*$"),
		os: new RegExp("^(?!invalid).*$"),
		browser: new RegExp("^(?!invalid).*$"),
		questionscomments: new RegExp("^.+$")
	};
	
	// capture the submit link
	$j('#contactus-submit').click(function(){
		$j('#contactus').trigger('submit');
		return false;
	});

	$j('#contactus').submit(function(e){
		// validate user entry
		console.log('start form validation...');
		var validated = true, contact = $j(this);
		for (el in validate) {
			if (!validate[el].test($j('*[name='+el+']').val())) {
				$j('#'+el+'Error').show();
				validated = false;
				console.error(el+': invalid!');
			} else {
				$j('#'+el+'Error').hide();
				console.warn(el+': valid!');
			}
		}
		console.log('validated: '+validated);
		if (validated) {
			function sendFailed() {
				$j('#contactus-working').hide();
				contact.hide();
				$j('#contactus-generalerror').show();
			}
			//$j('#contactus').ajaxForm({
			$j.ajax({
				url: contact.attr('action'),
				data: contact.serialize(),
				beforeSend: function(){
					console.log('begin ajax request');
					// set the spinner height to the form height, and dim the form while you're at it
					var height = contact.css('opacity',.5).height();
					$j('#contactus-working').height(height).show();
					$j('#contactus-success').height(height);
					$j('#contactus-generalerror').height(height);
				},
				error: sendFailed,
				success: function(response){
					console.log(response);
					if (response == 'email_sent:successful') {
						contact.hide();
						$j('#contactus-working').hide();
						$j('#contactus-success').show();
					} else {
						sendFailed();
					}
				}
			})
		}
		// reset the bottom corners for IE
		$j('.nested-gradient-content-footer').css('bottom','0');
		return false;
	});
});