var patternEmail =  /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var mailEntered = false;

function validateMail(fieldName) {
  if(!isObjectValidated(fieldName)){
    alert("Occorre specificare l\'indirizzo di e-mail");
  }
}

/*
 *  The function retrieves the control value and the pattern to be applied.
 *  The function then validates the control value against the correct pattern.
 *  The name of each object to be validated has a prefix equal to the pattern suffix to be 
 *  applied, followed by underscore (as delimiter) and an alphanumeric description.
 *  In case of validation returns true, in case else returns false,
 */
function isObjectValid(objField) {
  var pattern = eval("patternEmail" + objField.name.substring(0,objField.name.indexOf("_")));
  var inputText = eval("formName." + objField.name + ".value");
  new RegExp();
  if(!pattern.test(inputText)){
    return false;
  } else {
    return true;
  }
}

function isEntityValid(entity) {
  var pattern;
  var inputText;
  var t = typeof(entity);
  if(t=='string') {
    pattern = eval("patternEmail" + entity.substring(0,entity.indexOf("_")));
    inputText = eval("formName." + entity + ".value");
  } else if(t=='object') {
    pattern = eval("patternEmail" + entity.name.substring(0,entity.name.indexOf("_")));
    inputText = eval("formName." + entity.name + ".value");
  }
  new RegExp();
  if(!pattern.test(inputText)){
    return false;
  } else {
    return true;
  }
}

function submitIfValid(entity) {
  if(isEntityValid(entity)) {
    eval('document.formName.submit()');
  } else {
    alert("Verificare l'indirizzo di posta elettronica");
  }
}
