// form validate
function number_bad_chars(str) {
  text_length = str.length;
  bad_chars_count = 0;
  while (text_length != 0) {
    if (str.charCodeAt(text_length - 1) <= 32) {
      bad_chars_count += 1;
    }
    text_length -= 1;
  }
  return bad_chars_count; 
}

function is_valid_email(str) {
  if ((str.indexOf('@') < 0) || (str.indexOf('.') < 0)) {
    return false;
  }
  return true;
}
	
function is_radio_selected(radios) {
  for (i=0;i<radios.length;i++) {
    if (radios[i].checked) {
      return true;
    }
  }
  return false;
}

function message_for_cond(msg, cond) {
  if (cond) { return msg; }
  else { return ""; }
}

function validate(f) {
  errors = "";



 for (i=0; i<f.length; i++) {
    if ((f[i].type=="text") && (f[i].name != "telephone") && (f[i].name != "country") && (f[i].name != "where") || (f[i].type=="select-one")) {
	bad_chars_count = number_bad_chars(f[i].value);
	if (bad_chars_count >= f[i].value.length - bad_chars_count) { 
	  errors+= f[i].name+" cannot be blank\n";
	} else {
	  //specific matches only now
	  if (f[i].name == "Email") {
	    if (!is_valid_email(f[i].value)) { 
	      errors += "Email address is invalid\n";
	    }
	  }
        }
    }
  }

  if (errors == "")
  {
   if (!isValidDate(document.win.dateofbirthmonth.value + '/' + document.win.dateofbirthday.value + '/' + document.win.dateofbirthyear.value))
    errors = "You entered an invalid date of birth\n";
   else
   {
    var dt = parseInt(document.win.dateofbirthyear.value) * 365;
    dt += parseInt(document.win.dateofbirthmonth.value) * 31;
    dt += parseInt(document.win.dateofbirthday.value);
    if ((dt < 726435) || (dt > 728587))
     errors = "Sorry you need to be born between 23rd Feb 1990 and 16th Jan 1996 to enter\n";
   }
  }
  
  if (errors != "") {
    alert("Sorry there appears to be a problem with details you supplied.\n\nPlease correct the following questions and try again. \n\n" +errors);
    return false;
  }
		
} // end validate function

function isValidDate(dateStr) {
 var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert("Date is not in a valid format.")
return false;
}
month = matchArray[1]; // parse date into variables
day = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
return false;
}
if (day < 1 || day > 31) {
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
return false
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
return false;
   }
}
return true;  // date is valid
}