$(document).ready(function() {
	// Reset Form
	$('form :reset').click(function(e) {
		var parent = $(this).closest("form");
		$('.invalid', parent).removeClass("invalid"); // Remove the error highlighting
		$('p.status', parent).html(""); // Remove the error message
	});
	
	// Handle Form Submits using AJAX
	$('form :submit').click(function(e) {  
		var parent = $(this).closest("form");
		
		var submitString = "redirect=false";
		$('input[type!="submit"][type!="button"], textarea', parent).each(function() {
			submitString += "&" + $(this).attr('name') + "=" + $(this).val();
		});
		
		$('select', parent).each(function() {
			submitString += "&" + $(this).attr('name') + "=" + $(':selected', $(this)).val();
		});
		
		// Perform validation
		var validates = true;
		
		var clearInvalid = function(obj) {
			$(obj).removeClass("invalid"); // Remove the error highlighting
			$('p.status', parent).html(""); // Remove the error message
		};
		
		$('.required', parent).each(function() {
			// If the user hasn't provided an answer
			if($(this).val() == "" || $(this).val() == "-- SELECT --") {
				validates = false;
				$(this).addClass("invalid");
				
				var tag = $(this).attr('tagName').toLowerCase();       
						 
				if(tag == "select") { // Input is a select drop down and therefore should clear on the changing of the selection
					$(this).change(function() {
						clearInvalid($(this));
					});
				} else { // Input is text based, and therefore should clear on key press
					$(this).keypress(function() {
						clearInvalid($(this));
					});
				}
			}
		});
		
		// Perform the AJAX Request
		if(validates) {
			$(this).attr('disabled','disabled'); // Disable the button to stop them from clicking it multiple times
			$('.field input, .field textarea, .field select', parent).attr('disabled','disabled'); // Disable all of the fields in the form
			$('p.status', parent).html("<img class='sending' src='http://www.iview.com.au/ahm/iview2010/images/loading.gif' alt='Sending!' /><span class='sending'>Sending...</span>");
			
			$.ajax({  
				type: "POST",  
				url: "ProcessForm.aspx",  
				data: submitString,  
				success: function(msg) {
					$('p.status', parent).html("");
					$('p.result', parent).html(msg);
					$('p.result', parent).fadeIn("slow");
					$('.field', parent).hide();
					$('.button_container', parent).hide();
					$('.intro').hide();
					$('#request_quote_success').show();
					setInterval(function() {
						location.reload();
					}, 5000);
				}  
			});
		} else {
				
			$('p.status', parent).html("<img src='http://www.iview.com.au/ahm/iview2010/images/error.png' alt='Error!' /><span class='error'>One or more required fields are missing!</span>");
		}
		e.preventDefault();        
	}); 
});
