// validation helper function
function validEmail(inputvalue){	
	var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	return pattern.test(inputvalue);
}

// on document ready
$( function() {
	// set up pretty corners
	$('#property-info').corner({
		tl: { radius: 16 },
		tr: { radius: 16 },
		bl: { radius: 16 },
		br: { radius: 16 },
		antiAlias: true,
		autoPad: true});
	$('#property-images').corner({
		tl: { radius: 8 },
		tr: { radius: 8 },
		bl: { radius: 8 },
		br: { radius: 8 },
		antiAlias: true,
		autoPad: true});
	$('#site-info').corner({
		tl: { radius: 5 },
		tr: { radius: 5 },
		bl: { radius: 5 },
		br: { radius: 5 },
		antiAlias: true,
		autoPad: true});
	$('#slideshow').cycle({ 
		fx: 'fade', 
		pause: 1 
	});

	// initialize "modal" contact dialog
	$('#contact-dialog').jqm({modal: false, trigger: 'a#contact-link'});

	// hijack form submission for JS validation
	$("#contact-form").bind("submit", function(event){
		event.preventDefault();
		var problem = false;
		if ( $('#name').val() == "" ) {
			$('#name_error').show();
			problem = true;
		} else {
			$('#name_error').hide();
		}
		if ( $('#email').val() == "" ) {
			$('#email_error').show();
			$('#valid_email_error').hide();
			problem = true;
		} else if ( ! validEmail($('#email').val()) ) {
			$('#valid_email_error').show();
			$('#email_error').hide();
			problem = true;
		} else {
			$('#email_error').hide();
			$('#valid_email_error').hide();
		}
		if ( $('#message').val() == "" ) {
			$('#message_error').show();
			problem = true;
		} else {
			$('#message_error').hide();
		}
		if ( ! problem ) {
			// collect data
			var contact_data = $("#contact-form").serialize();
			// hide form
			$("#contact-form").hide();
			$("#ajax-loader").show();
			//submit form
			$.ajax({
				type: "POST",
				url: "/mvv/send_email.asp",
				data: contact_data,
				dataType: "json",
				success: function(data,textStatus){
					var status = data.sent;
					if ( status == "True" ) {
						$("#ajax-loader").hide();
						$("#contact-success").show();
						// clean form values
						$('#name').val("");
						$('#email').val("");
						$('#message').val("");
					} else {
						$("#ajax-loader").hide();
						$("#contact-error").show();
						$("#contact-form").show();
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					if (textStatus == 'timeout') {
						$("#ajax-loader").hide();
						$("#network-error").show();
					} else {
						$("#ajax-loader").hide();
						$("#other-error-reason").text('Problem sending message: ' + textStatus + ' - ' + errorThrown)
						$("#other-error").show();
					}
					$("#contact-form").show();
				}
			});
			return false;
		}
		return false;
	});
});
