// check-order-form.js
// Check fields are filled in and that a valid UK postcode has been supplied.

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;
}

function isnumber(n)
{
	var v = parseFloat(n);
	if (isNaN(v)) {
		return false;
	}
	return true;
}

function make_optional(f)
{
	//call this if a family
	f.surname_person3.optional = true;
	f.surname_person4.optional = true;
	f.surname_person5.optional = true;
	f.surname_person6.optional = true;

	f.initials_person3.optional = true;
	f.initials_person4.optional = true;
	f.initials_person5.optional = true;
	f.initials_person6.optional = true;

	f.age_person3.optional = true;
	f.age_person4.optional = true;
	f.age_person5.optional = true;
	f.age_person6.optional = true;
}

function valid_UK_postcode(pcode)
{
	var p = pcode.charAt(0).toUpperCase();	
	if ( p >= 'A' && p <= 'Z' ) {
		return true;
	}
	alert( "You have not entered a valid UK postcode.\nInsurance is only available to UK residents.");
	return false;
}

function ages_under_65(f) 
{
	var max_age = 65;
	if (f.pcode.value == "wanderer") max_age = 45;

	for( var i = 0; i < f.length; i++ ) {
		var e = f.elements[i];
		if (e.name.substring(0,3) == "age") {
			if (e.value >= max_age) {
				alert( "Sorry, this policy is only available to under " + max_age + "s." );
				return false;
			}
		}
	}

	return true;
}

function check_fields(f)
{
	var msg;
	var empty_fields = "";
	var errors = "";

	for(var i = 0; i < f.length; i++ ) {
		var e = f.elements[i];
		if (((e.type == "text") || (e.type == "textarea")) && !e.optional) {
			// is the field empty?
			if ((e.value == null) || (e.value == "") || isblank(e.value)) {
				if (empty_fields != "") empty_fields += ", ";
				empty_fields += e.name;
				continue;
			}
			// now check numerics
			if ((e.numeric) && (!isnumber(e.value))) {
				if (errors != "") errors += ", ";
				errors += e.name + " must be a number ";
			}
		}
	}

	// any errors?
	if (!empty_fields && !errors) return true;

	msg =  "The form was not submitted because of the following ";
	msg += "errors. Please correct them and try again.\n-\n";

	if (empty_fields) {
		msg += "The following required fields are empty:\n" + empty_fields;
		if (errors) msg += "\n-\n";
	}
	msg += errors;
	alert (msg);
	return false;
}