// Check if the field is blank
function isblank(s) {
	for (var i=0; i<s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}

// Check email syntax
function emailSyntax(s) {
	emailRe = /([\w\-\+]+)@([\w\-\+\.]+)/;
	return emailRe.test(s);
}

// Main function to verify the form fields.  Can also verify the values in a field.
// If f.elements[i].required = true, check the value.
//  - use f.elements[i].min and f.elements[i].max to limit the floating point values
//  - use f.elements[i].emailsyntax = true to check email syntax
function verify(f) {
	var msg;
	var empty_fields = "";
	var errors = "";
	var radio_req = "";
	var radio_chk = "";
	var radio_name = "";

	// loop through all the fields
	for (var i=0; i<f.length; i++) {
		var e = f.elements[i];
		
		// not necessary to check radio button
		// if ((e.type == "radio")) {
		//	radio_req = "yes";
		//	radio_name = e.name;
		//	if (e.checked) { radio_chk = "yes"}
		//	}
		// not necessary to check radio button
		
		// if type is text, or textarea and required, check
		if((e.name == "country")&& e.required) {
			if (e.value == ""){
				empty_fields += "\n    " + e.name;
				continue;			}
		}
		if (((e.type == "text") || (e.type == "textarea")) && e.required) {
			if ((e.value == null) || (e.value == "") || isblank(e.value)) {
				empty_fields += "\n    " + e.name;
				continue;
			}
		
			// if type is text, or textarea and required, check
			if (e.emailsyntax) {
				if (!emailSyntax(e.value)) {
					empty_fields += "\n    " + e.name + " -- wrong email syntax";
					continue;
				}
			}

			// if field value is numeric or min or max is not null, check
			if (e.numeric || (e.min != null) || (e.max != null)) {
				var v = parseFloat(e.value);
				if (isNaN(v) ||
					((e.min != null) && (v < e.min)) ||
					((e.max != null) && (v > e.max))) {
						errors += "- The field " + e.name + " must be a number";
						if (e.min != null)
							errors += " that is greater than " + e.min;
						if (e.max != null)
							errors += " and less than " + e.max;
						else if (e.max != null)
							errors += " that is less than " + e.max;
						errors += ".\n";
				}
			}
		}

	}
	
	if (radio_req && !radio_chk) {
		empty_fields += "\n    " + radio_name;
	}

	// if no errors or no empty fields, return true, else, output msg using the alert box.
	if (!empty_fields && !errors) return true;

	msg = "___________________________________________________\n\n";
	msg += "The form was not submitted because of the following error(s).\n";
	msg += "Please correct these error(s) and re-submit.\n";
	msg += "___________________________________________________\n\n";

	if (empty_fields) {
		msg += "- Please check that the following required field(s) are filled in:"
			+ empty_fields + "\n";
		if (errors) msg += "\n";
	}

	msg += errors;
	alert(msg);
	return false;
}
