(function($){
	
	var  showInvalidField  = function (field) {
		field.css({backgroundColor: 'red', color: 'white'});
		
		field.bind('blur', function(){
			var that = $(this);
			if (that.val().length > 0) {
				that.css({backgroundColor: 'white', color: 'black'});
			}
		});
		
	};

	$('.contact').fancybox({
		titleShow: false,
		scrolling: false,
		overlayOpacity: .95
	});

	$('#contact-form').submit(function(e){

		e.preventDefault();
		
		var fields = $('input[data-required=true], textarea[data-required=true]', this),
			valid = true,
			form = $(this)
		;

		fields.each(function(){

			var that = $(this);

			if (that.val().length === 0) {
				showInvalidField(that);
				valid = false;
			}
			
		});

		if (valid) {

			$.fancybox.showActivity();
			
			$.ajax({
				type: 'post',
				url: 'index_post2.php',
				data: form.serializeArray(),
				success: function(data){
					var result = $.parseJSON(data);
					
					if(result.status === 'success') {
						$.fancybox('<h3>Thank You!</h3><p>Your inquiry has been successfully submitted. We will contact you with a resolution as quickly as possible.</p>');
					}
					else if (result.status === 'fail') {
						$.fancybox.hideActivity();
						
						$.each(result.fields, function() {
							showInvalidField($(this));
						});
					}
				},
				cache: false
			});
			
		}	
		
	});


})(jQuery);
	
