﻿function validateFormOnSubmit(theForm) {
	var reason = "";
	var dvdFail = false;
	var condFail = false;
	var nameFail = false;
	var yellowNote = false;

	reason += validateEmail(theForm.mailfrom);
	
	if (reason != "") {
		yellowNote = true;
	}

	if (validateEmpty(theForm.Name) == true) {
		yellowNote = true;
		reason += "You didn't enter your name.\n\n";
	}


	if (theForm.Consultation.checked == true) {
		// make sure condtion is described
		if (validateEmpty(theForm.describe_condition) == true) {
			condFail = true;
		}
		
		if (condFail == true) {
			reason += "Please type a brief description of your condition.\n\n";
			yellowNote = true;
		}
	}	

	if (theForm.DVD_Request.checked == true) {
	
		// make sure address is provided
		if (validateEmpty(theForm.mailStreet) == true) {
			dvdFail = true;
		}

		if (validateEmpty(theForm.mailCity) == true) {
			dvdFail = true;
		}
		if (validateEmpty(theForm.mailZip) == true) {
			dvdFail = true;
		}
		
		
		if (dvdFail == true) {
			reason += "Please complete all address fields for DVD delivery.\n\n";
			yellowNote = true;
		}
	}	
	 
		
	if (yellowNote == true) {
		reason += "Please check the information in all fields that now highighted yellow.\n\n";
	
	}
	
	if (reason != "") {
		alert("Oops. Some small form errors were found.\n\n" + reason);
		return false;
	}

	return true; //final answer
}


function validateEmpty(fld) {
    var error = false;
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = true; //"The required field has not been filled in.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}


function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter an email address.\n\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

