// The following function accepts a string and search for instances of 
// stripchar, if replacechar is not empty then it will replace the 
// stripchar with replacechar and return the string

// Unfortunately because javascript does not support any include or
// uses clauses I have had to include this function here

function dostripChar (str, stripChar, replaceChar)
  {
  var outStr = new String ();
  var tempArray = str.split(stripChar);

  for (i=0; i < tempArray.length; i++)
    {
      if (i != tempArray.length)
        outStr += tempArray[i] + replaceChar;
    }
  return outStr;
  }

function Replace( str, strFind, strReplace, strOpts )
{
	if( strOpts==null )
		strOpts=""
		
	if( strOpts=="" )
	{
		str = String(str);
		strFind = String(strFind);
	    iStart = 0;
	    
		while(true)
		{
			var iFind = str.toUpperCase().indexOf( strFind.toUpperCase(), iStart );
			if( iFind<0 )
				break;
				
			var s1 = str.substr(0,iFind);
			var s2 = str.substring(iFind+strFind.length);
			str = s1 + strReplace + s2;
			iStart = iFind+strReplace.length+1;
		}
	}
	else if( strOpts=="re" )
	{
		var re = new RegExp( strFind, "i" );
	
		while( str.search( re )>=0 )
			str = str.replace( re, strReplace );
	}
	
	return str;
}

// The following function should be used for the Clear buttons on any largish forms.
// It checks that the visitor does want to lose all the info they have just entered.
// User the FORM ONRESET property and return the value of this function to decide if
// form is reset

function doClear ()
  {
  return confirm ('Are you sure you want to clear the form and lose all data?');
  }

// The following function accepts a form ID (name - string) and a layer ID (name - string) using
// these values it returns the form object (for both browsers)

function getFormObject(fID, lID)
  {
  if (self.document.all)
    return self.document.forms[fID];
  else
    {
      if (lID == '')
        return self.document.forms[fID];
      else
        return self.document.layers[lID].document.forms[fID];
    }
  }

// The following function just matches two fields (both converted to lowercase) and
// returns true or false depending on the match

function checkStringMatch(Str1, Str2)
  {
    if (Str1.toLowerCase() == Str2.toLowerCase())
      return true;
    else
      return false;
  }

// The following functions check valid dates

function DatePosition(dateString,dateType)
{
/*
   function DatePosition 
   parameters: dateString dateType
   returns: integer (-1, 0, 1)
   
   dateString is a date passed as a string in the following
   formats:

   type 1 : 19970529
   type 2 : 970529
   type 3 : 29/05/1997
   type 4 : 29/05/97
   type 5 : 05/29/1997
   type 6 : 05291997
   type 7 : 052997
   
   dateType is a numeric integer from 1 to 7, representing
   the type of dateString passed, as defined above.

   Returns -1 if the date passed is behind todays date
   Returns 0 if the date passed is equal to todays date
   or if dateType is not 1 to 7
   Returns 1 if the date passed is ahead of todays date
   
   Added Y2K checking.  (Works for any century cross over)
*/


    var now = new Date();
    var today = new Date(now.getYear(),now.getMonth(),now.getDate());
    var century = parseInt(now.getYear()/100)*100;
        
    if (dateType == 1)
        var date = new Date(dateString.substring(0,4),
                            dateString.substring(4,6)-1,
                            dateString.substring(6,8));
    else if (dateType == 2)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(0,2)))
        {
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(2,4)-1),
                            dateString.substring(4,6));
        }
        else
        {
            var date = new Date(century-100+parseInt(dateString.substring(0,2)),
                            parseInt(dateString.substring(2,4)-1),
                            dateString.substring(4,6));
        }
        
    }
    else if (dateType == 3)
        var date = new Date(dateString.substring(6,10),
                            dateString.substring(3,5)-1,
                            dateString.substring(0,2));
    else if (dateType == 4)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(6,8)))
        {
            document.write(century+parseInt(dateString.substring(6,8)),'<P>');
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(3,5)-1),
                            dateString.substring(0,2));
        }
        else
        {
            document.write(century-100+parseInt(dateString.substring(6,8)),'<P>');
            var date = new Date(century-100+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(3,5)-1),
                            dateString.substring(0,2));
        }
        
    }
    else if (dateType == 5)
        var date = new Date(dateString.substring(6,10),
                            dateString.substring(0,2)-1,
                            dateString.substring(3,5));
    else if (dateType == 6)
        var date = new Date(dateString.substring(4,8),
                            dateString.substring(0,2)-1,
                            dateString.substring(2,4));
    else if (dateType == 7)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(4,6)))
        {
            document.write('datestring Century:',century+parseInt(dateString.substring(4,6)),'<P>');
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(0,2)-1),
                            dateString.substring(2,4));
        }
        else
        {
            document.write('datestring Century:',century-100+parseInt(dateString.substring(4,6)),'<P>');
            var date = new Date(century-100+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(0,2)-1),
                            dateString.substring(2,4));
        }
        
    }
    else
        return false;

    if (date < today)
    {
        //document.write(date.toString(),' is behind ',today.toString(),'<P>');
        return -1;
    }
    else if (date > today)
    {
        //document.write(date.toString(),' is ahead of ',today.toString(),'<P>');
        return 1;
        
    }
    else
    {
        //document.write(date.toString(),' is the same as ',today.toString(),'<P>');
        return 0;
    }
}

function IsValidDMY(iDay,iMonth,iYear)
{
  if (String(iDay)=="" || String(iDay)=="undefined" || String(iDay)==null)
    return false;

  if (String(iMonth)=="" || String(iMonth)=="undefined" || String(iMonth)==null)
    return false;

  if (String(iYear)=="" || String(iYear)=="undefined" || String(iYear)==null)
    return false;
    
   iDay = Number(iDay);
   iMonth = Number(iMonth);
   iYear = Number(iYear);

   if (isNaN(iDay))
    return false;

   if (isNaN(iMonth))
    return false;

   if (isNaN(iYear))
    return false;

    //Check Month between 1 - 12

      if (iMonth < 1 || iMonth > 12)
        return false;

    // Check days within range for the month
	
	  switch(iMonth)
	   {
		case 1: max=31;break;
        case 2:	max=28;break;
		case 3: max=31;break;
		case 5: max=31;break;
		case 7: max=31;break;
		case 8: max=31;break;
		case 10: max=31;break;
		case 12: max=31;break;			
		default: max=30;break;
	   }
	
	  if( iDay>max )
		return false;
		
      if(iYear<1900 && iYear>99)
        return false;
        
   return true;	
}


// The following function checks that the string passed to it is a valid email. It assumes
// that the email parameter is not empty.
// Current email validation is simple it checks for the presence of an '@' sign and at least one full stop, it also
// check that the characters before the '@' is >= 2 and characters between the '@' and '.' are at least two characters
// This could be extended to include an array of valid top level domains but seems unnecessary in the long term.
// The return value is true or false depending on the validity of the email


function checkValidEmail (email)
  {
    var atint = 0;
    var stopint = 0;
    var valid = false;

    atint = email.indexOf('@',0);

    // check only one '@' sign in address
     if (email.indexOf('@',atint+1) == -1)
      {     
      stopint = email.indexOf('.',atint+1);

        if (atint != -1 && atint >= 2)
          {
            if (stopint != -1 && stopint >= 5)
              valid = true;
          }
      }
  return valid;
  }

// The following function checks a password does not include certain invalid chars - currently only spaces

function checkValidPassword (pwd)
  {
  var invalid = " ";

    if(pwd.value.indexOf(invalid) > -1)
      return false;
    else
      return true;
  }

function IsValidFromToDate(FDay, FMonth, FYear, TDay, TMonth, TYear)
 {
  if (FDay!="" && FMonth!="" && FYear!="" && TDay!="" && TMonth!="" && TYear!=""
      && !isNaN(FDay) && !isNaN(FMonth) && !isNaN(FYear) && !isNaN(TDay) && !isNaN(TMonth) && !isNaN(TYear))
   {
    try
     {
      if (FYear > TYear)
        throw "Bad Year"
        
      if (FYear == TYear)
       {
        if (FMonth > TMonth)
          throw "Bad Month"
        
        if (FMonth == TMonth)
          if (FDay >= TDay)
            throw "Bad Day"
       }
    
      return true;
     }
   catch(e)
     {
      return false;
     }
   }
  else
    return true;
 }

function IsAlphaNumeric(Str)
  {         
   var NonAlphaSearch = new RegExp("[^a-zA-Z0-9_]");

    if (NonAlphaSearch.test(Str))       
      return false;
     else
      return true;
      
     NonAlphaSearch = null;
  }

// The following function accepts a form ID (name - string) and a layer ID (name - string) and then
// validates this form's values. Using hidden input values within the specified form it checks
// for 'required', 'email', and 'password' values to check whether these are valid. If you do not want
// to check passwords for instance remove the tag from the HTML in the form. The function returns
// true or false depending on whether validation errors occurred

// The customerrorMsg parameter allows you to perform custom validation before passing it to the 
// general function. This is expected to be a formatted string with carriage returns and will be
// added at the end of the general validation message.

function checkAndSubmit(formID, layerID, customerrorMsg, ReplaceQuals){
  //check required fields
  var errormsg = new String ();
  var errorcount = 0;
  var lformID = formID;
  var llayerID = layerID;
  var infoform = getFormObject(lformID,llayerID);

  if (!infoform) {
    alert('\t\nThere is a serious problem in this page. Form cannot be referenced!');
    return false;
    }

    errormsg = 'This form cannot be submitted.\n\n';
    errormsg += 'The following error(s) occurred:\n';
    errormsg += '________________________________________________          \n\n';

 if (infoform.required)
    {
    // Do checks - the following checks for required fields which are specified in the hidden form input type required

    var requirearray = infoform.required.value.split(',');

      for (var i = 0 ; i < requirearray.length ; i ++){

      var req =  requirearray[i];
      var formel = infoform[req];

      switch (formel.type)
        {
        case 'text' :
        case 'password' : if (formel.value == '' || formel.value == null){errorcount++;errormsg += dostripChar(req, '_', ' ') + 'must be specified.\n';} break;
        case 'select-one' : if (formel.selectedIndex == 0) {errorcount++;errormsg += dostripChar(req, '_', ' ') + 'must be specified.\n';} break;
        case 'textarea' : if (formel.value == '' || formel.value == null) {errorcount++;errormsg += dostripChar(req, '_', ' ') + 'must be specified.\n';} break;
        case 'file' : if (formel.value == '' || formel.value == null) {errorcount++;errormsg += dostripChar(req, '_', ' ') + 'must be attached.\n';} break;
        }
       }
    }

  if (infoform.checkemail)
    {
    // Do checks - the following checks for email fields which are specified in the hidden form input type email
    var emailarray = infoform.checkemail.value.split(',');

    for (var y = 0 ; y < emailarray.length ; y ++)
      {
       var mail =  emailarray[y];
       var formem = infoform[mail];

         if (formem.value != '')
           {
             if (checkValidEmail (formem.value)==false)
               {
                errormsg += dostripChar(mail, '_', ' ') + ' is not a valid email address (i.e. name@domain.com)\n';
                errorcount++;
               }
           }
      }
    }

  if (infoform.alphanumeric)
    {
    // Do checks - the following checks for alphanumeric fields which are specified in the hidden form input type alphanumeric
    var alphaarray = infoform.alphanumeric.value.split(',');

    for (var z = 0 ; z < alphaarray.length ; z++)
      {
       var an =  alphaarray[z];
       var formam = infoform[an];

         if (formam.value != '')
           {
             if (IsAlphaNumeric(formam.value)==false)
               {
                errormsg += dostripChar(an, '_', ' ') + 'must be made up of numbers or characters only.\n';
                errorcount++;
               }
           }
      }
    }

  if (infoform.checkpassword)
    {
     // Do checks - the following checks for matching fields (i.e. passwords and confirmations) which are specified in the hidden form input type password

    var passArray = infoform.checkpassword.value.split(',');

    var Pass1 = passArray[0];
    var Pass2 = passArray[1];

    var tempStr1 = infoform[Pass1];
    var tempStr2 = infoform[Pass2];

     if (checkValidPassword(tempStr1))
      {
       if (checkStringMatch (tempStr1.value, tempStr2.value)==false)
        {
         errormsg += dostripChar(Pass1, '_', ' ') + ' and ' + dostripChar(Pass2, '_', ' ') + ' must match.\n';
         errorcount++;
        }
      }
     else
      {
         errormsg += dostripChar(Pass1, '_', ' ') + ' contains invalid characters.\n';
         errorcount++; 
      }
    } 

  // Currently this can only handle one date, with the fields required status pre-checked and params passed
  // Day, Month, Year

  if (infoform.checkdate)
    {
    var datearray = infoform.checkdate.value.split(',');

     for (var q = 0 ; q < datearray.length ; q++)
      {
       var FieldName = datearray[q];    
       var Day = infoform[String(FieldName + "_Day")].value;
       var Month = infoform[FieldName + "_Month"].value;
       var Year = infoform[FieldName + "_Year"].value;

         if (Day != "" && Month != "" && Year != "")
           {
             if (!IsValidDMY(Day, Month, Year))
              {
               errormsg += dostripChar(FieldName, '_', ' ') + ' is not a valid date (dd/mm/yyyy)\n';
               errorcount++;
              }
           }
         else
          {
            if (Day == "" && Month == "" && Year == "")
              {
                // That's okay
              }
            else
              {
               // All three date field values must be entered to constitute a valid date
               errormsg += dostripChar(FieldName, '_', ' ') + ' is not a valid date (dd/mm/yyyy)\n';
               errorcount++;
              }
          }
      }       
    } 

  // Currently this can only handle one date, with the fields required status pre-checked and params passed
  // Day, Month, Year

  if (infoform.check4digitdate)
    {
    var date4digitarray = infoform.check4digitdate.value.split(',');

     for (var q = 0 ; q < date4digitarray.length ; q++)
      {
       var tFieldName = date4digitarray[q];    
       var tDay = infoform[String(tFieldName + "_Day")].value;
       var tMonth = infoform[tFieldName + "_Month"].value;
       var tYear = infoform[tFieldName + "_Year"].value;
       tFieldName = dostripChar(tFieldName, '_', ' ');
       
       if (ReplaceQuals)
         tFieldName = Replace(tFieldName, "Q", "Qualification");

         if (tDay != "" && tMonth != "" && tYear != "")
           {
            if (tYear.length == 4)
             {
              if (!IsValidDMY(tDay, tMonth, tYear))
               {
                errormsg += tFieldName + ' is not a valid date (dd/mm/yyyy)\n';
                errorcount++;
               }
             }
            else
             {
              errormsg += tFieldName + ' must have a 4 digit year (dd/mm/yyyy)\n';
              errorcount++;              
             }
           }
         else
          {
            if (tDay == "" && tMonth == "" && tYear == "")
              {
                // That's okay
              }
            else
              {
               // All three date field values must be entered to constitute a valid date
               errormsg += tFieldName + ' is not a valid date (dd/mm/yyyy)\n';
               errorcount++;
              }
          }
      }       
    }

  if (customerrorMsg != '')
    {
    errormsg += customerrorMsg + '\n';    
    errorcount++; 
    }   

  errormsg += '________________________________________________          \n\n';
  errormsg += 'Please amend the error(s) and re-submit the form.\n';
  
  if (errorcount > 0){
    alert(errormsg);
    return false;
    }
  else
    return true;
  }  
  
function CheckAndSetFocus(what,e,max,action) {
    if (document.layers) {
        if (e.target.value.length >= max)
            eval(action);
    }
    else if (document.all) {
        if (what.value.length > (max-1))
            eval(action);
    }
}  

  function CheckOther(SelObj, OtherObj, LayerName1, LayerName2)
    {
     // Cannot check the value of other as is id so assume that Other is always last in the list!
      if (document.all(SelObj).selectedIndex == document.all(SelObj).options.length-1)
        {
         document.all(LayerName1).style.visibility = "visible";
           if (LayerName2!=null)
             document.all(LayerName2).style.visibility = "visible";
        }
      else
        {
         document.all(OtherObj).value = "";
         document.all(LayerName1).style.visibility = "hidden";
           if (LayerName2!=null)
             document.all(LayerName2).style.visibility = "hidden";
        }
    }
    
function CheckDate(Day, Month, Year, Title)
  {
      var tDay = String(Day);
      var tMonth = String(Month);
      var tYear = String(Year);
      
      // Check year is 4 digits
      if (tYear.length != 4)
        return Title + " must have a 4 digit year (dd/mm/yyyy)\n";  
      
      // Pad any single char fields
        if (tDay.length==1)
          tDay = "0" + tDay;
        if (tMonth.length==1)
          tMonth = "0" + tMonth;
          
      // If Values entered for all fields
      if (tDay != "" || tMonth != "" || tYear != "")
        {
         if (IsValidDMY(tDay,tMonth,tYear))
          {
            //if (DatePosition(tMonth + tDay + tYear,6)==1)
              return "";
            //else
            //  return Title + " must be greater than today\n"; 
          }
         else
           return Title + " is not a valid date (dd/mm/yyyy)\n";  
       }         
  }