$(document).ready(function() {
	
	var name;
	var email;
	
	$('#focused').submit(function() {
		var submitButton = ('#submit');
		$('div.error').hide();
		$('input.error, select.error').removeClass('error');
		
		$.ajax({
			url: 'resources/php/focusedApp.php',
			type: "POST",
			data: ({
		    	name: $('#name').val(),
		    	company: $('#company').val(),
		    	phone: $('#phone').val(),
		    	email: $('#email').val(),
		    	details: $('#details').val(),
				ajax: 'true',
				submit: 'submit'
			}),
		    dataType: 'json',
		    
		    // Before we send the AJAX request
		    beforeSend: function() {
				$(submitButton).attr({
					value: 'processing...',
					disabled: 'disabled'
				});
			},
			
			// If the AJAX call is successful
			success: function(data){
				
				var hasError = false;
				
				for(key in data) {
					var name = data[key]['name'];
					var error = data[key]['error'];
		        	
					if (error != null) {
						var input = $('#' + name);
						hasError = true;
						$(input).addClass('error');
						$(input).siblings('.error').html(error).hide().slideDown('slow');
					}
				}
				
				// If we found an error
		        if (hasError == true) {
		        	var errorMessage = 'There was a problem with your application. Please correct all errors above.';
					$('#results').html(errorMessage).addClass('error').slideDown('slow');
				}
		        // If we did not find an error
		        else {
		        	var successMessage = 'Dear ' + data.value + ',<br/>Your FOCUSed application was successful.<br/>Thanks,<br/>The CROWNWeb Team';
		        	$('form').slideUp('slow', function() {
						$('#results').html(successMessage).addClass('success').slideDown('slow');
					});
		        	//alert();
				}
			},
			
			// After the AJAX is complete (either on error or success)
			complete: function() {
				$(submitButton).attr({
					value: 'Send Application',
					disabled: ''
				});
			}
		});
		
		
		return false;
	});
	
});
