﻿// -()------------------------------------------------------------------------------------------------------------------
//
//    Name: currencyValidation.js
// Purpose: To provide any date validation
// History:	2009/03/16  GD      Created
//
//			* prototype string.trim() 
//          * validateCurrency
//			* jQuery 
//
// -)(------------------------------------------------------------------------------------------------------------------

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, "");
}

// -<!>-----------------------------------------------------------------------------------------------------------------
//
// Name : validateCurrency
// Purpose: // Validates the a currency field locally.
//
// History: 2009/03/16  GD      (created)
//          2009/08/19  AH
//          2010/04/15  ES
//
// ->!<-----------------------------------------------------------------------------------------------------------------

function validateCurrency( value, minvalue, maxvalue )
{
	var valid =true;

	if (value != "") {
	    var strippedString = stripString(value);

		if (strippedString.length > 0) {
		    // convert to integer and set the valid flag if it falls inside the range.
		    var strippedData = parseInt(strippedString, 10);
		    valid = (strippedData >= minvalue) && (strippedData <= maxvalue);
		}
		else
		    valid = false; // all characters must have been invalid
	}
	return valid;
}


// -<!>-----------------------------------------------------------------------------------------------------------------
//
// Name : stripString
// Purpose: // Removes non-numeric characters from a string, factored out of validateCurrency
//
// History: 2010/04/15  ES      (created)
//
// ->!<-----------------------------------------------------------------------------------------------------------------
function stripString(value) {
    var strippedString = "";
    // if there's something to check
    for (var c = 0; c < value.length; c++) {
        // scan through each char to see if it's one of the following ...
        var a = value.charCodeAt(c);
        // decimal point. everything after this is dumped
        if (a == 46) { break; }
        // numbers only.
        if (a >= 48 && a <= 57) { strippedString += String.fromCharCode(a); }
    }

    return strippedString;
}

// -<!>-----------------------------------------------------------------------------------------------------------------
//
// Name : isLessThanMin
// Purpose: // works out if the value passed in is less than the minValue passed in
//
// History: 2010/04/15  ES      (created)
//
// ->!<-----------------------------------------------------------------------------------------------------------------
function isLessThanMin ( value, minValue )
{
    var isLess = true;
	
	if (value !="")
	{
		var strippedString = stripString(value);

		if (strippedString.length > 0)
		{
		    // convert to integer and set the valid flag if it falls inside the range.
		    var strippedData = parseInt(strippedString, 10);
		    
		    isLess = strippedData < minValue;
		}
		else
        {
		    isLess = false;
		}
	}
	
	return isLess;
}

// -<!>-----------------------------------------------------------------------------------------------------------------
//
// Name : isGreaterThanMax
// Purpose: // works out if the value passed in is greater than the msxValue passed in
//
// History: 2010/04/15  ES      (created)
//
// ->!<-----------------------------------------------------------------------------------------------------------------
function isGreaterThanMax ( value, maxValue )
{
    var isGreater = true;
	
	if (value !="")
	{
		var strippedString = stripString(value);

		if (strippedString.length > 0)
		{
		    // convert to integer and set the valid flag if it falls inside the range.
		    var strippedData = parseInt(strippedString, 10);
		    
		    isGreater = strippedData > maxValue;
		}
		else
        {
		    isGreater = false;
		}
	}
	
	return isGreater;
}

// -<!>-----------------------------------------------------------------------------------------------------------------
//
// Name : validateCurrencyInRange
// Purpose: Checks that a currency value is a valid number and falls within a given range.
//          If it isn't, the function will set the field to the specified reset value.
//
// History: 2009/08/20  AH      (created)
//
// ->!<-----------------------------------------------------------------------------------------------------------------

function validateCurrencyInRange(sender, value, minvalue, maxvalue, resetvalue) {
    if (value != "") {
        var strippedAmount = value.replace(/,/g, '');
        var isInvalid = false;
        if (isNaN(strippedAmount)) {
            isInvalid = true;
        }
        else {
            isInvalid = !(strippedAmount >= minvalue && strippedAmount <= maxvalue);
        }
        if (isInvalid) {
            // if value is invalid just reset it to the default value
            var amt = document.getElementById(sender.controltovalidate);
            amt.value = resetvalue;
        }
        return;
    }
}

// -<!>-----------------------------------------------------------------------------------------------------------------
//
// Name : validatePeriodAmountAndSecurity
// Purpose: Validates the a loan amount, period and residential status.
//
// History: 2009/04/15  LM  (created)
//
// ->!<-----------------------------------------------------------------------------------------------------------------

function validatePeriodAmountAndSecurity(value, minValue, maxValue, homeOwner, residentialStatus, loanTerm, minPeriod)
{
    var valid = true;

    if (validateCurrency(value, minValue, maxValue) &&  (homeOwner == residentialStatus) && (loanTerm >= minPeriod))
    {
        valid = false;
    }
    return valid;
}

// -<!>-----------------------------------------------------------------------------------------------------------------
//
// Name : formatCurrency
// Purpose: Inserts commas into the currency field
//
// History: 2009/12/07  LM  (created)
//
// ->!<-----------------------------------------------------------------------------------------------------------------
function formatCurrency(sv)
{
    var rs = "",
		rsd = "",
		dp = false;

    if (sv.length > 0)
    {
        // if ther's anything to reformat
        for (var c = 0; c < sv.length; c++)
        {
            // build a string of valid characters
            var a = sv.charCodeAt(c);
            // only the first decimal point is allowed. 
            if (a == 46 && !dp)
            {
                rsd += String.fromCharCode(a);
                dp = true;
            }
            // numbers only
            if ((c == 0 && a == 45) || (a >= 48 && a <= 57))
            {
                rsd += String.fromCharCode(a);
                if (!dp)
                {
                    rs += String.fromCharCode(a);
                }
            }
        }

        // convert into shortest form
        if (rsd.length > 0)
        {
            var rsN = parseInt(rs, 10),
				rsdN = parseFloat(rsd);

            if (!isNaN(rsN)) {
                if (rsdN > rsN) {
                    {
                        rsN += 1;
                    }
                    rs = rsN.toString();
                }
            }
            
            // build regex to insert the thousands
            var rx = /(\d+)(\d{3})/;
            while (rx.test(rs))
            {
                rs = rs.replace(rx, '$1' + ',' + '$2');
            }
        }
    }

    return rs;
}

// -<!>-----------------------------------------------------------------------------------------------------------------
//
// Name : page level jQuery
// Purpose: jQuery function to to re-format the fields into a readable format n,nnn,nnn
//
// History: 2009/03/16  GD      (created)
//			2009/04/02	GD		added support for rounding UP. Ceiling effectively. 
//
// ->!<-----------------------------------------------------------------------------------------------------------------

function attachWholePounds()
{

    $(".wholepounds:not(.hasWholePoundsHandler)").blur(function() {
        var sv = $(this).val().trim();
        var title = $(this).attr("title");
    
        if (sv == title)
            return true;

        var rs = formatCurrency(sv);
        
        // drop the new value into the field
        $(this).val(rs);

        // and tell the browser all is well.
        return true;
    }).addClass("hasWholePoundsHandler");

}

// -<!>-----------------------------------------------------------------------------------------------------------------
//
// Name : formatPeriodDropDown
// Purpose: jQuery function to to re-populate the drop down list based on homeowner status and loan amount
//
// History: 2010/03/08  LM      (created)
//
// ->!<-----------------------------------------------------------------------------------------------------------------
function formatPeriodDropDown(loanAmount, periodSelector, optionSelector, period, homeOwnerYes, errorSelector)
{
    // Initialise variables
    var messages = new Array(
        "As a non-homeowner looking to borrow between £10,000 and £15,000, the maximum term you can borrow over is 7 years. Please amend your entry.",
        "As a non-homeowner looking to borrow between £15,000 and £25,000, the maximum term you can borrow over is 10 years. Please amend your entry.",
        "As a non-homeowner, the maximum loan available to you is £25,000.",
        "You cannot apply for an unsecured loan over £25,000.");
    var msg = "";
    var option = "";
    var min = 1
    var max = 25;

    var homeOwner = homeOwnerYes ? "1" : "0"    // Get the selected homeowner Yes=1 No=0
    var combo = $(periodSelector);              // Get reference to the drop down list

    // Clear out the error
    $(errorSelector).parent().hide();

    if (loanAmount != "" && homeOwner != "")
    {
        // Set the range based on the tbLoanAmount and rbHomeOwner
        if (homeOwner == "1")
        {
            if (loanAmount < 10000) { min = 1; max = 7; }
            if (loanAmount >= 10000 && loanAmount <= 25000) { min = 1; max = 25; }
            if (loanAmount > 25000) { min = 5; max = 25; }
        }
        else if (homeOwner == "0")
        {
            if (loanAmount < 15000) { min = 1; max = 7; }
            if (loanAmount >= 15000 && loanAmount <= 25000) { min = 1; max = 10; }
            if (loanAmount > 25000) { min = 0; max = 0; msg = messages[3]; }
        }
    }

    // Determine if the previous selected period is outside the bounds of the current min and max
    // and that we've changed to non-homeowner (this is where the period items will be removed from the list)
    if (period > max && homeOwner == "0")
    {
        if (loanAmount >= 10000 && loanAmount < 15000) { msg = messages[0]; }
        if (loanAmount >= 15000 && loanAmount <= 25000) { msg = messages[1]; }
        if (loanAmount > 25000) { msg = messages[2]; }
    }

    // Remove all <option>s from the drop down
    $(optionSelector).remove();

    // Add the default first item
    combo.append($('<option></option>').val(0).html("Select"));

    if (min > 0 && max > 0)
    {
        // Add the rest of the items based on min and max range
        for (var i = min; i <= max; i++)
        {
            // If the new set of periods contains the current period then select it
            i == period ? option = '<option selected="true"></option>' : option = '<option></option>'
            var suffix = (i == 1 ? ' year' : ' years');
            combo.append($(option).val(i).html(i + suffix));
        }
    }

    if (msg != "")
    {
        ClearErrorBox();
        $(errorSelector).html(msg).parent().show();
    }
}

jQuery(function($){

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    
	if (prm.endRequest == null)
	{
		prm.add_endRequest(attachWholePounds);
    }
    attachWholePounds();

});

