// validate.js
//
// Copyright 2007 Elephant's Task LLC
//
// validateForm() function :
// 	Checks to see that the required form elements are present
//	and in an acceptable state. 
function validateForm() {

	var msgStr = "<p>Please correct the following: <br />";
	var isInValid = false;
	
	var name = document.frmContact.Name;
	if ( name.value == "" ) {
		msgStr = msgStr + "Please include your name.<br />";
		isInValid = true;
	}
	
	var email = document.frmContact.Email;
	if ( !isValidEmail( email.value )) {
		msgStr = msgStr + "Please include a valid email address.<br />";
		isInValid = true;
	}
	
	var message = document.frmContact.Message;
	if ( message.value == "" ) {
		msgStr = msgStr + "The message field appears empty.<br />";
		isInValid = true;
	}

	var phone = document.frmContact.Phone;
	if ( phone != null && phone.value != "" ) {
		if (!isValidPhone(phone.value)) {
			msgStr = msgStr + "Please provide digits and use the phone format shown.<br />";
			isInValid = true;
		}
	}
	
	if ( isInValid ) {
		var msgDiv = document.getElementById("messages");
		msgDiv.innerHTML = msgStr + "</p>";
		return false;
	} else {
		return true;
	}
}

function isValidEmail( str ) {

	if ( str.length <= 5 ) {
		return false;
	}

	var at = "@";
	var dot = ".";
	var in_at = str.indexOf(at);
	var in_dot = str.indexOf(dot);
	
	if ( in_at < 1 || in_dot < 3 ) {
		return false;
	}
	
	if ( str.substring( in_at + 1, in_at + 2 ) == dot ) {
		return false;
	}
	
	if ( str.substring( in_at - 1, in_at ) == dot ) {
		return false;
	}
	
	if ( str.indexOf( at, in_at + 1 ) != -1 ) {
		return false;
	}
	return true;
}

function isValidPhone( str ) {

           var digPattern = /^\d{10}$/;
           if ( digPattern.test( str )) {
               return true;
           }

	var pattern = /^\(\d{3}\) \d{3} - \d{4}$/;
	if (pattern.test( str )) {
		return true;
	}
	return false;
}
