// This file contains the data validation JavaScript functions
// It is included in the HTML pages with forms that need these
// data validation routines.

// Date Amended: 14,17 May 2004
// Amended By: FD
// Details:
// Duplicated some functions and edited them so that a div is displayed on the 
//  page rather than an alert message.


/****************************************************************/
// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s) {
	
// whitespace characters
    var whitespace = " \t\n\r";
    var i;
    // Is s empty?
    if ( (s == null) || (s.length == 0) ) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
	// Check that current character isn't whitespace.
	var c = s.charAt(i);

	if (whitespace.indexOf(c) == -1)  return false;
    }
    // All characters are whitespace.
    return true;
}


/****************************************************************/
// Checks to see if a required field is blank.  
// If it is and the FieldName para is not blank, NO warning
// alert is displayed, but a message on the page is displayed instead and 'false' is returned...

function CheckNotBlankMsgNotAlert(objField, FieldName)
{
	var strField = new String(objField.value);

	if (isWhitespace(strField)) {
        if (!isWhitespace(FieldName)) {
			document.getElementById("error_"+objField.name).style.visibility="visible";
			document.getElementById("error_"+objField.name).style.display="inline";
	    }
	    return false;
	}else{
		document.getElementById("error_"+objField.name).style.visible="hidden";
		document.getElementById("error_"+objField.name).style.display="none";
	}

	return true;
}
		

/****************************************************************/
// Checks to see if a required field is blank.  
// If it is and the FieldName para is not blank , a warning
// message is displayed...

function CheckNotBlank(objField, FieldName)
{
	var strField = new String(objField.value);

	if (isWhitespace(strField)) {
            		if (!isWhitespace(FieldName)) {
            			alert("You must enter " + FieldName);
			objField.focus();
	    }
	     return false;
	}

	return true;
}
		

/****************************************************************/
// Check for valid e-mail address

function EmailOK (objField) {
    var emailStr = new String(objField.value);

/* 1.1.2: Fixed a bug where trailing . in e-mail address was passing
            (the bug is actually in the weak regexp engine of the browser; I
            simplified the regexps to make it work).
   1.1.1: Removed restriction that countries must be preceded by a domain,
            so abc@host.uk is now legal.  However, there's still the 
            restriction that an address must end in a two or three letter
            word.
     1.1: Rewrote most of the function to conform more closely to RFC 822.
     1.0: Original  
   From http://javascript.internet.com */

   <!-- Define patterns to check address                                                                  
   /* 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("E-mail address is blank or incorrect (check @ and .'s)")                                     
      objField.focus();                                                                                                                                                                     
      return false                                                                                        
   }                                                                                                      
   var user=matchArray[1]                                                                                 
   var domain=matchArray[2]                                                                               
                                                                                                          
   // See if "user" is valid                                                                              
   if (user.match(userPat)==null) {                                                                       
       // user is not valid                                                                               
      alert("Problem with the username part of the e-mail address")                                       
      objField.focus();                                                                                   
      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("E-mail IP address is incorrect")                                                     
           objField.focus();                                                                           
   	   return false                                                                                
           }                                                                                              
       }                                                                                                  
       return true                                                                                        
   }                                                                                                      
                                                                                                          
   // Domain is symbolic name                                                                             
   var domainArray=domain.match(domainPat)                                                                
   if (domainArray==null) {                                                                               
      alert("E-mail address is incorrect - check the domain name.")                                       
      objField.focus();                                                                                   
      return false                                                                                        
   }                                                                                                      
                                                                                                          
   /* domain name seems valid, but now make sure that it ends in a                                        
      three-letter word (like com, edu, gov) or a two-letter word,                                        
      representing country (uk, nl), and that there's a hostname preceding                                
      the domain or country. */                                                                           
                                                                                                          
   /* Now we need to break up the domain to get a count of how many atoms                                 
      it consists of. */                                                                                  
   var atomPat=new RegExp(atom,"g")                                                                       
   var domArr=domain.match(atomPat)                                                                       
   var len=domArr.length                                                                                  
   if (domArr[domArr.length-1].length<2 ||                                                                
       domArr[domArr.length-1].length>3) {                                                                
      // the address must end in a two letter or three letter word.                                       
      alert("E-mail address is incorrect - must end in 2/3 letter domain/country.")                                  
      objField.focus();                                                                                   
      return false                                                                                        
   }                                                                                                      
                                                                                                          
   // Make sure there's a host name preceding the domain.                                                 
   if (len<2) {                                                                                           
      alert("E-mail address is incorrect - error in host name.")                                           
      objField.focus();                                                                                   
      return false                                                                                        
   }                                                                                                      
                                                                                                          
   // Everything's valid!                                                                                 
   return true;                                                                                           
}
//  End -->


/****************************************************************/
// Check for valid e-mail address

function EmailOKMsgNotAlert (objField, BlankOK) {
    var emailStr = new String(objField.value);

/* 1.1.2: Fixed a bug where trailing . in e-mail address was passing
            (the bug is actually in the weak regexp engine of the browser; I
            simplified the regexps to make it work).
   1.1.1: Removed restriction that countries must be preceded by a domain,
            so abc@host.uk is now legal.  However, there's still the 
            restriction that an address must end in a two or three letter
            word.
     1.1: Rewrote most of the function to conform more closely to RFC 822.
     1.0: Original  
   From http://javascript.internet.com */

   <!-- Define patterns to check address                                                                  
   /* 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 (isWhitespace(emailStr)) {   
		if (BlankOK) {
			document.getElementById("error_"+objField.name).style.visibility="hidden";
			document.getElementById("error_"+objField.name).style.display="none";
			return true
		}else{
			document.getElementById("error_"+objField.name).style.visibility="visible";
			document.getElementById("error_"+objField.name).style.display="inline";
			return false 
		}     
	}else{                                                                                  
                                                                                
	   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. */                                          
			document.getElementById("error_"+objField.name).style.visibility="visible";
			document.getElementById("error_"+objField.name).style.display="inline";
		  return false                                                                                  
	   }                                                                                                      
	   var user=matchArray[1]                                                                                 
	   var domain=matchArray[2]                                                                               
																											  
	   // See if "user" is valid                                                                              
	   if (user.match(userPat)==null) {                                                                       
		   // user is not valid                                                                               
			document.getElementById("error_"+objField.name).style.visibility="visible";
			document.getElementById("error_"+objField.name).style.display="inline";
		  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) {                                                                          
				document.getElementById("error_"+objField.name).style.visibility="visible";
				document.getElementById("error_"+objField.name).style.display="inline";
		   return false                                                                                
			   }                                                                                              
		   }                                                                                                  
		   return true                                                                                        
	   }                                                                                                      
																											  
	   // Domain is symbolic name                                                                             
	   var domainArray=domain.match(domainPat)                                                                
	   if (domainArray==null) {                                                                               
			document.getElementById("error_"+objField.name).style.visibility="visible";
			document.getElementById("error_"+objField.name).style.display="inline";
		  return false                                                                                        
	   }                                                                                                      
																											  
	   /* domain name seems valid, but now make sure that it ends in a                                        
		  three-letter word (like com, edu, gov) or a two-letter word,                                        
		  representing country (uk, nl), and that there's a hostname preceding                                
		  the domain or country. */                                                                           
																											  
	   /* Now we need to break up the domain to get a count of how many atoms                                 
		  it consists of. */                                                                                  
	   var atomPat=new RegExp(atom,"g")                                                                       
	   var domArr=domain.match(atomPat)                                                                       
	   var len=domArr.length                                                                                  
	   if (domArr[domArr.length-1].length<2 ||                                                                
		   domArr[domArr.length-1].length>3) {                                                                
		  // the address must end in a two letter or three letter word.                                       
			document.getElementById("error_"+objField.name).style.visibility="visible";
			document.getElementById("error_"+objField.name).style.display="inline";
		  return false                                                                                        
	   }                                                                                                      
																											  
	   // Make sure there's a host name preceding the domain.                                                 
	   if (len<2) {                                                                                           
			document.getElementById("error_"+objField.name).style.visibility="visible";
			document.getElementById("error_"+objField.name).style.display="inline";
		  return false                                                                                        
	   }
	}                                                                                                      
                                                                                                          
   // Everything's valid!                                                                                 
	document.getElementById("error_"+objField.name).style.visibility="hidden";
	document.getElementById("error_"+objField.name).style.display="none";
   return true;                                                                                           
}
//  End -->


/****************************************************************/
// Checks email format, but allows it to be blank

function checkEmailAddressBlankOK ( objField ) {
// if email is blank we don't force an update
   OK = CheckNotBlank(objField.value)
   if (!OK) return true
   OK = EmailOK( objField )
   if (!OK) {
       objField.focus()
       return false
   }
return true;
}


/****************************************************************/
// Returns true if the string contains numbers only



function isNumber ( objField , FieldName ) {

    var strField = new String(objField.value);

    for (i=0; i<strField.length; i++) {
        if ( ((strField.charAt(i)<"0") || (strField.charAt(i)>"9")) || (strField.charAt(i) != ".") ) {
    	    alert(FieldName + " must be a decimal number" );
            objField.focus();
            return false;
        }
    } 
    return true;
}
/****************************************************************/
// Returns true if the string has a valid currency value

function CheckCurrency ( objField , FieldName ) {

    var strField = new String(objField.value);

//  matches £17.23 or £14,281,545.45 or £12345 or 12345.00 or 1,234
    var currencyPat = /^\£?\d{1,}(,\d{3})*((\.\d{2})?)$/

    if ( !currencyPat.exec(strField) ) {
        alert( FieldName + " has an invalid format");
        objField.focus();
        return false;
    } 
    return true;
}


/****************************************************************/
// Checks the length of the field

function CheckLength ( objField , FieldName , LengthLimit) {

    var len=objField.value.length;

    if (len>LengthLimit) {
        alert( FieldName + " is too long - (you have entered " + len + " characters). The max allowed is " + LengthLimit + " characters.");
        objField.focus();
        return false;
    }
    else {
        return true;
    }
}



/****************************************************************/
// Checks the length of the field, NO warning
// alert is displayed, but a message on the page is displayed instead and 'false' is returned...

function CheckLengthMsgNotAlert ( objField , FieldName , LengthLimit) {

    var len=objField.value.length;

    if (len>LengthLimit) {
		document.getElementById("errorlen_"+objField.name).style.visibility="visible";
		document.getElementById("errorlen_"+objField.name).style.display="inline";
        return false;
    }else {
		document.getElementById("errorlen_"+objField.name).style.visible="hidden";
		document.getElementById("errorlen_"+objField.name).style.display="none";
        return true;
    }
}


function IsNumeric (elem, str) {
	var ValidChars = '0123456789.';
	var Char;
  	var strField = new String(elem.value);
	if (strField.length == 0 ){
		alert(str);
		elem.focus();
		return false;
	}
	for (var i=0; i<strField.length; i++) {
		Char= strField.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			alert(str);
			elem.focus();
			return false;
		}
	}
	//if (strField.indexOf('.') == -1) {
	//	alert(str);
	//	elem.focus();
	//	return false;
	//} 
	return true;
}

function IsInteger (elem, str) {
	var ValidChars = '0123456789';
	var Char;
	var test=true;
  	var strField = new String(elem.value);
	if (strField.length == 0){
		alert(str);
		elem.focus();
		return false;
	}
	for (var i=0; i<strField.length; i++) {
		Char= strField.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			alert(str);
			elem.focus();
			return false;
		}
	}
	if (strField.indexOf('') == -1) {
		alert(str);
		elem.focus();
		return false;
	}
	if (! test) {
		alert(str);
		elem.focus();
		return false;
	} 
	return true;
}

function IsIntegerMsgNotAlert (elem, str) {
	var ValidChars = '0123456789';
	var Char;
	var test=true;
  	var strField = new String(elem.value);
	if (strField.length == 0){
		document.getElementById("errorint_"+elem.name).style.visibility="visible";
		document.getElementById("errorint_"+elem.name).style.display="inline";
		return false;
	}
	for (var i=0; i<strField.length; i++) {
		Char= strField.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			document.getElementById("errorint_"+elem.name).style.visibility="visible";
			document.getElementById("errorint_"+elem.name).style.display="inline";
			return false;
		}
	}
	if (strField.indexOf('') == -1) {
		document.getElementById("errorint_"+elem.name).style.visibility="visible";
		document.getElementById("errorint_"+elem.name).style.display="inline";
		return false;
	}
	if (! test) {
		document.getElementById("errorint_"+elem.name).style.visibility="visible";
		document.getElementById("errorint_"+elem.name).style.display="inline";
		return false;
	} 
	document.getElementById("errorint_"+elem.name).style.visibility="hidden";
	document.getElementById("errorint_"+elem.name).style.display="none";
	return true;
}

function CheckList (elem, str){
	if (elem.options.selectedIndex == 0) {
		alert(str);
		elem.focus();
		return false;
	}
	return true;
}

function CheckRadio(elem, str){
	for (i=0; i<elem.length; i++){
		if (elem[i].checked) {
			i=true;
			return true;
		}
	}
				
	alert(str);
	elem[0].focus();
	return false;
}

function CheckRange(elem, minval, maxval,str) {

	if (elem.value == '') {
		alert(str);
		elem.focus();
		return false;
	}

	var test = parseFloat(elem.value);
	if (isNaN(test) || test < minval || test > maxval) {
		alert(str);
		elem.focus();
		return false;
	}

	return true;
}

function testfunc() {

	return false;
}

/****************************************************************/
// Returns true if the date has correct number of days for the month

function isDateValid(ctrlday, ctrlmonth, ctrlyear, fieldname) {
  // Ensure valid month and set maximum days for that month...
  day = ctrlday.value;
  month = ctrlmonth.value;
  year = ctrlyear.value;

  if( (month == 1) || (month == 3) || (month == 5) || 
	  (month == 7) || (month == 8) || (month == 10) || 
	  (month == 12) ) { monthdays = 31 }
  else if( (month == 4) || (month == 6) || (month == 9) ||
		   (month == 11) ) { monthdays = 30 }
  else if(month == 2) { 
	monthdays = ((year % 4) == 0) ? 29 : 28; 
  }
  if(day > monthdays) {
	alert( "Please enter a valid date for " + fieldname + " - the month you have selected has only " + monthdays + " days.");
	blnSubmit = false;
	ctrlday.focus();
	return false;
  }
  if(day=='' || month=='' || year=='') {
	alert( "Please enter day, month and year fields for " + fieldname + ".");
	blnSubmit = false;
	ctrlday.focus();
	return false;
  }
  return true;
}

/****************************************************************/
// Returns true if the date has correct number of days for the month, NO warning
// alert is displayed, but a message on the page is displayed instead and 'false' is returned...

function isDateValidMsgNotAlert(ctrlday, ctrlmonth, ctrlyear, fieldname) {
  // Ensure valid month and set maximum days for that month...
  day = ctrlday.value;
  month = ctrlmonth.value;
  year = ctrlyear.value;

  if( (month == 1) || (month == 3) || (month == 5) || 
	  (month == 7) || (month == 8) || (month == 10) || 
	  (month == 12) ) { monthdays = 31 }
  else if( (month == 4) || (month == 6) || (month == 9) ||
		   (month == 11) ) { monthdays = 30 }
  else if(month == 2) { 
	monthdays = ((year % 4) == 0) ? 29 : 28; 
  }
  if(day > monthdays) {
	document.getElementById("errordatevalid_"+fieldname).style.visibility="visible";
	document.getElementById("errordatevalid_"+fieldname).style.display="inline";
	return false                                                                                  
  }
  if(day=='' || month=='' || year=='') {
	document.getElementById("errordatevalid_"+fieldname).style.visibility="visible";
	document.getElementById("errordatevalid_"+fieldname).style.display="inline";
	return false;
  }
  document.getElementById("errordatevalid_"+fieldname).style.visibility="hidden";
  document.getElementById("errordatevalid_"+fieldname).style.display="none";
  return true;
}

/****************************************************************/
// Returns true if the start date earlier than the end date

function compareDates(startmonth, startyear, endmonth, endyear) {
  // Ensure valid month and set maximum days for that month...
  startdate = new Date(startyear.value, startmonth.value, 1);
  enddate = new Date(endyear.value, endmonth.value, 1);

  if(startdate >= enddate) {
	alert( "The end date should be later than the start date.");
	blnSubmit = false;
	startmonth.focus();
	return false;
  }
  return true;
}

/****************************************************************/
// Returns true if the start date earlier than the end date, NO warning
// alert is displayed, but a message on the page is displayed instead and 'false' is returned...

function compareDatesMsgNotAlert(FirstDateMonth, FirstDateYear, SecondDateMonth, SecondDateYear, CompareType) {
  // Ensure valid month and set maximum days for that month...
  FirstDatedate = new Date(FirstDateYear.value, FirstDateMonth.value, 1);
  SecondDatedate = new Date(SecondDateYear.value, SecondDateMonth.value, 1);

	if (CompareType == "FirstDate<SecondDate") {
		if(FirstDatedate >= SecondDatedate) {
			document.getElementById("errorcompdate").style.visibility="visible";
			document.getElementById("errorcompdate").style.display="inline";
					return false;
			}else {
			document.getElementById("errorcompdate").style.visible="hidden";
			document.getElementById("errorcompdate").style.display="none";
					return true;
		}
	}else if (CompareType == "FirstDate<=SecondDate") {
		if(FirstDatedate > SecondDatedate) {
			document.getElementById("errorcompdate").style.visibility="visible";
			document.getElementById("errorcompdate").style.display="inline";
					return false;
			}else {
			document.getElementById("errorcompdate").style.visible="hidden";
			document.getElementById("errorcompdate").style.display="none";
					return true;
		}
	}
	
}

