// Javascript helpers for our bear traps
// used by web/whitepapers.php etc

function is_present(fld,called){
  var r = "";
  if(fld.value.length == 0){
    fld.style.background = '#ffc';
    r = "Please add your " + called + ".\n";
  } else {
    fld.style.background = 'White';
  }
  return r;
}
function good_phone(fld){
  var r = "";
  r = is_present(fld,"phone");
  if(r != ""){ return r; }
  var just_nums = fld.value.replace(/[\+\(\)\.\-\ x]/g,'');  
  if(isNaN(parseInt(just_nums))){
    r = "The phone number contains illegal characters.\n\n";
    fld.style.background = '#ffc';
    return r;
  }
  if(just_nums.length < 10){
    fld.style.background = '#ffc';
    r = "The provided phone number is not long enough. Please make sure to include the area code.\n";
    return r;
  }
  fld.style.background = 'White';
  return r;
}
function strim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function good_email(fld) {
  var r = "";
  var sfld = strim(fld.value);                        // value of field with whitespace trimmed off
  var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
  var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
  if (fld.value == "") {
    fld.style.background = '#ffc';
    r = "Please let us know your email address.\n";
  } else if (!emailFilter.test(sfld)) {              //test email for illegal characters
    fld.style.background = '#ffc';
    r = "Please enter a valid email address.\n";
  } else if (fld.value.match(illegalChars)) {
    fld.style.background = '#ffc';
    r = "The email address contains illegal characters.\n";
  } else {
    fld.style.background = 'White';
  }
  return r;
}
function vf(frm) {
 var r = "";

 if (frm.nevergonnagiveyouup) r += is_present(frm.nevergonnagiveyouup,"name");
 if (frm.nevergonnarunaround) r += is_present(frm.nevergonnarunaround,"company");
 if (frm.nevergonnamakeyoucry) r += good_phone(frm.nevergonnamakeyoucry);
 if (frm.anddesertyou)	r += good_email(frm.anddesertyou);
 if (frm.nevergonnaletyoudown) r += is_present(frm.nevergonnaletyoudown,"topic");
 if (frm.nevergonnasaygoodbye) r += is_present(frm.nevergonnasaygoodbye,"country");
 
 // Country is optional for now.
 if(r != ""){
  alert("Please enter more information:\n\n" + r);
  return false;
 }
 return true;
}
