backgroundcolor = "#FFFFFF";
function FormValidator() {
  this.isValid = true;

  this.doCheck = doCheck;
  this.getValue = getValue;
  this.isEmpty = isEmpty;
  this.doEmailCheck = doEmailCheck;
};

function doAutoCheck() {
  var nrOfPhoneNumbers = 0;
  var nrOfFilledInPhoneNumbers = 0;
  var firstPhoneField;
  var firstPhoneFieldMsg;
  var hasPhoneNumber = 0;
  
  this.isValid = true;
  var formFields = Array('SELECT', 'INPUT');
  var inputs = new Array();
  for (var n=0; n < formFields.length;n++) {
    var tmp = document.getElementsByTagName(formFields[n]);
    for (var i=0; i<tmp.length; i++){
    	// MjN : only Fld???? fields are validated by autocheck !
    	var fldid = tmp[i].getAttribute('id');
    	if (fldid && fldid.length >0 && fldid.indexOf('Fld') == 0) {
      	inputs[inputs.length] = tmp[i];
      }	
    }
  }
  
  for (var i=0; i<inputs.length; i++){
    inputObject = inputs[i];
    if (inputObject.getAttribute('required')== 1) {
      if ((inputObject.getAttribute("ID").length > 0)) {
      	if (inputObject.getAttribute("ID").indexOf("Verify") > 0){
        	origmailinputobject = inputs[i-1];
        	doEmailVerifyCheck(inputObject.getAttribute('ID'),origmailinputobject.getAttribute('ID'),((inputObject.getAttribute("errormsg") != null)) ? inputObject.getAttribute('errormsg') : "");
      	} else if (inputObject.getAttribute("ID").indexOf("mail") > 0)
          doEmailCheck(inputObject.getAttribute('ID'),((inputObject.getAttribute("errormsg") != null)) ? inputObject.getAttribute('errormsg') : "");
        else if (inputObject.getAttribute("ID").indexOf("hone") > 0)
          doPhoneCheck(inputObject.getAttribute('ID'),((inputObject.getAttribute("errormsg") != null)) ? inputObject.getAttribute('errormsg') : "");
		  
        else
          doCheck(inputObject.getAttribute('ID'),((inputObject.getAttribute("errormsg") != null)) ? inputObject.getAttribute('errormsg') : "");
  		}
    } else if (inputObject.getAttribute('required')== 2) {// at least one of the field is required
		
	    // phonenumbers
		if (inputObject.getAttribute("ID").indexOf("hone") > 0) {
			if ((inputObject.getAttribute("ID").length > 0)) {
				nrOfPhoneNumbers++;
				var obj = getObject(inputObject.getAttribute('ID'));
				var value = getValue(obj);
				var msg = (inputObject.getAttribute("errormsg") != null) ? inputObject.getAttribute('errormsg') : "";
				// save for showing an error first phone field
				if (hasPhoneNumber==0) {
				  firstPhoneField=inputObject.getAttribute("ID");
				  firstPhoneFieldMsg=(msg);
				  hasPhoneNumber=1;
				}
				// when filled in nr should be more than 10 digits
				if (!isEmpty(value) && value.length < 10 ) {
					processMessage(obj, msg);
					this.isValid = false;
				}
				// count
				if ( ! isEmpty(value)) {
				  nrOfFilledInPhoneNumbers ++;
				}
			}
		}
	}
  }
  
  // verify==2 atleast one phone number mandatory.
  if (nrOfPhoneNumbers>0 && nrOfFilledInPhoneNumbers==0) {
	doPhoneCheck(firstPhoneField,firstPhoneFieldMsg);
  }
  
  return this.isValid;
};



function doPhoneCheck(field, msg) {
  obj = getObject(field);
  value = getValue(obj);

  var mandatoryPhonelength = 10;
  if (obj.attributes['phonelength']) {
	mandatoryPhonelength = obj.attributes['phonelength'].value;
  }
  
  if (isEmpty(value) || value.length < mandatoryPhonelength) {
    processMessage(obj, msg);
    this.isValid = false;
  }
  else {
    obj.style.backgroundColor = backgroundcolor;
    //this.isValid = true;
  }
};

function doEmailCheck(field, msg, isAlertField) {
	result = true;
	
  obj = getObject(field, isAlertField);
  value = getValue(obj);
  
  emailArray = value.split('@');
  if (isEmpty(value) || (emailArray.length != 2) || value.length < 6 || ! validateEmail(value) || ! validateEmailCPRules(value)) {
  	processMessage(obj, msg);
    this.isValid = false;
    result = false;
  }else {
    obj.style.backgroundColor = backgroundcolor;
	var v = obj.value;
	obj.value = v.toLowerCase();
    //this.isValid = true;
  }
  return result;
};

function doEmailVerifyCheck(field, origmailfield, msg) {
  obj = getObject(field);
  value = getValue(obj);
  origmailobj = getObject(origmailfield);
  origmailvalue = getValue(origmailobj);
  
  if (obj && obj.value) {
	obj.value = value.toLowerCase();
  }

  if (origmailobj && origmailobj.value) {
	origmailobj.value=origmailvalue.toLowerCase();
	
  }
  value = getValue(obj);
  origmailvalue = getValue(origmailobj);
  
  if (isEmpty(value) || (value != origmailvalue)) {
  	processMessage(obj, msg);
    this.isValid = false;
  }else {
    obj.style.backgroundColor = backgroundcolor;
    //this.isValid = true;
  }
};

function doCheck(field, msg, isAlertField) {
  obj = getObject(field, isAlertField);
  value = getValue(obj);

  if (isEmpty(value)) {
    processMessage(obj, msg);
    this.isValid = false;
  }
  else {
    obj.style.backgroundColor = backgroundcolor;
    //this.isValid = true;
  }
};

function isEmpty(str) {
  return  ((str == "" || str == null)? true : false);
};

function getValue(obj) {
  if (obj.type == "select-one") 
    if (!isEmpty(obj.options[obj.selectedIndex].value)) str = obj.options[obj.selectedIndex].text;
    else str = obj.options[obj.selectedIndex].value;
  else 
    str = obj.value;

  return str;
};

function processMessage(obj, msg) {
   obj.style.backgroundColor = "#FFDDDD";
   obj.style.borderColor = "#a52008";
   obj.onchange = removeError;
   if (!isEmpty(msg)) alert(msg);
	tabcheck=false;
};

function removeError() {
	this.style.borderColor = "#999999";
	this.style.backgroundColor = "#FFFFFF";
	this.onchange = null;
};


function getObject( field ,isAlertField) {
	if (isAlertField) x = getAlertInputField(field);
	else if (document.getElementById) x = document.getElementById(field);
	else if (document.all) x = document.all[field];
	else if (document.layers)	x = document.layers[field];
  
  return x;
};

function getAlertInputField(fieldname) {
	var el_alert 		= document.getElementById('alert');
	
	var inputs = el_alert.getElementsByTagName('INPUT');
  for (var i=0; i<inputs.length; i++){    
    inputObject = inputs[i];
    if (inputObject.getAttribute('id') == fieldname) {
    		return inputObject;
    }
  } 
  alert( fieldname + ' : not found within Alert');			 
  return null;
};




function Summary(prefix) {
  this.prefix = prefix;
  
  this.addSummary = addSummary;
};

function addSummary(field) {
    obj = getObject(field);
    obj_summary = getObject(this.prefix+field);
        
    obj_summary.innerHTML = getValue(obj);
};

function validateEmail(email) {
	//RFC 2822 token definitions for valid email - only used together to form a java Pattern object:
	var sp = "\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~";
	var atext = "[a-zA-Z0-9" + sp + "]";
	var atom = atext + "+"; //one or more atext chars
	var dotAtom = "\\." + atom;
	var localPart = atom + "(" + dotAtom + ")*"; //one atom followed by 0 or more dotAtoms.

	//RFC 1035 tokens for domain names:
	var letter = "[a-zA-Z]";
	var letDig = "[a-zA-Z0-9]";
	var letDigHyp = "[a-zA-Z0-9-]";
	var rfcLabel = letDig + "(" + letDigHyp + "{0,61}" + letDig + ")?";
	var domain = rfcLabel + "(\\." + rfcLabel + ")*\\." + letter + "{2,6}";

	//Combined together, these form the allowed email regexp allowed by RFC 2822:
	var addrSpec = "^" + localPart + "@" + domain + "$";

	var d  = new RegExp("[a-z]","g");
	return d.test(email);
};

function validateEmailCPRules(email) {
  //Note that even though the syntax of the address may be correct, there's no guarantee that a mailbox of that name exists.
  //addresses composed of simple names (with no "@domain" part) are allowed. Such "illegal" addresses are not uncommon in real messages.
  //
  //However according to Business rule of valid e-mail PRESTO+1062:
  //        An e-mail address requires:
  //        +1. Presence of an @
  //        +2. A character before the @
  //        +3 Length > 6 characters
  //        +4. min 1 character after @, before .
  //        +5. min. 1 character after .
  //        6. Does not contain ()<>,;:\"[] !true!!!
  //     PRESTO+3059 Email address specification
  //        7. domain name only may contain letters, digits an hyphens (-)
  //        8. - may not be the first character of a domain name.
  var ok=false;
  var atIndex  = email.indexOf("@");
  var dotIndex = email.lastIndexOf(".");

  var illegalCharacterPattern  = new RegExp(".*[ \\(\\)<>,;:\\\"\\[\\]]+.*","g");
  var domainPattern = new RegExp("\\w+([-\\.]\\w+)*\\.\\w+","i");
  
  if ( atIndex!=-1 && dotIndex != -1 && dotIndex > atIndex && !illegalCharacterPattern.test(email)) {
    
	var user = email.substring(0, atIndex);
	var domainname = email.substring(atIndex+1);
    var extension = email.substring(dotIndex+1);
    
    if ( user.length >= 1 ) {
      if (email.length > 6) {
        if (domainname.length > 1 && extension.length > 1) {
          if ("-.".indexOf(domainname.charAt(0)) < 0) {
           if ( domainPattern.test(domainname) ) {
             ok = true;
           }
          }
        }
      }
    }
  }
  return ok;
};

function validateAtLeastOne(inputs,field,msg) {

  obj = getObject(field);
  value = getValue(obj);

  if (isEmpty(value) || value.length < 10 ) {
    processMessage(obj, msg);
    this.isValid = false;
  }
  else {
    obj.style.backgroundColor = backgroundcolor;
  }
  
};

