var errTest = true; //set to 'false' to turn error reporting off

var jsLibrary = true;
var defaultEmptyOK = false;

var blankFields = "The following fields were blank:-\n\n";
var UKPostCodeDelimiter = "|";
var UKPostCodes = "AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GU|HA|HD|HG|HP|HR|HU|HX|IG|IP|IV|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO";
var whitespace = "\t\n\r ";

var iNumeric = "This field must contain numeric characters only.\nPlease re-enter it now."

var mPrefix = "You did not enter a value into the ' "
var mSuffix = " ' field.\n\n This is a required field. Please enter it now."

var pAddress = "the home address."
var pAddrMth = "the number of months."
var pAddrYr = "the number of years at this address."
var pAnnPay = "gross annual pay."
var pBank = "the name of the bank.";
var pBankAc = "your name as shown on the bank statement.";
var pBankAcNum = "the bank account number.";
var pBankAcOpen = "when the bank account was opened.";
var pBankAddr = "the address of the bank.";
var pBankCGCard = "whether you hold a cheque guarantee card.";
var pBankSCode = "the bank's sort code (like 20-13-36).";
var pCCJs = "whether you have any CCJs."
var pCCJDets = "details of any county court judgments (CCJs), defaults etc. including dates and amounts.";
var pCCJnum = "how many CCJs."
var pCCJpay = "whether you have any proof of payment or satisfaction of the CCJ(s)."
var pCouncilTax = "the monthly council tax payment.";
var pCCardCo = "the name of the credit card company.";
var pCCardExp = "the expiry date of the credit card.";
var pCCardHeldYr = "the number of years the credit card has been held.";
var pCCardLimit = "the limit on the credit card.";
var pCCardName = "your name exactly as shown on the credit card.";
var pCCardType = "the type of credit card held, if any.";
var pDay = "a day number."
var pDependents = "the number of dependents."
var pDepntsAge = "the age(s) of the dependents."
var pEmail = "a valid email address (like foo@bar.com).";
var pEmpAddr = "the employers name & address.";
var pEmpTime = "how long employed there.";
var pEmpTimeYr = "the number of years employed there.";
var pEndowment = "the monthly premium for any mortgage related endowment policy.";
var pEntryPrompt = "Please enter "
var pFirstName = "the first name(s)."
var pFullName = "the first and last names."
var pHmPhone =	"a valid landline phone number (like 01234 12345,  0121 234 1234  or  020 7890 1234)."
var pHrsWkd = "how many hours worked per week."
var pHseVal = "the approximate value of the house."
var pInsurance = "any regular insurance premiums.";
var pLandlord = "the name & address of the landlord or Building Society"; 
var pLastName = "the last name."
var pLoanAmt = "the amount of loan required.";
var pLoanArrears = "details of the arrears on the above credit agreements.";
var pLoanPayout = "whether the loan should be paid out by cheque or bank transfer.";
var pLoanProtect = "whether loan payment protection against sickness, accident and redundency is required.";
var pLoanPurp = "the purpose for the loan.";
var pLoanTerm = "over how long you want to repay the loan.";
var pMbPhone =	"a valid mobile phone number (like 07759 123456)."
var pMessage = "a message.";
var pMonth = "a month number.";
var pMortArrears = "the amount of any arrears.";
var pMortMth = "the monthly mortgage payment.";
var pMortOS = "the outstanding mortgage balance";
var pMortRent = "the monthly mortgage or rent payment.";
var pMortUTD = "whether the mortgage payments are up to date.";
var pNetPay = "the net take home pay.";
var pOcc = "the occupation.";
var pOccupancy = "the type of occupancy.";
var pOtherCredit = "whether you have any existing credit.";
var pOtherCreditDets = "the company name, outstanding balance, monthly payments, if paid by S/O or D/D and whether you intend to settle.";
var pOtherCreditPaid = "whether the repayments on the above credit are up to date.";
var pOtherPay = "any other regular income.";
var pPCode = "a valid postcode (like WA10 1JP).";
var pPrevAddr = "the previous home address.";
var pPrevEmpAddr = "the previous employers name & address.";
var pPrevOcc = "the previous occupation.";
var pPropType = "the type of property.";
var pSourceOtherPay = "the source of the other regular income.";
var pTitle = "a title (like mr, mrs or ms).";
var pTenure = "whether the property is freehold or leasehold.";
var pYear = "a year number.";

var sAddress = " Address";
var sAddrMth = "Time at address - Months";
var sAddrYr = "Time at address - Years";
var sCCJs = "County Court Judgments (CCJs)";
var sCCJnum = "How many CCJs";
var sCCJpay = "Proof of payment of CCJs";
var sDependents = "Number of dependents";
var sDepntsAge = "Age of dependents";
var sEmpAddr = "Name of Employer & Works Address";
var sEmpYr = "Time with employer - Years";
var sEmpMth = "Time with employer - Months";
var sFirstName = "First name";
var sHmPhone = "Home phone number";
var sHseVal = "Estimated house value";
var sIncome = "Income";
var sLandlord = "Name & Address of Landlord or Building Society"; 
var sMarital =  "Marital status";
var sMessage = "Message";
var sMortOS = "Mortgage outstanding";
var sMortUTD = "Mortgage payments up to date";
var sName = "Name";
var sOcc = "Occupation";
var sOccupancy = "Occupancy";
var sPCode = "Post code";
var sPrevAddr = "Previous address";
var sPrevAddrMth="Time at previous address-Months";
var sPrevAddrYr="Time at previous address-Years";
var sPrevEmp = "Time with previous employer";
var sPrevEmpAddr = "Name of Previous Employer & Works Address";
var sPrevOcc = "Previous Occupation";
var sPrevEmpPhone = "Previous Employers Phone Number";
var sTitle = "Title";

	function checkPostCode (chek,theField) {
		if (!isValidPCode(chek,theField)) {
		   return false;	
			}
		   return true;
		}

function isValidPCode(chek,theField) {

var postCode =  stripWhitespace (chek);
var isPostCode = isPCode(postCode);
	   if (isPCode(postCode) == false) {
	   theField.focus();
	   theField.select();
           alert("This field must be a valid postcode (like L10 4JP).\n\nPlease re-enter it now!");
	   return postCode;

        }

    else {
	if (isPostCode.substring(0, 4).toUpperCase() == "BFPO") {
	n = isPostCode.length-4;
	return (reformat(isPostCode.toUpperCase(), "", 4, " ", n));
	}
	    else {
		n = isPostCode.length-3;
		return (reformat(isPostCode.toUpperCase(), "", n, " ", 3));
		}
	}
}
function isPCode(String) {
    newString = ""; 
    count = 0;	    
    space = 0;

	ch = String.substring(0, 4).toUpperCase();
	if (ch == "BFPO") {
	    return String.toUpperCase();
	}
    n = String.length - 3;
	ch = String.substring(n, n+1);
        if (!isDigit(ch)) {
	    return false;
	}
	ch = String.substring(n+1, n+2);
	if (!isLetter(ch)) {
	    return false;
	}
	ch = String.substring(n+2, n+3);
	if (!isLetter(ch)) {
	    return false;
	}
    
    for (i = 0; i < String.length; i++) {
        ch = String.substring(i, i+1);
        if (isLetter(ch) || isDigit(ch)) {
            	newString += ch;
		count++;
        }
    }

	if (count <= 4 || count >= 8) {
	   return false;
	}

	else {
	return newString;

	}
}

function isWhitespace (s)

{   var i;

    if (isEmpty(s)) return true;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    return true;
}

function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}


function stripCharsInBag (s, bag) {
    var i;
    var returnString = "";

    for (i = 0; i < s.length; i++)
    {   
         var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}


function reformat (s)

{   var arg;
    var sPos = 0;
    var resultString = "";
    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}


function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isNew(theField, theTime) {
    return (theField.value <= theTime)
}


function isPostCode(s)
{   if (isEmpty(s)) 
       if (isPostCode.arguments.length == 1) return defaultEmptyOK;
       else return (isPostCode.arguments[1] == true);
    return ( (UKPostCodes.indexOf(s) != -1) &&
             (s.indexOf(UKPostCodeDelimiter) == -1) )
}

function isDate(i,theForm,theField,build) {

	i = i-0;
	a = theForm.elements[i].options[theForm.elements[i].selectedIndex].text;
	b = theForm.elements[i+1].options[theForm.elements[i+1].selectedIndex].text;
	c = theForm.elements[i+2].options[theForm.elements[i+2].selectedIndex].text;

	if (a == "dd") {
	 if (build)  {
		return warnEmpty (theForm.elements[i],"Date of birth - day");
		     }
	   theField.value="";
	   theForm.elements[i].focus();
	   return false;
	}

	if (b == "mm") {
	 if (build)  {
		return warnEmpty (theForm.elements[i+1],"Date of birth - month");	
		     }
           theField.value="";
	   theForm.elements[i+1].focus();
	   return false;
	}

	if (c == "yyyy") {
	 if (build)  {
		return warnEmpty (theForm.elements[i+2],"Date of birth - year");
		     }
           theField.value="";
	   theForm.elements[i+2].focus();
	   return false;
	}

	d = a + '/' + b + '/' + c;
	Day   = a-0;
	Month = b-0;
	Year  = c-0;

	TotalDays = (Month + (Month > 7)) % 2 + 30;

     if (Month == 2) {

	if (((Year % 4 == 0) && (Year % 100 != 0)) || (Year % 400 == 0))
	   TotalDays = 29; 
	else
	   TotalDays = 28;

	}

	if (Day > TotalDays) {
	   theForm.elements[i].selectedIndex = 0;
	   theForm.elements[i+1].selectedIndex = 0;
	   theForm.elements[i+2].selectedIndex = 0;
	   alert('Sorry!\n\n' + d + '\nis NOT a valid date.\n\nPlease re-enter.');
	   theForm.elements[i].focus();
	   return false;

        }

	if (build) 	theField.value = d; //this sets the value of the hidden field

return true;
 }

function warnEmpty (theField, s) {

     var errFuncOld =errFunc;
     errFunc=errFunc + "/warnEmpty";
//    blankFields = blankFields + theField.name + "\n";
//    document.forms[1].elements["blanks"].value = blankFields;
    theField.focus()
//    theField.select()
    alert(mPrefix + s + mSuffix)
    errFunc = errFuncOld;
    return false
}

function checkString (theField, s, emptyOK)

{
      var errFuncOld =errFunc;
      errFunc=errFunc + "/checkString";
    if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
   if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value)) {
       errFunc = errFuncOld;
       return warnEmpty (theField, s); }
    else {
        errFunc = errFuncOld;
	return true;
	}
}

function checkRequiredFields(theField,s)
{
    var errFuncOld =errFunc;
    errFunc=errFunc + "/checkRequiredFields";
   if(!theField.options[theField.selectedIndex].value) {
    theField.focus();
    return warnEmpty (theField, s);
    errFunc = errFuncOld;
    return false; 
                }     else {
        errFunc = errFuncOld;
	return true;
	           }
}

function promptEntry (s)
{   window.status = pEntryPrompt + s
}

function clearStatus()
{   window.status = ""
}

function activate(field) {
  field.disabled=false;
//  if(document.styleSheets)field.style.visibility  = 'visible';
  field.focus(); }
function first_choice(selection) {
  return selection.selectedIndex >= 2; }
function second_choice(selection) {
  return selection.selectedIndex == 1; }
function third_choice(selection) {
  return selection.selectedIndex >= 1; }

function process_ccjs(selection,theField,theSelectField) {
  if(first_choice(selection)) {
    theField.value = '';
    theSelectField.selectedIndex = 0;
	return true;
	}
  if(third_choice(selection)) {
    activate(theField); }
  else {
    theField.disabled = true;    
//    if(document.styleSheets)Age_of_Dependents.style.visibility  = 'hidden';
    theField.value = '';
    theSelectField.selectedIndex = 0;}
  }

function process_choice(selection,theField) {
    var errFuncOld =errFunc;
    errFunc=errFunc + "/process_choice";
  if(first_choice(selection)) {
    activate(theField);
    errFunc = errFuncOld;
	}
  else {
    theField.disabled = true;    
//    if(document.styleSheets)Age_of_Dependents.style.visibility  = 'hidden';
    theField.value = '';
    errFunc = errFuncOld;
}}

function checkDependents(selection,theField,msg1,msg2) {
  var errFuncOld =errFunc;
  errFunc=errFunc + "/checkDependents";
  if(selection.selectedIndex == 0) {
    selection.focus();
    return warnEmpty (selection, msg1);
    errFunc = errFuncOld;
    return false;} 
  if(theField.value == '') {
    if(first_choice(selection)) {
      theField.focus();
      return warnEmpty (theField, msg2);
      errFunc = errFuncOld;
      return false; }
    else {
      errFunc = errFuncOld;
      return true; }}
  else {
    if(!first_choice(selection)) {
      alert('Incompatible selection');
      errFunc = errFuncOld;
      return false; }
    else {
      errFunc = errFuncOld;
      return true; }}}

function check_ccjs(selection,theField,s) {
  if(first_choice(selection)) {
    theField.blur();
    alert('Completion of this field is not now required');
    return; }
  if(selection.selectedIndex == 0) {
    theField.blur();
    return warnEmpty (selection,s);
    selection.focus(); }
}

function check_choice(selection,theField,s) {
    var errFuncOld =errFunc;
    errFunc=errFunc + "/check_choice";
  if(second_choice(selection)) {
    theField.blur();
    alert('Completion of this field is not now required');
    errFunc = errFuncOld;
    return; }
  if(!first_choice(selection)) {
    theField.blur();
    return warnEmpty (selection,s);
    selection.focus();
    errFunc = errFuncOld;
 }
}

function isCCJ(selection) {
  return selection.selectedIndex == 1; }

function checkTheCCJs(selection,theField,msg1,msg2) {
  if(selection.selectedIndex == 0) {
    selection.focus();
    return warnEmpty (selection, msg1);
    return false;} 
  if(theField.value == '' || theField.selectedIndex == 0) {
    if(isCCJ(selection)) {
      theField.focus();
      return warnEmpty (theField, msg2);
      return false; }
    else {
      return true; }
	 }
  else {
    if(!isCCJ(selection)) {
      alert('Incompatible selection');
      return false; }
    else {
      return true; }
	 	  	  }
	}

function checkNum(theField,s) {
	if (!isInteger(theField.value)) {
	if (isEmpty(theField.value))
	  return warnEmpty (theField, s);
	else
          return warnInvalid(theField,iNumeric);
	}
	else return true;
	}

function  processTimeAtPrevAddr(theAddress,theTimeAtAddress) {
	if(theAddress.value == '') {
	  theTimeAtAddress.blur();
	  alert('Completion of this field is not now required');
	  return;}
	}

function  processPrevAddr(theAddress,theTimeAtAddress,theField,msg1,msg2) {
	if(theAddress.value == '') {
	  theAddress.focus();
          return warnEmpty (theAddress, msg1);
	  return false;}

	if(theTimeAtAddress.value == '') {
	  theTimeAtAddress.focus();
          return warnEmpty (theTimeAtAddress, msg2);
	  return false;}

	if(theTimeAtAddress.value >= 3) {
	  theField.blur();
	  alert('Completion of this field is not now required');
	  return;}
				}

function checkPrevAddress(theTimeAtAddress,theField,msg) {
	if(theField.value == '') {
	   if(isNew(theTimeAtAddress,2))  {
	     theField.focus();
	     return warnEmpty (theField, msg);
	     return false; }
	   else {
	     return true; }
				}
	     return true;
			     }