// SCRIPT CLEANED UP AND VALIDATED BY YOKI
function Validator(frmname)
{
 this.formobj=document.forms[frmname];
	if(!this.formobj)
	{
	 alert("BUG: couldnot get Form object "+frmname);
		return;
	}
	if(this.formobj.onsubmit)
	{
	 this.formobj.old_onsubmit = this.formobj.onsubmit;
	 this.formobj.onsubmit=null;
	}
	else
	{
	 this.formobj.old_onsubmit = null;
	}
	this.formobj.onsubmit=form_submit_handler;
	this.addValidation = add_validation;
	this.setAddnlValidationFunction=set_addnl_vfunction;
	this.clearAllValidations = clear_all_validations;
}

function set_addnl_vfunction(functionname)
{
 this.formobj.addnlvalidation = functionname;
}
function clear_all_validations()
{
	for(var itr=0;itr < this.formobj.elements.length;itr++)
	{
		this.formobj.elements[itr].validationset = null;
	}
}

function form_submit_handler()
{
	for(var itr=0;itr < this.elements.length;itr++)
	{
		if(this.elements[itr].validationset && !this.elements[itr].validationset.validate())
		{
		 return false;
		}
	}
	if(this.addnlvalidation)
	{
	 str =" var ret = "+this.addnlvalidation+"()";
	 eval(str);
  if(!ret) return ret;
	}
	return true;
}

function add_validation(itemname,descriptor,errstr)
{
 if(!this.formobj)
	{
	 alert("BUG: the form object is not set properly");
		return;
	}//if
	var itemobj = this.formobj[itemname];
 if(!itemobj)
	{
	 alert("BUG: Couldnot get the input object named: "+itemname);
		return;
	}
	if(!itemobj.validationset)
	{
	 itemobj.validationset = new ValidationSet(itemobj);
	}
 itemobj.validationset.add(descriptor,errstr);
}

function ValidationDesc(inputitem,desc,error)
{
 this.desc=desc;
	this.error=error;
	this.itemobj = inputitem;
	this.validate=vdesc_validate;
}

function vdesc_validate()
{
 if(!V2validateData(this.desc,this.itemobj,this.error))
 {
  this.itemobj.focus();
		return false;
 }
 return true;
}

function ValidationSet(inputitem)
{
 this.vSet=new Array();
	this.add= add_validationdesc;
	this.validate= vset_validate;
	this.itemobj = inputitem;
}

function add_validationdesc(desc,error)
{
 this.vSet[this.vSet.length]=new ValidationDesc(this.itemobj,desc,error);
}

function vset_validate()
{
 for(var itr=0;itr<this.vSet.length;itr++)
	{
	 if(!this.vSet[itr].validate())
	 {
		 return false;
		}
	}
	return true;
}

function validateEmailv2(emailStr)
{
 // START EXPANDED E-MAIL VALIDATION SCRIPT ADDED BY YOKI
 
 /* The following variable tells the rest of the function whether or not to verify that the address ends in a two-letter country or well-known TLD.  1 means check it, 0 means don't. */
 var checkTLD=1;
 
 /* The following is the list of known TLDs that an e-mail address must end with. */
 var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
 
 /* The following pattern is used to check if the entered e-mail address fits the user@domain format. It  also is used to separate the username from the domain. */
 var emailPat=/^(.+)@(.+)$/;

 /* The following string represents the pattern for matching all special characters.  We don't want to allow special characters in the address. These characters include ( ) < > @ , ; : \ " . [ ] */
 var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
 
 /* The following string represents the range of characters allowed in a username or domainname. It really states which chars aren't allowed.*/
 var validChars="\[^\\s" + specialChars + "\]";
 
 /* The following pattern applies if the "user" is a quoted string (in  which case, there are no rules about which characters are allowed and which aren't; anything goes). E.g. "jiminy cricket"@disney.com is a legal e-mail address. */
 var quotedUser="(\"[^\"]*\")";
 
 /* The following pattern applies for domains that are IP addresses, rather than symbolic names. E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required. */ 
 var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
 
 /* The following string represents an atom (basically a series of non-special characters.) */
 var atom=validChars + '+';
 
 /* The following string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string. */
 var word="(" + atom + "|" + quotedUser + ")";
 
 // The following pattern describes the structure of the user
 var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
 
 /* The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above. */
 var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
 
 /* Finally, let's start trying to figure out if the supplied address is valid. */
 
 /* Begin with the coarse pattern to simply break up user@domain into
 different pieces that are easy to analyze. */
 var matchArray=emailStr.match(emailPat);
 if (matchArray==null)
 {
  /* Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address. */
  alert("Invalid E-mail Address, please check @ and .'s)");
  return false;
 }
 var user=matchArray[1];
 var domain=matchArray[2];
 // Start by checking that only basic ASCII characters are in the strings (0-127).
 for (i=0; i<user.length; i++)
 {
  if (user.charCodeAt(i)>127)
  {
   alert("The username part of the e-mail address contains invalid characters.");
   return false;
  }
 }
 for (i=0; i<domain.length; i++)
 {
  if (domain.charCodeAt(i)>127)
  {
   alert("The domain name part of the e-mail address contains invalid characters.");
   return false;
  }
 }
 // See if "user" is valid 
 if (user.match(userPat)==null)
 {
  // user is not valid
  alert("The username part of the e-mail address is not valid, please correct it.");
  return false;
 }
 /* if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid. */
 var IPArray=domain.match(ipDomainPat);
 if (IPArray!=null)
 {
  // this is an IP address
  for (var i=1;i<=4;i++)
  {
   if (IPArray[i]>255)
   {
    alert("The e-mail address destination IP address is invalid, please correct it.");
    return false;
   }
  }
  return true;
 }
 // Domain is symbolic name. Check if it's valid.
 var atomPat=new RegExp("^" + atom + "$");
 var domArr=domain.split(".");
 var len=domArr.length;
 for (i=0;i<len;i++)
 {
  if (domArr[i].search(atomPat)==-1)
  {
   alert("The domain name part of the e-mail address is not valid, please correct it.");
   return false;
  }
 }
 /* domain name seems valid, but now make sure that it ends in a known top-level domain (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country. */
 if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1)
 {
  alert("The e-mail address must end in a well-known domain or two letter " + "country.");
  return false;
 }
 // Make sure there's a host name preceding the domain.
 if (len<2)
 {
  alert("The e-mail address is missing a hostname, please add this.");
  return false;
 }
 // If we've gotten this far, everything's valid!
 return true;
}
// END EXPANDED E-MAIL VALIDATION CODE

function V2validateData(strValidateStr,objValue,strError)
{
 var epos = strValidateStr.search("=");
 var  command  = "";
 var  cmdvalue = "";
 if(epos >= 0)
 {
  command  = strValidateStr.substring(0,epos);
  cmdvalue = strValidateStr.substr(epos+1);
 }
 else
 {
  command = strValidateStr;
 }
 switch(command)
 {
  case "req":
  case "required":
  {
   if(eval(objValue.value.length) == 0)
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name + " : Required Field";
    }//if
    alert(strError);
    return false;
   }//if
   break;            
  }//case required
  case "maxlength":
  case "maxlen":
  {
   if(eval(objValue.value.length) >  eval(cmdvalue))
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name + " : "+cmdvalue+" characters maximum ";
    }//if
    alert(strError + "\n[Current length = " + objValue.value.length + " ]");
    return false;
   }//if
   break;
  }//case maxlen
  case "minlength":
  case "minlen":
  {
   if(eval(objValue.value.length) <  eval(cmdvalue))
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name + " : " + cmdvalue + " characters minimum  ";
    }//if
    alert(strError + "\n[Current length = " + objValue.value.length + " ]");
    return false;
   }//if
   break;
  }//case minlen
  case "alnum":
  case "alphanumeric":
  {
   var charpos = objValue.value.search("[^A-Za-z0-9]");
   if(objValue.value.length > 0 &&  charpos >= 0)
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name+": Only alpha-numeric characters allowed ";
    }//if
    alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
    return false;
   }//if
   break;
  }//case alphanumeric
  case "num":
  case "numeric":
  {
   var charpos = objValue.value.search("[^0-9]");
   if(objValue.value.length > 0 &&  charpos >= 0)
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name+": Only digits allowed ";
    }//if
    alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
    return false;
   }//if
   break;
  }//numeric
  case "alphabetic":
  case "alpha":
  {
   var charpos = objValue.value.search("[^A-Za-z]");
   if(objValue.value.length > 0 &&  charpos >= 0)
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name+": Only alphabetic characters allowed ";
    }//if           
    alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
    return false;
   }//if
   break;
  }//alpha
  
  case "alnumhyphen":
  {
   var charpos = objValue.value.search("[^A-Za-z0-9\-_+.]");
   if(objValue.value.length > 0 &&  charpos >= 0)
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name+": characters allowed are A-Z,a-z,0-9,- and _";
    }//if           
    alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
    return false;
   }//if
   break;
  } //alnumhyphen
  
    case "alphahyphen":
  {
   var charpos = objValue.value.search("[^A-Za-z\-_]");
   if(objValue.value.length > 0 &&  charpos >= 0)
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name+": characters allowed are A-Z,a-z,- and _";
    }//if           
    alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
    return false;
   }//if
   break;
  }
  
    case "numhyphen":
  {
   var charpos = objValue.value.search("[^0-9\-_+.]");
   if(objValue.value.length > 0 &&  charpos >= 0)
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name+": characters allowed are 0-9,-,+,. and _";
    }//if           
    alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
    return false;
   }//if
   break;
  } //numhyphen
  
  case "email":
  {
   if(!validateEmailv2(objValue.value))
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name+": Enter a valid Email address ";
    }//if
    alert(strError);
    return false;
   }//if
   break;
  }//case email
  case "lt":
  case "lessthan":
  {
   if(isNaN(objValue.value))
   {
    alert(objValue.name+": Should be a number ");
    return false;
   }//if
   if(eval(objValue.value) >=  eval(cmdvalue))
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name + " : value should be less than "+ cmdvalue;
    }//if
    alert(strError);
    return false;
   }//if
   break;
  }//case lessthan
  case "gt":
  case "greaterthan":
  {
   if(isNaN(objValue.value))
   {
    alert(objValue.name+": Should be a number ");
    return false;
   }//if
   if(eval(objValue.value) <=  eval(cmdvalue))
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name + " : value should be greater than "+ cmdvalue;
    }//if
    alert(strError);
    return false;
   }//if
   break;
  }//case greaterthan
  case "regexp":
  {
   if(objValue.value.length > 0)
   {
    if(!objValue.value.match(cmdvalue))
    {
     if(!strError || strError.length ==0)
     {
      strError = objValue.name+": Invalid characters found ";
     }//if
     alert(strError);
     return false;
    }//if
   }
   break;
  }//case regexp
  case "dontselect":
  {
   if(objValue.selectedIndex == null)
   {
    alert("BUG: dontselect command for non-select Item");
    return false;
   }
   if(objValue.selectedIndex == eval(cmdvalue))
   {
    if(!strError || strError.length ==0)
    {
     strError = objValue.name+": Please Select one option ";
    }//if
    alert(strError);
    return false;
   }
   break;
  }//case dontselect
 }//switch
 return true;
}

// ADDITIONAL VALIDATION STEPS ADDED BY YOKI

// VERFIY THAT 'NEW PASSWORD' AND 'CONFIRM PASSWORD' MATCH
function DoCustomValidation() // parenthesis must hold the form name
{
 var frm = document.forms["demographics"]; // NOTE: this is configured for the 'demographics' form
 if(frm.RTP__password.value != frm.RTP__passwordconfirm.value) // the string value between 'frm.' and '.value' must equal the name of the two password fields to be compared, in this case the names are from the 'demographics' form
 {
  alert('The Password and Verified Password do not match, please try again.');
  return false;
 }
 else
 {
  return true;
 }
}

