// Author: Stephen Poley
var nbsp = 160; 
var node_text = 3;
var emptyString = /^\s*$/
var glb_vfld; 
function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};
function setFocusDelayed() {
  glb_vfld.focus()
}
function setfocus(vfld) {
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}
function msg(fld, msgtype, message) {
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;
  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  elem.className = msgtype; 
};
var proceed = 2;  
function commonCheck(vfld, ifld, reqd) {
  if (!document.getElementById) 
    return true;  
  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true; 
  if (elem.firstChild.nodeType != node_text)
    return true; 
  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "error", "Required field");  
	  elem.style.color = "#F00";
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}
function validatePresent(vfld, ifld )  {
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) return stat;
  msg (ifld, "warn", "");  
  return true;
};
function validateEmail(vfld, ifld, reqd) {
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value); 
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "error", "Not a valid e-mail address");
    var elem = document.getElementById(ifld);
	elem.style.color = "#F00";
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg (ifld, "warn", "Unusual e-mail address - check if correct");
  else
    msg (ifld, "warn", "");
  return true;
};

function showComments() {
  cf=document.getElementById("addComment");
  cf.style.display="block";
  document.location = "#Comment";
  document.getElementById("comment").focus();
}
function validateOnSubmit() {
  var elem;
  var errs=0;
  if (!validatePresent(document.forms.addcom.comment, 'inf_comment',  false)) errs += 1; 
  if (document.forms.addcom.author && !validatePresent(document.forms.addcom.author, 'inf_author', true)) errs += 1; 
  if (document.forms.addcom.author_email && !validatePresent(document.forms.addcom.author_email, 'inf_author', true)) errs += 1; 
  if (document.forms.addcom.author_email && !validateEmail(document.forms.addcom.author_email, 'inf_email', true)) errs += 1; 
  if (errs>1)  alert('There are fields which need correction before sending');
  if (errs==1) alert('There is a field which needs correction before sending');
  return (errs==0);
};


