﻿// JScript File


//**minloan Validation**//
function ValidateMinAmountRow(clientRowID, clientListID, clientCheckBoxID, invalidRowClientID)
{
    if(IsRowDisplayed(clientRowID))
        ValidateMinAmount(clientListID, clientCheckBoxID, invalidRowClientID);
}

function IsValidMinAmountRow(clientRowID, clientListID, clientCheckBoxID)
{
    if(IsRowDisplayed(clientRowID))
    {
        if(IsDropDownListSelected(clientListID) || IsCheckBoxSelected(clientCheckBoxID))
            return true;
        else
            return false;
    }
    else
        return true;
}

function ValidateMinAmount(clientListID, clientCheckBoxID, invalidRowClientID)
{
    if (IsDropDownListSelected(clientListID) || IsCheckBoxSelected(clientCheckBoxID))
        SetStyleDisplay(invalidRowClientID, 'none');
    else
        SetStyleDisplay(invalidRowClientID, '');
}

//***ButtonList Validation**/

//returns true if displayed AND selected
function IsValidButtonListRow(clientRowID, clientListID)
{
    if(IsRowDisplayed(clientRowID))
        return IsButtonListSelected(clientListID);
    else
        return true;
}

//if displayed validates fields and shows/hides error message
function ValidateButtonListRow(clientRowID, clientListID, invalidRowClientID)
{
    if(IsRowDisplayed(clientRowID))
        ValidateButtonList(clientListID, invalidRowClientID);
}

function ValidateButtonList(clientID, invalidRowClientID)
{
    if (IsButtonListSelected(clientID))
        SetStyleDisplay(invalidRowClientID, 'none');
    else
        SetStyleDisplay(invalidRowClientID, '');
}

//returns true if displayed AND selected
function IsValidDropDownListRow(clientRowID, clientDropDownListID)
{
    if(IsRowDisplayed(clientRowID))
        return IsDropDownListSelected(clientDropDownListID);
    else
        return true;
}

//if displayed validates fields and shows/hides error message
function ValidateDropDownListRow(clientRowID, clientDropDownListID, invalidRowClientID)
{
    if(IsRowDisplayed(clientRowID))
        ValidateDropDownList(clientDropDownListID, invalidRowClientID);
}

function ValidateDropDownList(clientID, invalidRowClientID)
{
    if (IsDropDownListSelected(clientID))
        SetStyleDisplay(invalidRowClientID, 'none');
    else
        SetStyleDisplay(invalidRowClientID, '');
}

//returns true is button list selected
function IsButtonListSelected(clientID)
{
    //if it's dont exist its valid
    if (document.getElementById(clientID))
    {
        var e = document.getElementById(clientID).getElementsByTagName('INPUT');
        
        for (var j=0; j < e.length; j++)
        {
            if (e[j].checked)
            {
                return true;
            }
        }
        
        return false;
     }
     else
        return true;
}

function IsButtonListSelected2(clientID)
{
    //if it's dont exist its valid
    if (document.getElementById(clientID))
    {
        var e = document.getElementById(clientID);
        
       
            if (e.checked)
            {
                return true;
            }
       
        
        return false;
     }
     else
        return true;
}

function IsCheckBoxSelected(clientID)
{
    return getElementValue(clientID);
}

//returns true is drop down list selected
function IsDropDownListSelected(clientID)
{
    //if it's dont exist its valid
    if (document.getElementById(clientID))
    {
        if(getElementValue(clientID) == "")
            return false;
        else
            return true;
    }
    else
        return true;
}

// Validates an integer field,
// ensuring only numbers are added.
function ValidateInteger(objTextBox)
{
    var strText = objTextBox.value;

    var strCharCode = 0;
    var strNewNum = '';

    // remove all non numeric characters.
    for (var i = 0; i < strText.length; i++) {
        intCharCode = strText.charCodeAt(i);

        if ((48 <= intCharCode) && (intCharCode <= 57))
            strNewNum = strNewNum.concat(strText.charAt(i));
    }

    //then copy the new value into the textbox
    objTextBox.value = strNewNum;
}
    
// Validates a currency value field
// adding commas to clarify the value
// and ensuring only numbers, with a
// maximum of 2 decimal places are
// added.
function ValidateCurrency(objTextBox)
{
    var strText = objTextBox.value;

    var blnDecimalFound = false;
    var intDecimalCount = 0;
    
    var strCharCode = 0;
    var strNewNum = '';
    
    var strCommaNum = '';
    var intCurrentPos = 0;
    
    // remove all non numeric characters, with
    // the exception of a single decimal point
    // and a maximum of 2 decimal places.
    for (var i=0; i < strText.length; i++)
    {
        intCharCode = strText.charCodeAt(i);

        if ((48 <= intCharCode) && (intCharCode <= 57))
        {
            if (blnDecimalFound == true)
            {
                if (intDecimalCount > 1)
                {
                    alert('only 2 decimal places are permitted.');
                    break;
                }
                else
                {
                    strNewNum = strNewNum.concat(strText.charAt(i));
                    intDecimalCount++;
                }
            }
            else
            {
                strNewNum = strNewNum.concat(strText.charAt(i));
            }
        }
        else if ((intCharCode == 46) && (blnDecimalFound == false))
        {
            strNewNum = strNewNum.concat(strText.charAt(i));
            blnDecimalFound = true;
        }
    }

    //Go through and add the commas
    intCurrentPos = strNewNum.indexOf('.');
    if (intCurrentPos == -1)
    {
        intCurrentPos = strNewNum.length;
    }
    else
    {
        strCommaNum = strNewNum.substring(strNewNum.indexOf('.'));
    }
    for (var i = intCurrentPos; i > 0; i = i - 3)
    {
        if (i > 3)
        {
            strCommaNum = ',' + strNewNum.substring(i-3,i) + strCommaNum;
        }
        else
        {
            strCommaNum = strNewNum.substring(0,i) + strCommaNum;
        }
    }
    //then copy the new value into the textbox
    objTextBox.value = strCommaNum;
}

//**Text Field Validation**/
function ValidateNameField(clientID, invalidRowClientID, checkBlank)
{
    if (IsValidNameField(clientID, checkBlank))
        SetStyleDisplay(invalidRowClientID, 'none');
    else
        SetStyleDisplay(invalidRowClientID, '');    
}


//Validate text field - turn corresponding message on/off
function ValidateField(clientID, invalidRowClientID, checkBlank)
{
    if (IsValidField(clientID, checkBlank))
        SetStyleDisplay(invalidRowClientID, 'none');
    else
        SetStyleDisplay(invalidRowClientID, '');    
}

function ValidateRowField(clientID, invalidRowClientID, rowClientID, checkBlank)
{
    //alert('clientid ' + clientID);
    //alert('rowClientid ' + rowClientID);
    //alert('invalidRowClientID ' + invalidRowClientID);

    if (GetStyleDisplay(rowClientID) != 'none')
    {
        if (IsValidField(clientID, checkBlank))
            SetStyleDisplay(invalidRowClientID, 'none');
        else
            SetStyleDisplay(invalidRowClientID, '');    
    }            
}

function IsValidNameField(clientID, checkBlank)
{
    document.getElementById(clientID).value = LTrim(RTrim(getElementValue(clientID)));

    var text = getElementValue(clientID);
    
    if (text==null||text==""&&checkBlank)
        return false;
    else if(text.length==1)
        return false;
    else
        return true;    
}

function IsValidField(clientID, checkBlank)
{
    var text = getElementValue(clientID);
    
    if (text==null||text==""&&checkBlank)
        return false;
    else
        return true;    
}

function IsValidRowField(clientID, rowClientID, checkBlank)
{
    if (GetStyleDisplay(rowClientID) != 'none')
    {
        var text = getElementValue(clientID);
    
        if (text==null||text==""&&checkBlank)
            return false;
        else
            return true;    
    }
    else
        return true;
}

//**Amount Field Validation **/

function ValidateRangeAmount(clientID, invalidRowClientID, bottomValue, topValue, checkBlank)
{
    //First remove any chars if we can
    RemoveComma(clientID);
    RemovePound(clientID);
    RemoveCharacters(clientID);
    
    if (IsValidRangeAmount(clientID, bottomValue, topValue, checkBlank))
        SetStyleDisplay(invalidRowClientID, 'none');
    else
        SetStyleDisplay(invalidRowClientID, '');

}

function IsValidRangeAmount(clientID, bottomValue, topValue, checkBlank)
{
    var amount = getElementValue(clientID);

    if(!IsValidAmount(clientID, checkBlank))
        return false;
    else if (amount < bottomValue || amount > topValue)
        return false;
    else
        return true;
            
}
//Validate an amount field - turn correspnding error messsage on/off
function ValidateAmount(clientID, invalidRowClientID, checkBlank)
{        
    //First remove any chars if we can
    RemoveComma(clientID);
    RemovePound(clientID);
    RemoveCharacters(clientID);
    
    if (IsValidAmount(clientID, checkBlank))
        SetStyleDisplay(invalidRowClientID, 'none');
    else
        SetStyleDisplay(invalidRowClientID, '');
}

function ValidateAmountRow(clientRowID, clientAmountID, invalidRowClientID, checkBlank)
{
    if(IsRowDisplayed(clientRowID))
        ValidateAmount(clientAmountID, invalidRowClientID, checkBlank)
}

function IsValidAmountRow(clientRowID, clientAmountID, checkBlank)
{
    if(IsRowDisplayed(clientRowID))
        return IsValidAmount(clientAmountID, checkBlank);
    else
        return true;
}

//returns true if amount field is valid
//if checkBlank then we also check if field is empty
function IsValidAmount(clientID, checkBlank)
{
    return IsValidAmountRange(clientID, checkBlank, 1, 1000000)
}

function IsValidAmountRange(clientID, checkBlank, lower, upper)
{
    var amount = getElementValue(clientID);
    
    if (amount==null||amount=="")
    {
        if(checkBlank)
            return false;
        else
            return true;
    }
    else if (isNaN(parseInt(amount, 10)) || parseInt(amount,10) == 0)
    {
        return false;
    }
    else if (amount < lower || amount > upper)
    {
        return false;
    }
    else
        return true;
}

//Used by form to see if when a button list is selected if we should remove the error
function CheckInvalidRow(radioButtonListClientID, invalidRowClientID)
{
    if(IsButtonListSelected(radioButtonListClientID))
        SetStyleDisplay(invalidRowClientID, 'none');
}
    
//Used by form to see if when a button list is selected if we should remove the error
function CheckInvalidDropDownListRow(dropDownListClientID, invalidRowClientID)
{
    if(IsDropDownListSelected(dropDownListClientID))
        SetStyleDisplay(invalidRowClientID, 'none');
}    
    
//returns true/false depending on display property of element
function IsRowDisplayed(clientId)
{
    if (document.getElementById(clientId))
    {
        if (document.getElementById(clientId).style.display == "none")
            return false;
        else
            return true;
    }
    else
        return false;
}

function RemovePound(clientID)
{
    document.getElementById(clientID).value = getElementValue(clientID).replace(/£/,'');
}

function RemoveComma(clientID)
{
    document.getElementById(clientID).value = getElementValue(clientID).replace(/,/,'');
}

function RemoveSpace(clientID)
{
    while (document.getElementById(clientID).value.indexOf(" ")!= -1)  
    {
        document.getElementById(clientID).value = document.getElementById(clientID).value.slice (0,document.getElementById(clientID).value.indexOf(" ")) + document.getElementById(clientID).value.slice (document.getElementById(clientID).value.indexOf(" ")+1)
    }    
}

//Remove characters from field if we can
function RemoveCharacters(clientID)
{
    var amount = getElementValue(clientID);
    
    if(!isNaN(parseInt(amount, 10)) || !parseInt(amount,10) == 0)
        document.getElementById(clientID).value = parseInt(amount, 10);

}

//Are the fields required for doing a broker search valid
function IsValidBrokerSearchDetails()        
{
    //alert('IsValidBrokerSearchDetails');

    if (IsValidAmount(objForm.amountTextBox, true) &&
        IsValidAmount(objForm.mortgageBalanceTextBox, true) &&
        IsValidAmount(objForm.houseValueTextBox, true) &&
        IsValidPostCode(objForm.postCodeTextBox, objForm.postCodeRow, true) &&
        IsButtonListSelected(objForm.adverseCreditRadioButtonList))
        return true;
    else
        return false;
}

//Are the fields required for doing a broker search valid
function IsValidMortgageBrokerSearchDetails()        
{
    //alert('IsValidMortgageBrokerSearchDetails');

    if (IsValidAmount(objForm.amountTextBox, true) &&
        IsValidAmount(objForm.houseValueTextBox, true) &&
        IsValidPostCode(objForm.postCodeTextBox, objForm.postCodeRow, true) &&
        IsButtonListSelected(objForm.adverseCreditRadioButtonList) &&
        IsDropDownListSelected(objForm.mortgageTypeDropDownList) &&
        IsDropDownListSelected(objForm.employmentStatusDropDownList) &&
        IsValidButtonListRow(objForm.foundPropertyRow, objForm.foundPropertyRadioButtonList))
        return true;
    else
        return false;
}

//Are the fields required for doing a broker search valid
function IsValidMortgageBrokerSearchDetails2()        
{
    //alert('IsValidMortgageBrokerSearchDetails2');

    if (IsValidAmountRange(objForm.amountTextBox, true, 25000, 5000000) &&
        IsValidAmountRange(objForm.houseValueTextBox, true, 40000, 5000000) &&
        IsValidPostCodeRow(objForm.postCodeTextBox, true) &&
        IsButtonListSelected(objForm.adverseCreditRadioButtonList) &&
        IsDropDownListSelected(objForm.mortgageTypeDropDownList) &&
        IsDropDownListSelected(objForm.employmentStatusDropDownList))
        return true;
    else
        return false;
}



//Are the fields required for doing a broker search valid
function IsValidMortgageBrokerSearchDetails3()        
{
    //alert('IsValidMortgageBrokerSearchDetails2');

    if (IsValidAmountRange(objForm.amountTextBox, true, 25000, 5000000) &&
        IsValidAmountRange(objForm.houseValueTextBox, true, 40000, 5000000) &&
        IsValidPostCodeRow(objForm.postCodeTextBox, true) &&
        IsButtonListSelected(objForm.ccjRadioButtonList) &&
        IsButtonListSelected(objForm.missedPaymentRadioButtonList) &&
        IsButtonListSelected(objForm.bankruptRadioButtonList) &&
        IsButtonListSelected(objForm.selfCertifyRadioButtonList) &&
        IsDropDownListSelected(objForm.mortgageTypeDropDownList))
        return true;
    else
        return false;
}

//Are the fields required for doing a broker search valid
function IsValidMortgageBrokerSearchDetails4()        
{
   // alert('IsValidMortgageBrokerSearchDetails4');
    var noBtn = document.getElementById(objForm.noRadioButton);
    
    if (IsValidAmountRange(objForm.amountTextBox, true, 25000, 5000000) &&
        IsValidAmountRange(objForm.propertyValueTextBox, true, 40000, 5000000) &&
        IsDropDownListSelected(objForm.employmentStatusDropDownList)&&
        IsDropDownListSelected(objForm.mortgageTypeDropDownList) &&
        (IsButtonListSelected2(objForm.yesRadioButton) || (noBtn.checked))  && 
        IsValidPostCodeRow(objForm.postCodeTextBox, true) 
       )
        return true;
    else
        return false;
}
    
//Are the fields required for doing a broker search valid
function IsValidMortgageBrokerSearchDetails5()        
{
    if (IsValidAmountRange(objForm.amountTextBox, true, 25000, 5000000) &&
        IsValidAmountRange(objForm.houseValueTextBox, true, 40000, 5000000) &&
        IsValidPostCodeRow(objForm.postCodeTextBox, true) &&
        IsButtonListSelected(objForm.ccjRadioButtonList) &&
        IsButtonListSelected(objForm.ivaRadioButtonList) &&
        IsButtonListSelected(objForm.missedPaymentRadioButtonList) &&
        IsButtonListSelected(objForm.bankruptRadioButtonList) &&
        IsButtonListSelected(objForm.selfCertifyRadioButtonList) &&
        IsDropDownListSelected(objForm.mortgageTypeDropDownList))
        return true;
    else
        return false;
}

function IsValidShowMaxLoanRow()
{
    if (IsValidAmount(objForm.amountTextBox, true) &&
        IsValidAmount(objForm.mortgageBalanceTextBox, true) &&
        IsValidAmount(objForm.houseValueTextBox, true) &&
        IsButtonListSelected(objForm.mortgageRadioButtonList) &&
        IsButtonListSelected(objForm.adverseCreditRadioButtonList))
        return true;
    else
        return false;
}        

function ValidatePhone(homePhoneClientID, workPhoneClientID, mobilePhoneClientId, phoneInvalidRowClientID, checkBlank)
{         
    var isValidHomePhone = IsValidPhone(homePhoneClientID, checkBlank);
    var isValidWorkPhone = IsValidPhone(workPhoneClientID, checkBlank);
    var isValidMobilePhone = IsValidPhone(mobilePhoneClientId, checkBlank);

    if (isValidHomePhone || isValidWorkPhone || isValidMobilePhone)
        SetStyleDisplay(phoneInvalidRowClientID, 'none');
    else
        SetStyleDisplay(phoneInvalidRowClientID, '');    
}

//if checkBlank then we also check if field is empty
function IsValidPhone(clientID, checkBlank)
{
    var phoneNumber = checkUKTelephone(getElementValue(clientID));
   
    if (phoneNumber==null||phoneNumber=="")
    {
        if(checkBlank)
            return false;
        else
            return true;
    }
    
    if (phoneNumber == false)
        return false;
    else
    {
        document.getElementById(clientID).value = phoneNumber;
        return true;
    }
}

//Validate an email field - turn correspnding error messsage on/off
function ValidateEmail(clientID, invalidRowClientID, checkBlank)
{       
    if (IsValidEmail(clientID, checkBlank))
        SetStyleDisplay(invalidRowClientID, 'none');
    else
        SetStyleDisplay(invalidRowClientID, '');
}

function IsValidEmail(clientID, checkBlank) 
{
    RemoveSpace(clientID);
    var email = getElementValue(clientID);

    if (email==null||email=="")
    {
        if(checkBlank)
            return false;
        else
            return true;
    }
    
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
        return true;
    else
        return false;
 
    //return (email.indexOf(".") > 2) && (email.indexOf("@") > 0); 
}

function ValidatePostCode(clientID, invalidRowClientID, rowClientID, checkBlank)
{
    if(GetStyleDisplay(rowClientID) != 'none')
    {
        if (IsValidPostCode(clientID, rowClientID, checkBlank))
        {
            var postcode = checkPostCode(getElementValue(clientID));
            var changeValue;
        
            if (!postcode) changeValue = false; else changeValue = true;
            
            if (changeValue)
                document.getElementById(clientID).value = postcode;
           
            SetStyleDisplay(invalidRowClientID, 'none');
        }
        else
            SetStyleDisplay(invalidRowClientID, '');  
    }
}

function IsValidPostCode(clientID, rowClientID, checkBlank)
{

    if(GetStyleDisplay(rowClientID) != 'none')
    {    
        return IsValidPostCodeRow(clientID, checkBlank)
    }
    else
        return true;
}

function IsValidPostCodeRow(clientID, checkBlank)
{
    SetElementValue(clientID, LTrim(RTrim(getElementValue(clientID))));
    var postcode = getElementValue(clientID);  
    var value = checkPostCode(postcode);

    if (postcode==null||postcode=="")
    {
        if (checkBlank)
            return false;
        else
            return true;
    }
    else if(!value)
        return false;
    else
        return true;
}

//returns false if invalid
//return formatted if valid

function checkPostCode(toCheck) 
{

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  

  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) {return postCode;} else return false;
}

function checkUKTelephone (telephoneNumber) {
    
  // Convert into a string and check that we were provided with something
  var telnum = telephoneNumber + " ";
  if (telnum.length == 1)  {
     return false
  }
  telnum.length = telnum.length - 1;
  
  // Don't allow country codes to be included (assumes a leading "+")
  var exp = /^(\+)[\s]*(.*)$/;
  if (exp.test(telnum) == true) {
     return false;
  }
  
  // Remove spaces from the telephone number to help validation
  while (telnum.indexOf(" ")!= -1)  {
    telnum = telnum.slice (0,telnum.indexOf(" ")) + telnum.slice (telnum.indexOf(" ")+1)
  }
  
  // Remove hyphens from the telephone number to help validation
  while (telnum.indexOf("-")!= -1)  {
    telnum = telnum.slice (0,telnum.indexOf("-")) + telnum.slice (telnum.indexOf("-")+1)
  }  
  
  // Now check that all the characters are digits
  exp = /^[0-9]{10,11}$/
  if (exp.test(telnum) != true) {
     return false;
  }
  
  // Now check that the first digit is 0
  exp = /^0[0-9]{9,10}$/
  if (exp.test(telnum) != true) {
     return false;
  }
  
  // Finally check that the telephone number is appropriate.
  exp = /^(01|02|05|070|077|078|079)[0-9]+$/;
  if (exp.test(telnum) != true) {
     return false;
  }
  
  // Telephone number seems to be valid - return the stripped telehone number  
  return telnum;
}
    