// JavaScript Document

/* Note from Damon: I updated this validation script to only check each field if 
  it exists. This is to make the script flexible since the signup form will sometimes
  not have certain fields (or they will be prepopulated) depending upon where the
  user has come from.
*/

// Main code checking loop

function checkWholeForm(theForm) {
	var why = "Please check the following items in the form:\n";
	var no_error_why = why;
	
	// Check user's name.
	
	if (theForm.first_name) {	
		if (theForm.first_name.value == "") {
			why += " - First name\n";
		}
	}
	
	if (theForm.last_name) {
		if (theForm.last_name.value == "") {
			why += " - Last name\n";
		}
	}

	if (theForm.company) {
		if (theForm.company.value == "") {
			why += " - Company name\n";
		}
	}

	if (theForm.email) {
		why += checkEmail(theForm.email.value);
	}

	if (theForm.email2) {
		why += checkRetypeEmail(theForm.email.value,theForm.email2.value);
	}

	if (theForm.interest) {
	var at_least_one = false;
		
		for (i=0, n=theForm.interest.length; i<n; i++) {
			if (theForm.interest[i].checked) {
				at_least_one = true;
				break;
			}
		}
		
		if (at_least_one == false)
			why += " - Check at least one application area interest\n";
	}

	if (why != no_error_why) {
		alert(why);
		return false;
	}

	// Post-processing after validation succeeds.
	// Assemble list of interests from check boxes.

	var checked_interests = "Checked Interests: ";
	var first_time = true;
	
	for (i=0, n=theForm.interest.length; i<n; i++) {
		if (theForm.interest[i].checked) {
			if (first_time == true) {
				checked_interests += theForm.interest[i].value;
				first_time = false;
			}
			else {
				checked_interests += ", " + theForm.interest[i].value;
			}
  		}
	}

	// If the form has passed validation, concatenate the check box values
	// and text message area content. These then go into one field in Salesforce.com.
	
	if (theForm.message.value != "")
		theForm.description.value = checked_interests + "\nComment / Message text:\n" + theForm.message.value;
	else
		theForm.description.value = checked_interests;

	return true;
}

// email

function checkEmail (strng) {
	var error="";

	if (strng == "") {
 	 error = " - Email address\n";
	  return error;
	}

  var emailFilter=/^.+@.+\..{2,3}$/;
  if (!(emailFilter.test(strng))) { 
    error = " - Email address\n";
  }
  else {
//test email for illegal characters
		var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
		if (strng.match(illegalChars)) {
			error = " - Email address\n";
		}
	}
return error; 
}

function checkRetypeEmail (strng, strng2) {
	var error = "";
	if (strng2 == "") {
	 error = " - Confirm email address\n";
	 return error;
	}
	if (strng != strng2) {
 	 error = " - Confirm email address\n";
	 return error;
	}
return error;
}
