
(function($){
$(document).ready(function() {
	$("#contact-form").submit(function(e) {
		$("#contact-form label.error").removeClass("error");
		var valid = true;
		var required = new Array();
		var invalid = new Array();
		var firstError = null;
		
		var emptyRequired = $("#contact-form .requiredField[value=]");
		if(emptyRequired.size() > 0 ) {
			valid = false;
			$.each(emptyRequired, function() {
				var field = $(this);
				valid = false;
				var lbl = $("label[for='" + field.attr("id") + "']");
				lbl.addClass("error");
				required.push(lbl.attr("errorLabel"));
				
				if(firstError == null) {
					firstError = field;
				}
			});
		}
		
		$(".phoneField").each(function() {
			var field = $(this);
			if(!validatePhoneNumber(field.val())) {
				valid = false;
				var lbl = $("label[for='" + field.attr("id") + "']");
				lbl.addClass("error");
				invalid.push(lbl.attr("errorLabel"));
				
				if(firstError == null) {
					firstError = field;
				}
			}
		});
		
		$(".emailField").each(function() {
			var field = $(this);
			if(!validateEmail(field.val())) {
				valid = false;
				var lbl = $("label[for='" + field.attr("id") + "']");
				lbl.addClass("error");
				invalid.push(lbl.attr("errorLabel"));
				
				if(firstError == null) {
					firstError = field;
				}
			}
		});
		
		if(!valid) {
			e.preventDefault();
			var msg = "<div>";
			
			if(required.length > 0) {
				msg += "The following fields are required:<br /><p class=\"indent\">";
				$.each(required, function(i, lbl) {
					msg += lbl;
					
					if(i < required.length) {
						msg += "<br />";
					}
				});
				msg += "</p>";
			}
			
			if(invalid.length > 0) {
				msg += "The following fields have invalid data:<br /><p class=\"indent\">";
				$.each(invalid, function(i, lbl) {
					msg += lbl;
					
					if(i < required.length) {
						msg += "<br />";
					}
				});
				msg += "</p>";
			}
			
			msg += "</div>";
			var dlg = createDialog("Validation Errors", msg, popupDialogOptions).bind("dialogclose", firstError, function(e) {
				$(e.data).focus();
			}).dialog("option", "dialogClass", "contact-form-submit-validation-dialog");
		}
	});
	
	$(".requiredField").blur(function(e) {
		var field = $(this);
		if(field.hasClass("requiredField") && field.val() != "") {
			var lbl = $("label[for='" + field.attr("id") + "']");
				lbl.removeClass("error");
		}
	});
	
	$(".phoneField").blur(function(e) {
		var field = $(this);
		var val = formatPhoneNumber(field.val());
		var lbl = $("label[for='" + field.attr("id") + "']");
		
		if(validatePhoneNumber(val)) {
			if(!(field.hasClass("requiredField") && field.val() == "")) {
				lbl.removeClass("error");
				field.val(val);
			}
		} else {
			if(!lbl.hasClass("error") && $(".contact-form-submit-validation-dialog").size() == 0) {
				lbl.addClass("error");
				createDialog("Invalid data", "<p>The value entered is not a valid phone number</p>", fieldErrorDialogOptions).bind("dialogclose", field, function(e) {
					$(e.data).focus().select();
				});
			}
		}
	});
	
	function formatPhoneNumber(val) {
		val = val.replace(/[^\d]/g, "").replace(/^1/, "");
		if(val.match(/^\d{10}$/)) {
			val = val.replace(/^(\d{3})(\d{3})(\d{4})$/, "($1) $2-$3");
		}
		
		return val;
	}
	
	function validatePhoneNumber(val) {
		if(val == "") {
			return true;
		}
		
		if(!val.match(/^\(\d{3}\) \d{3}-\d{4}$/)) {
			return false;
		}
		
		return true;
	}
	
	$(".emailField").blur(function(e) {
		var field = $(this);
		var val = field.val();
		var lbl = $("label[for='" + field.attr("id") + "']");
		
		if(validateEmail(val)) {
			if(!(field.hasClass("requiredField") && field.val() == "")) {
				lbl.removeClass("error");
				field.val(val);
			}
		} else {
			if(!lbl.hasClass("error") && $(".contact-form-submit-validation-dialog").size() == 0) {
				lbl.addClass("error");
				createDialog("Invalid data", "<p>The value entered is not a valid email address.</p>", fieldErrorDialogOptions).bind("dialogclose", field, function(e) {
					$(e.data).focus().select();
				});
			}
		}
	});
	
	function validateEmail(val) {
		if(val == "") {
			return true;
		}
			
		// check the length of the components
		if(!val.match(/^.{1,64}@.{4,255}$/)) {
			return false;
		}
		// make sure the first character of the local part is acceptable
		if(!val.match(/^[^\.].*$/)) {
			return false;
		}
		// make sure the first character of the local part is acceptable
		if(!val.match(/^.*[^\.]@.*$/)) {
			return false;
		}
		// make sure the local part contains only valid characters
		if(!val.match(/^[a-zA-Z0-9!#\$%&'\*\+-\/=\?\^_`{|}~\.]+@.*$/)) {
			return false;
		}
		// make sure the domain has at least one period and ends in atleast two characters
		if(!val.match(/^.*@.*\.\S\S*$/)) {
			return false;
		}
		// makes sure that there aren't multiple @ symbols
		if(val.match(/^(.*@.*){2}$/)) {
			return false;
		}
		
		return true;
	}
	
	var popupDialogOptions = {
		modal: true,
		width: 350,
		buttons: {
			"Close": function() {
				$(this).dialog("close").parent(".ui-dialog").empty().remove();
			}
		}
	}
							
	var fieldErrorDialogOptions = {
		modal: true,
		width: 400,
		buttons: {
			"Ok": function() {
				$(this).dialog("close").parent(".ui-dialog").empty().remove();
			}
		}
	}
	
	function createDialog(title, message, options) {
		return $("<div title=\"" + title + "\">" + message + "</div>").dialog(options);
	}
});
})(jQuery);
