// 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 = "";

  errors += message_for_cond("You must pick a competition answer\n", !is_radio_selected(document.win.answer));

  for (i=0; i<f.length; i++) {
    if ((f[i].type=="text") && (f[i].name != "birthday")) {
	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";
	    }
	  }
        }
    }
  }


  errors += message_for_cond("You must agree to the Channel4 Terms and Conditions\n", !document.win.terms.checked);
	
  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
