/*
	Barb Hadlow:	
	03/06/2009
	Tony Milne (Inlight Media)
*/

$(document).ready(function() {	
	contact_labels();
	contact_validation();
});

var NAME_LABEL = "Name:";
var CONTACT_LABEL = "Phone or Email:";
var MESSAGE_LABEL = "Message:";

/** 
 * Helper to set up the form fields with their default label and
 * removes the label on click, and adds it back if it's empty on blur.
 */
function set_up_contact_field(field_id, label) {
	var field_selector = "#"+field_id;
	$(field_selector).val(label);
	$(field_selector).click(function() {
		if ($(this).val() == label) { 
			$(this).val(""); 
		}
	}).blur(function() {
		if ($(this).val() == "") { 
			$(this).val(label); 
		}		
	});	
}

/** 
 * Helper to add custom required validation methods which check if the field is 
 * either empty or the default label.
 */
function add_validation_method(field_id, label, msg) {	
	jQuery.validator.addMethod(field_id + "_required", function(value, element) { 				
  			return !((value.length == 0) || (value == label)); 
		}, msg);		
}

function contact_labels() {
	set_up_contact_field("txtName", NAME_LABEL);
	set_up_contact_field("txtContact", CONTACT_LABEL);
	set_up_contact_field("txtMessage", MESSAGE_LABEL);
}

function contact_validation() {
	// Set ajax variable to avoid sending the page contents back after form submission.
	$("#ajax").val("true");		
	$("#validation").hide();
	
	$("#contactForm").validate({							   
		submitHandler: function(form) {
			$("#contactForm").ajaxSubmit(function(result) {	
				if (result == "true") {			
					// Remove the form components.
					$("#contact_form_outer").fadeOut(500, function() {	
						// Display the thankyou message.
						$("#thankyou").fadeIn(500);
					});	
				}
				else {
					alert("There was an error sending your message. \r\n Perhaps you could try giving me a call instead.");
				}	
			});
		},		
		invalidHandler: function(form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'You missed 1 mandatory field.'
					: 'You missed ' + errors + ' mandatory fields.';
				
				$("#validation p").text(message);
				$("#validation").show();
			} else {
				$("#validation").hide();
			}
		},					
		rules: {
			txtName: "txtName_required",				
			txtContact: "txtContact_required",			
			txtMessage: "txtMessage_required"		
		}		
	});
	
	// Add custom required validation rules: (validate if empty or inital labels are present).	
	add_validation_method("txtName", NAME_LABEL, "");
	add_validation_method("txtContact", CONTACT_LABEL, "");
	add_validation_method("txtMessage", MESSAGE_LABEL, "");
}