//------------------------------------------------
// LoansResultAjax.js
// Contains Ajax functions for Loan Results Page
//------------------------------------------------

// Object to contain the initial Search
var fireSliderEvents = true;

// Slider default ranges
var unsecuredSliderAmountRange = [500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500, 10000, 10500, 11000, 11500, 12000, 12500, 13000, 13500, 14000, 14500, 15000, 15500, 16000, 16500, 17000, 17500, 18000, 18500, 19000, 19500, 20000, 20500, 21000, 21500, 22000, 22500, 23000, 23500, 24000, 24500, 25000];
var unsecuredSliderPeriodRange = [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 102, 108, 114, 120];

var securedSliderAmountRange = GenerateSecuredRange();
var securedSliderPeriodRange = [120, 132, 144, 156, 168, 180, 192, 204, 216, 228, 240, 252, 264, 276, 288, 300];

var sliderRepaymentRange = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350, 1400, 1450, 1500, 1550, 1600, 1650, 1700, 1750, 1800, 1850, 1900, 1950, 2000];

var inTheMiddleOfAnAjaxCall = false;

function GenerateSecuredRange()
{
    var valueArray = new Array();

    for (i = 25000; i <= 250000; i = i + 1000)
    {
        valueArray[valueArray.length] = i;
    }

    return valueArray;
}

var loans = null;


/// <summary>
/// Call back to the server for data based on the currentRequestObject
/// </summary>
function CallData()
{
    if (inTheMiddleOfAnAjaxCall == false)
    {        
        inTheMiddleOfAnAjaxCall = true;        
        showLoadingMessage();

        $.ajax(
        {
            type: "GET",
            url: "/ajax/loansearch.aspx?siteName=" + siteName,
            data: jQuery.param(currentRequest),
            cache: false,
            success: function (data, status) { inTheMiddleOfAnAjaxCall = false; parseAjaxResponse(data, status); },
            error: function () { inTheMiddleOfAnAjaxCall = false; failed(); }
        });

        // call function to indicate sort order
        IndicateSortOrder(currentRequest.sortCriteria);
        // hide input help tooltips
        $('#ttAmount').hide();
        $('#ttPeriod').hide();
        $('#ttRepayment').hide();
    }
}

/// <summary>
/// Handle a failure on the Ajax Request
/// </summary>
function failed()
{
    var tbody = $("#table_results")[0];
    var tr;
    var td;

    // Remove the result rows
    for (i = tbody.rows.length - 1; i >= 0; i--)
    {
        tbody.removeChild(tbody.rows.item(i));
    }

    // Insert a failure message to prompt a retry
    tr = document.createElement("tr");
    td = document.createElement("td");
    td.colSpan = 7;
    td.innerHTML = "<div id='NoResults'><h4>Oops, slight glitch!</h4><p>Our system is having a spot of trouble with your request. This should be a temporary thing - please move one of the sliders to re-submit.</p></div>";
    tr.appendChild(td);
    tbody.appendChild(tr);


    hideLoadingMessage();
}


/// <summary>
/// Handle a successful call
/// </summary>
function parseAjaxResponse(data, textStatus)
{    
    // If there was an input validation error then show the failure message
    if (data.indexOf("ArrayOfError") >= 0)
    {
        failed();
    }
    // Otherwise Show the Results
    else
    {
        ProcessResult(data);
        hideLoadingMessage();
    }
}

/// <summary>
/// If there are rows, show them in the table
/// </summary>
function ProcessResult(data)
{
    loans = eval("(" + data + ")");
    DrawTable();
}

function DrawTable()
{
    var tbody;
    var keyInfo;
    var tr;
    var td;
    var loan;
    var moreInfoLink = '';
    var applyLink = '';
    var applyLinkTarget = '';

    tbody = $("#table_results");
    if (tbody.length > 0)
    {
        tbody = tbody[0];
    }


    // Remove the current results
    for (i = tbody.rows.length - 1; i >= 0; i--)
    {
        tbody.removeChild(tbody.rows.item(i));
    }

    var domain = null;
    // get current domain and convert to https    
    if (document.domain != null)
    {
        domain = "https://" + document.domain;
    }
    else
    {
        domain = "https://www.fool.co.uk";
    }

    //If we have some results
    if (loans.LoansCollection.length > 0)
    {
        // Process each loan result
        for (i = 0; i < loans.LoansCollection.length; i++)
        {
            var className = "";
            loan = loans.LoansCollection[i];

            // Create row        
            if (i % 2 != 0)
            {
                className = "Odd";
            }

            applyLinkTarget = 'target=\"_blank\"';
            if (loan.ApplyLink.indexOf('non-partner') != -1)
            {
                applyLinkTarget = '';
            }

            if (loan.LoanType == 0)
            {
                applyLink = loan.ApplyLink;
                moreInfoLink = '/loans/detailsapply.aspx?LoanId=' + loan.FeedId + '&amp;advance=' + GetDecentValue(loans.Amount) + '&amp;term=' + loan.TermInMonths + '&amp;position=' + (((currentRequest.pageNumber - 1) * 10) + i + 1) + '&amp;from=/loans/search.aspx';
            }
            else
            {
                var jointApplication = 'false';
                var ddl = document.getElementById('drpJointApp');
                if (ddl != null)
                {
                    var selectedValue = ddl.options[ddl.selectedIndex].value;
                    if (selectedValue.toLowerCase() == 'joint')
                    {
                        jointApplication = 'true';
                    }
                }
                hop2ref = Hop2Ref(1, 'SecuredLoan', 'Default', loan.Company, 'SecuredLoan', serverDate, siteName, 'DCMain', (((currentRequest.pageNumber - 1) * 10) + i + 1), 'ApplyNow', loan.Partner, currentRequest.sortCriteria);

                applyLink = domain + '/loans/secured/linktracker.aspx?ref=' + hop2ref + '&lpId=' + loan.FeedId + '&la=' + GetDecentValue(loans.Amount) + '&pv=' + currentRequest.propertyValue + '&ou=' + currentRequest.mortgageBalance;
                moreInfoLink = '/loans/securedmoreinfo.aspx?hop2ref=' + hop2ref + '&lpId=' + loan.FeedId + '&la=' + GetDecentValue(loans.Amount) + '&rp=' + loan.TermInMonths + '&pv=' + currentRequest.propertyValue + '&ou=' + currentRequest.mortgageBalance + '&ja=' + jointApplication;
            }

            // Create Provider Cell (with images and links as required
            tdHTML = '<h3><a href="' + applyLink + '"' + applyLinkTarget + '><span class="Provider">' + loan.Company + '</span><br /><span class="LoanName">' + loan.LoanName + '</span></a></h3>';
            if (loan.ButtonURL != "" && loan.Partner)
            {
                tdHTML += '<div class="PartnerCreative';
                if (loan.Popularity > 0)
                {
                    tdHTML += ' BestSeller';
                }
                tdHTML += '">';
                tdHTML += '<a href="' + applyLink + '"' + applyLinkTarget + '><img src="' + loan.ButtonURL + '" class="PartnerCreative" alt="" /></a>'
                tdHTML += '</div>';
            }

            // Get Key Info        
            keyInfo = GetKeyInfo(loan);

            // Build the row cells
            tr = document.createElement("tr");
            td = CreateCell(tdHTML, "Product", tr);

            var existingCustomerHTML = '';
            if (loan.CustomerType.toLowerCase() == 'existing customer')
            {
                existingCustomerHTML = '<span class="existing-customer">(For existing customers only)</span>';
            }

            if (loan.LoanType == 0) // unsecured
            {
                td = CreateCell('<span>Representative<br /><span>' + loan.TypicalAPR.toFixed(1) + '%</span> APR</span>' + existingCustomerHTML, "Apr", tr);
            }
            else {
                td = CreateCell('<span>Typical<br /><span>' + loan.TypicalAPR.toFixed(1) + '%</span> APR</span>' + existingCustomerHTML, "Apr", tr);
            }
            td = CreateCell(loans.Amount + '<br /><span class="NoBreak">' + loan.TermInMonths + ' months</span>', "", tr);
            td = CreateCell(FormatCurrency(loan.TotalAmountRepayable), "", tr);
            td = CreateCell(FormatCurrency(loan.MonthlyRepayment), "", tr);
            td = CreateCell(keyInfo, "LoanFeatures", tr);
            var applyAndMore = '<a class="MoreApply ApplyBtn" ' + applyLinkTarget + ' href="' + applyLink + '"><span>Apply Now</span></a>';
            if (loan.ShowMoreInfoButton == true)
            {
                applyAndMore += '<a class="MoreApply MoreBtn" href="' + moreInfoLink + '"><span>More Info</span></a>';
            }
            td = CreateCell(applyAndMore, "", tr);

            // Add the row
            tr.className = className;
            tbody.appendChild(tr);

            // CCD representative example message for UNSECURED only
            if (loan.LoanType == 0) {
                var alternateColor = "";
                if (i % 2 != 0) {
                    //alternateColor = " color: #006778;";
                } 
                var rowHtml = "<tr class='" + className + "'>";
                rowHtml += "<td colspan='7' class='BorderBottom' style='text-align: left; padding-left: 10px; padding-top: 0px; padding-bottom: 15px;" + alternateColor + "'><b>" + loan.RepresentativeExampleMessage + "</b></td>";
                rowHtml += "</tr>";
                $(tbody).append($(rowHtml));
            }
        }
    }
    else
    {
        // Create a no results found message
        tr = document.createElement("tr");
        td = document.createElement("td");
        td.colSpan = 7;

        tdContent = "<div id='NoResults'><h4>Sorry, you've filtered out everything</h4><p>Try adjusting your criteria by unchecking some features or adjusting the amount, borrowing period or monthly repayment sliders.</p><p class='Second'>Please keep in mind that unsecured loans are available up to &pound;25,000 and for a period of up to 10 years, and secured loans range from &pound;5,000 to &pound;250,000 and for terms of up to 25 years.</p>";
        // TODO: include suggested searches
        tdContent = tdContent + "</div>";

        td.innerHTML = tdContent;
        tr.appendChild(td);
        tbody.appendChild(tr);



    }

    // Update Informational UI and Page navigation
    BuildPageList(loans.PageNumber, loans.TotalOfPages);
    SetResultCounters(loans.CountOfTotal, loans.CountOfVisible, loans.CountOfFilteredOut);    
}



/// <summary>
/// Show informational data
/// </summary>
function GetKeyInfo(loan)
{
    var keyInfo = "";

    if (loan.Partner)
    {
        // below line would observe the 'lovemoney.com product' link to activate glossary
        // however, that means it creates event listeners for each link on CallData so big memory use
        // TODO: fix this, duh
        // keyInfo += '<span class="KeyInfoGraphic LovePartner"><a href="#" rel="GlossaryFoolPartners" id="trigger' + loan.FeedId + '" class="ttTrigger">lovemoney.com partner</a></span>';
        keyInfo += '<span class="KeyInfoGraphic LovePartner">lovemoney.com partner</span>';
    }

    if (loan.LoanType == 1)
    {
        keyInfo += '<span class="KeyInfoGraphic SecuredLoan">Secured loan</span>';
    }
    else
    {
        keyInfo += '<span class="KeyInfoGraphic UnsecuredLoan">Unsecured loan</span>';
    }

    if (loan.LoanType == 0)
    {
        if (loan.ArrangementFee == "")
        {
            keyInfo += '<span class="KeyInfoGraphic NoArrangementFees">No arrangement fees</span>';
        }
        else
        {
            keyInfo += '<span class="KeyInfoGraphic ArrangementFees">' + loan.ArrangementFee + '</span>';
        }
    }

    if (loan.AvailableViaPhoneOnly)
    {
        keyInfo += '<span class="KeyInfoGraphic PhoneOnly">Phone applications only</span>';
    } else if (loan.AvailableViaBranch && loan.NotAvailableOnline)
    {
        keyInfo += '<span class="KeyInfoGraphic BranchOnly">Branch applications only</span>';
    } else if (loan.NotAvailableOnline)
    {
        keyInfo += '<span class="KeyInfoGraphic NotOnline">Not available online</span>';
    }

    return keyInfo;
}


/// <summary>
/// Create a cell and add it to the row
/// </summary>
function CreateCell(htmlString, className, tableRow)
{
    var td = document.createElement("td");
    td.innerHTML = htmlString;
    if (className != null)
    {
        td.className = className;
    }

    tableRow.appendChild(td);

    return td;
}


/// <summary>
/// Create a page list centered on the current page (4 left, 5 right)
/// </summary>
function BuildPageList(currentPage, totalPages)
{
    var startPage;
    var endPage;

    var pagingHTML = "";

    // Calculate Start and End of range to show
    startPage = ((currentPage - 4) < 1) ? 1 : currentPage - 4;
    endPage = currentPage + (10 - (currentPage - startPage)) - 1;
    endPage = (endPage <= totalPages) ? endPage : totalPages;
    startPage = ((endPage - 10) >= 1) ? (endPage - 9) : 1;


    // Previous button
    if (currentPage > 1)
    {
        pagingHTML += '<a href="#Top" onclick="GotoPage(' + (currentPage - 1) + ')" class="NextPrev" title="Previous page">&laquo; Previous</a>';
    }
    else
    {
        pagingHTML += '<span class="NextPrev">&laquo; Previous</span>';
    }

    // Pages in Range    
    for (i = startPage; i <= endPage; i++)
    {
        if (currentPage == i)
        {
            pagingHTML += '<span class="Current">' + i + '</span>';
        }
        else
        {
            pagingHTML += '<a href="#Top" onclick="GotoPage(' + i + ')" title="Go to page ' + i + '">' + i + '</a>';
        }
    }

    // Next Button
    if (currentPage < totalPages)
    {
        pagingHTML += '<a href="#Top" onclick="GotoPage(' + (currentPage + 1) + ')" class="NextPrev" title="Next page">Next &raquo;</a>';
    }
    else
    {
        pagingHTML += '<span class="NextPrev">Next &raquo;</span>';
    }

    // Render
    $('#PageList').html(pagingHTML);
}


/// <summary>
/// Display the Loading indicator
/// </summary>
function showLoadingMessage()
{
    $('#LoadingMessage').show();
}


/// <summary>
/// Hide the Loading Indocator
/// </summary>
function hideLoadingMessage()
{
    $('#LoadingMessage').hide();
}


/// <summary>
/// Callback for a new page
/// </summary>
function GotoPage(pageNumber)
{
    currentRequest.pageNumber = pageNumber;
    CallData();
}


/// <summary>
/// Sort data and call back for page 1
/// </summary>
function SortResultsFromSelect(sortObject)
{
    if (sortObject.selectedIndex >= 0)
    {
        currentRequest.sortCriteria = sortObject.options[sortObject.selectedIndex].value;
        currentRequest.pageNumber = 1;
        CallData();
    }
}


/// <summary>
/// Update dropdown list to current value
/// </summary>
function SetDropDown(value, listObject)
{
    for (i = 0; i < listObject.length; i++)
    {
        if (listObject[i].value == value)
            listObject.selectedIndex = i;
    }
}


/// <summary>
/// Sort from clicking column heading. Call for page 1
/// </summary>
function SortResultsFromLink(sortCriteria, sortListObject)
{
    currentRequest.sortCriteria = sortCriteria;
    // set dropdown to match sort criteria
    $(sortListObject).val(sortCriteria);
    currentRequest.pageNumber = 1;
    CallData();
}

// bug#41111
// a function to set a class in the <th> of the sorted column (where possible)
function IndicateSortOrder(sortValue)
{
    sortAscClassString = "ActiveAscSort";
    sortDescClassString = "ActiveDescSort";

    // this is garbage - need to convert this to get array of <th>s programatically
    tableHeadings = new Array(4);
    tableHeadings[0] = 'ThApr';
    tableHeadings[1] = 'ThTar';
    tableHeadings[2] = 'ThMonthlyRepayment';
    tableHeadings[3] = 'ThCompany';

    for (i = 0; i < tableHeadings.length; i++)
    {
        $('#' + tableHeadings[i]).removeClass(sortDescClassString);
        $('#' + tableHeadings[i]).removeClass(sortAscClassString);
    }

    switch (sortValue)
    {
        case "TypicalAPR ASC":
            $('ThApr').addClass(sortAscClassString);
            break;
        case "TotalAmountRepayable ASC":
            $('ThTar').addClass(sortAscClassString);
            break;
        case "MonthlyRepayment ASC":
            $('ThMonthlyRepayment').addClass(sortAscClassString);
            break;
        case "CompanyName ASC":
            $('ThCompany').addClass(sortAscClassString);
            break;
        default:
            return false;
            break;
    }
}


/// <summary>
/// Show number of loans found
/// </summary>
function SetResultCounters(countOfTotal, countOfVisible, countOfFilteredOut)
{
    $('#TotalLoanCount').html(countOfTotal);
    $('#TotalVisibleCount').html(countOfVisible);
    // $('TotalFilteredCount').innerHTML = countOfFilteredOut;
}

/// <summary>
/// Checkbox filter handlers - updates currentRequest and calls for page 1
/// </summary>
function handleEarlyRepayment(obj)
{
    currentRequest.noEarlyFee = (obj.checked) ? "true" : "false";
    currentRequest.pageNumber = 1;
    CallData();
}

function handlePaymentHoliday(obj)
{
    currentRequest.paymentHoliday = (obj.checked) ? "true" : "false";
    currentRequest.pageNumber = 1;
    CallData();
}

function handleSameDayFunds(obj)
{
    currentRequest.sameDayFunds = (obj.checked) ? "true" : "false";
    currentRequest.pageNumber = 1;
    CallData();
}

function handleNewCustomers(obj)
{
    currentRequest.newCustomers = (obj.checked) ? "true" : "false";
    currentRequest.pageNumber = 1;
    CallData();
}

function handleLumpSumPayments(obj)
{
    currentRequest.lumpSumPayments = (obj.checked) ? "true" : "false";
    currentRequest.pageNumber = 1;
    CallData();
}

function handleFoolApproved(obj)
{
    currentRequest.partner = (obj.checked) ? "true" : "false";
    currentRequest.pageNumber = 1;
    CallData();
}

function handleCCJConsidered(obj)
{
    currentRequest.CCJ = (obj.checked) ? "true" : "false";
    currentRequest.pageNumber = 1;
    CallData();
}

function handleAgeChange(eventArgs)
{
    currentRequest.ageBand = $F('drpAge');
    currentRequest.pageNumber = 1;
    CallData();
}

function handleEmploymentChange(eventArgs)
{
    currentRequest.employmentStatus = $F('rbEmploymentStatus');
    currentRequest.pageNumber = 1;
    CallData();
}

function handleHomeOwner(eventArgs)
{
    currentRequest.homeOwner = (eventArgs.target.checked) ? "true" : "false";
    currentRequest.pageNumber = 1;
    CallData();
}

function handleLoanType(eventArgs)
{
    eventArgs.preventDefault();
    currentRequest.pageNumber = 1;

    $('ul#bestbuytabs li').each(
      function (i)
      {
          $(this).removeClass('active');
      }
    );

    element = $(eventArgs.target).parent();
    switch (element.attr('id'))
    {
        case "LoanTypeAll":
            $(element).parent().addClass('active');
            currentRequest.showTypes = "all";
            $('#SecuredLoanOptions').show();
            $('#UnsecuredLoanOptions').show();
            $("span[id$='PersonalDisclaimer']").show();
            $("span[id$='SecuredDisclaimer']").show();
            break;
        case "LoanTypeUnsecuredOnly":
            $(element).parent().addClass('active');
            currentRequest.showTypes = "personal";
            $('#SecuredLoanOptions').hide();
            $('#UnsecuredLoanOptions').show();
            $("span[id$='PersonalDisclaimer']").show();
            $("span[id$='SecuredDisclaimer']").hide();
            break;
        case "LoanTypeSecuredOnly":
            $(element).parent().addClass('active');
            currentRequest.showTypes = "secured";
            $('#SecuredLoanOptions').show();
            $('#UnsecuredLoanOptions').hide();
            $("span[id$='PersonalDisclaimer']").hide();
            $("span[id$='SecuredDisclaimer']").show();
            break;
    }

    CallData();
}

function handleJointApplication(eventArgs)
{
    currentRequest.isJoint = $F('drpJointApp');
    currentRequest.pageNumber = 1;
    CallData();
}

/// <summary>
/// Strip any non numeric characters (except decimal point)
/// </summary>
function GetDecentValue(inputValue)
{
    var sanitizedValue;

    sanitizedValue = inputValue;
    sanitizedValue = sanitizedValue.replace(/[^.0-9]/g, "");

    val = parseInt(sanitizedValue);

    return val;
}


/// <summary>
/// Handle Return in a textbox to update the sliders and call for data requested
/// </summary>
function HandleKeyUp(eventArgs)
{
    //debugger;
    var amountValue;
    var monthlyValue;
    var termValue;
    var valid = true;
    var message = "";

    // Was it a return?
    if (eventArgs.keyCode == 13)
    {
        eventArgs.stopPropagation();

        // Get those values
        termValue = GetDecentValue($('#SliderValuePeriod').val());        

        monthlyValue = GetDecentValue($('#SliderValueRepayment').val());
        amountValue = GetDecentValue($('#SliderValueAmount').val());

        // Validate those values  
        if (isNaN(amountValue))
        {
            message += "Amount is invalid\n";
            valid = false;
        } else
        {
            if (amountValue > 250000 || amountValue < 500)
            {
                message += "Amount is invalid\n";
                valid = false;
            }
        }

        if (isNaN(monthlyValue))
        {
            message += "Monthly is invalid\n";
            valid = false;
        } else
        {
            if (termValue == 0 && (monthlyValue < 50 || monthlyValue > 2000))
            {
                message += "Monthly is invalid\n";
                valid = false;
            }
        }

        if (isNaN(termValue))
        {
            message += "Term is invalid\n";
            valid = false;
        }

        if (!isNaN(monthlyValue) && !isNaN(termValue))
        {
            if ((monthlyValue > 0) && (termValue > 0))
            {
                message += "Please choose EITHER a Period OR a Monthly Payment\n";
                valid = false;
            }
        }


        if (valid)
        {
            // Use those values!
            currentRequest.amount = amountValue;

            if (monthlyValue > 0)
            {
                currentRequest.monthlyRepayment = monthlyValue;
                currentRequest.term = 0;
            } else
            {
                termValue = RoundToBorrowingPeriod(termValue);
                currentRequest.term = termValue;
                currentRequest.monthlyRepayment = 0;
            }

            if (currentRequest.amountSlider == "less" && amountValue > 25000)
            {
                flipAmountSlider("more");
                currentRequest.amount = amountValue;
            }

            if (currentRequest.amountSlider == "more" && amountValue < 25000)
            {
                flipAmountSlider("less");
                currentRequest.amount = amountValue;
            }

            if (currentRequest.periodSlider == "less" && termValue > 120)
            {
                flipPeriodSlider("more");
                currentRequest.term = termValue;
            }

            if (currentRequest.periodSlider == "more" && termValue < 120)
            {
                flipPeriodSlider("less");
                currentRequest.term = termValue;
            }

            $('#SliderValueAmount').val(amountValue);
            $('#SliderValuePeriod').val(termValue);
            $('#SliderValueRepayment').val(monthlyValue);

            // Set Sliders
            valueArray = (currentRequest.amountSlider == "more") ? securedSliderAmountRange : unsecuredSliderAmountRange;
            idx = GetIndex(valueArray, amountValue);
            if (!isNaN(idx))
            {
                SetSlider('LoanAmountSlider', idx);
            }

            if (currentRequest.monthlyRepayment == 0)
            {
                valueArray = (currentRequest.periodSlider == "more") ? securedSliderPeriodRange : unsecuredSliderPeriodRange;
                idx = GetIndex(valueArray, termValue);
                if (!isNaN(idx))
                {
                    SetSlider('LoanPeriodSlider', idx);
                }
            }
            else
            {
                idx = GetIndex(valueArray, monthlyValue);
                if (!isNaN(idx))
                {
                    SetSlider('LoanRepaymentSlider', idx);
                }
            }

            // Call for results
            CallData();
        }
        else
        {
            alert(message);
        }
        return false;
    }
}


/// <summary>
/// Convert borrowing period in months to value in years
/// </summary>
function UpdateYearsCount()
{    
    var rawFieldValue = $('#SliderValuePeriod').val();
    var fieldValue = GetDecentValue(rawFieldValue);
    // check if figure entered is divisible by twelve
    var roundedValue = RoundToBorrowingPeriod(fieldValue);
    if (!isNaN(roundedValue))
    {
        if (roundedValue % 12 == 0)
        {
            $('#PeriodYearCount').html((roundedValue / 12).toFixed(1));
        }
        else
        {
            $('#PeriodYearCount').html((roundedValue / 12).toFixed(1));
        }
    }
    else
    {
        $('#PeriodYearCount').html('?');
    }
}


/// <summary>
/// Reflect the currentRequest on the GUI
/// Used after restoring state
/// </summary>
function UpdateGUI()
{
    // Personal Loan Filters
    $('#cbEarlyRepayment')[0].checked = (convertToBoolean(currentRequest.noEarlyFee));
    $('#cbPaymentHolidays')[0].checked = (convertToBoolean(currentRequest.paymentHoliday));
    $('#cbLumpSums')[0].checked = (convertToBoolean(currentRequest.lumpSumPayments));
    $('#cbSameDayFunds')[0].checked = (convertToBoolean(currentRequest.sameDayFunds));
    $('#cbNewCustomers')[0].checked = (convertToBoolean(currentRequest.newCustomers));
    $('#cbFoolApproved')[0].checked = (convertToBoolean(currentRequest.partner));
    $('#cbCCJConsidered')[0].checked = (convertToBoolean(currentRequest.CCJ));    

    // Secured Loan Filters
    $('#txtPropertyValue').val(currentRequest.propertyValue);
    $('#txtMortgageOutstanding').val(currentRequest.mortgageBalance);
    $('#txtHouseholdIncome').val(currentRequest.income);



    //SetDropDown(currentRequest.ageBand, $('drpAge'));

    // Loan Type Radio
    if (currentRequest.showTypes == "personal")
    {
        $('#LoanTypeUnsecuredOnly').parent().addClass('active');
        $('#SecuredLoanOptions').hide();
        $('#UnsecuredLoanOptions').show();
        $("span[id$='PersonalDisclaimer']").show();
        $("span[id$='SecuredDisclaimer']").hide();
    } else if (currentRequest.showTypes == "secured")
    {
        $('#LoanTypeSecuredOnly').parent().addClass('active');
        $('#SecuredLoanOptions').show();
        $('#UnsecuredLoanOptions').hide();
        $("span[id$='PersonalDisclaimer']").hide();
        $("span[id$='SecuredDisclaimer']").show();
    } else
    {
        $('#LoanTypeAll').parent().addClass('active');
        $('#SecuredLoanOptions').show();
        $('#UnsecuredLoanOptions').show();
        $("span[id$='PersonalDisclaimer']").show();
        $("span[id$='SecuredDisclaimer']").show();
    }

    UpdateSecureLoanPanel();

    // Sort Drop Down
    $('#SortDropdown').val(currentRequest.sortCriteria);
}

function UpdateSecureLoanPanel()
{
    // Update Secured Loan Display Panel
    $('#CompletedAnswer3').html("&pound;" + addCommas(currentRequest.propertyValue));
    $('#CompletedAnswer4').html("&pound;" + addCommas(currentRequest.mortgageBalance));
    $('#CompletedAnswer5').html("&pound;" + addCommas(currentRequest.income));
    $('#CompletedAnswer6').html((currentRequest.isJoint == "true") ? "Joint" : "Single");
    $('#CompletedAnswer7').html((currentRequest.employmentStatus == "1") ? "Unemployed" : (currentRequest.employmentStatus == "2") ? "Self Employed" : (currentRequest.employmentStatus == "3") ? "Employed" : "n/a");
}

/// <summary>
/// Round period entered to nearest 6 month
/// </summary>
function RoundToBorrowingPeriod(months)
{
    quotient = Math.floor(months / 6);
    remainder = (months % 6);
    if (remainder > 0)
    {
        if (remainder >= 3)
        {
            months = (quotient * 6) + 6;
        }
        else
        {
            months = (quotient * 6);
        }
    }

    months = (months < 6) ? 6 : months;
    months = (months > 300) ? 300 : months;

    return months;
}

function SetSecuredOptions()
{
    var propertyValue;
    var mortgageValue;
    var incomeValue;
    var employmentStatus;
    var valid = true;
    var message = "";

    // Was it a return?
    // Get those values
    propertyValue = GetDecentValue($('#txtPropertyValue').val());
    mortgageValue = GetDecentValue($('#txtMortgageOutstanding').val());
    incomeValue = GetDecentValue($('#txtHouseholdIncome').val());

    var radioGrp = $('#employmentStatusDiv input');
    for (i = 0; i < radioGrp.length; i++)
    {
        if (radioGrp[i].checked == true)
        {
            var employmentStatus = radioGrp[i].value;
        }
    }

    var radioGrp = $('#mortgageApplicationType input');
    for (i = 0; i < radioGrp.length; i++)
    {
        if (radioGrp[i].checked == true)
        {
            var mortgageApplicationType = radioGrp[i].value;
        }
    }

    // Validate those values  
    if (isNaN(propertyValue))
    {
        message += "<li>Property value is invalid</li>";
        valid = false;
    }

    if (isNaN(mortgageValue))
    {
        message += "<li>Outstanding mortgage balance is invalid</li>";
        valid = false;
    }

    if (isNaN(incomeValue))
    {
        message += "<li>Income is invalid</li>";
        valid = false;
    }

    if (employmentStatus != "1" && employmentStatus != "2" && employmentStatus != "3")
    {
        message += "<li>Please select your employment status</li>";
        valid = false;
    }

    if (mortgageApplicationType != "true" && mortgageApplicationType != "false")
    {
        message += "<li>Please select your mortgage type</li>";
        valid = false;
    }

    if (valid)
    {
        currentRequest.propertyValue = propertyValue;
        currentRequest.mortgageBalance = mortgageValue;
        currentRequest.income = incomeValue;
        currentRequest.employmentStatus = employmentStatus;
        currentRequest.isJoint = mortgageApplicationType;

        window.setTimeout("CallData();", 100);

        $('#txtPropertyValue').val(currentRequest.propertyValue);
        $('#txtMortgageOutstanding').val(currentRequest.mortgageBalance);
        $('#txtHouseholdIncome').val(currentRequest.income);

        UpdateSecureLoanPanel();
        $('#SecuredLoansDialog').dialog("close");
    }
    else
    {
        $('#LBError').html("<ul>" + message + "</ul>");
        $('#LBError').show();
    }
}

function hideAllTooltips()
{
    $('#ttAmount').hide();
    $('#ttPeriod').hide();
    $('#ttRepayment').hide();
}

// a function to hide select lists so that tooltip can overlay
function hideSelects(visibility)
{
    selects = document.getElementsByTagName('select');
    for (i = 0; i < selects.length; i++)
    {
        selects[i].style.visibility = visibility;
    }
}

function onSlideUnsecuredAmount(e, ui)
{
    if (fireSliderEvents)
    {
        slideAmount(e, ui, unsecuredSliderAmountRange);
    }
}

function onSlideSecuredAmount(e, ui)
{
    if (fireSliderEvents)
    {
        slideAmount(e, ui, securedSliderAmountRange);
    }
}

function onSlideUnsecuredPeriod(e, ui)
{
    if (fireSliderEvents)
    {
        slidePeriod(e, ui, unsecuredSliderPeriodRange);
    }
}

function onSlideSecuredPeriod(e, ui)
{
    if (fireSliderEvents)
    {
        slidePeriod(e, ui, securedSliderPeriodRange);
    }
}

function onSlideRepayment(e, ui)
{
    if (fireSliderEvents)
    {
        slideMonthlyRepayment(e, ui, sliderRepaymentRange);
    }
}

function onChangeUnsecuredAmount(e, ui)
{
    if (fireSliderEvents)
    {
        changeAmount(e, ui, unsecuredSliderAmountRange);
    }
}

function onChangeSecuredAmount(e, ui)
{
    if (fireSliderEvents)
    {
        changeAmount(e, ui, securedSliderAmountRange);
    }
}

function onChangeUnsecuredPeriod(e, ui)
{
    if (fireSliderEvents)
    {
        changePeriod(e, ui, unsecuredSliderPeriodRange);
    }
}

function onChangeSecuredPeriod(e, ui)
{
    if (fireSliderEvents)
    {
        changePeriod(e, ui, securedSliderPeriodRange);
    }
}

function onChangeRepayment(e, ui)
{
    if (fireSliderEvents)
    {
        changeMonthlyRepayment(e, ui, sliderRepaymentRange);
    }
}



// SLIDE & CHANGE FUNCTIONS FOR SLIDERS
// AMOUNT
function slideAmount(e, ui, valueArray)
{
    $('#SliderValueAmount').val(valueArray[ui.value]);
    $('#SliderHandleAmountValue').html(addCommas(valueArray[ui.value]));
    hideAllTooltips();
}
function changeAmount(e, ui, valueArray)
{
    $('#SliderValueAmount').val(valueArray[ui.value]);
    currentRequest.amount = valueArray[ui.value];
    currentRequest.pageNumber = 1;
    hideAllTooltips();
    CallData();
}

// PERIOD
function slidePeriod(e, ui, valueArray)
{
    $('#SliderValuePeriod').val(valueArray[ui.value]);
    $('#SliderHandlePeriodValue').html(addCommas(valueArray[ui.value]));
    UpdateYearsCount();
    $('#FriendlyTextPeriod').show();
    $('#ActivationLinePeriod').hide();
    hideAllTooltips();
}
function changePeriod(e, ui, valueArray)
{
    $('#SliderValuePeriod').val(valueArray[ui.value]);
    $('#FriendlyTextPeriod').show();
    $('#FriendlyTextRepayment').hide();
    $('#ActivationLinePeriod').hide();
    $('#ActivationLineRepayment').show();
    $('#SliderHandlePeriodValue').html(addCommas(valueArray[ui.value]));
    SetSlider('LoanRepaymentSlider', 0);
    $('#SliderValueRepayment').val("0");
    currentRequest.monthlyRepayment = "";
    currentRequest.term = valueArray[ui.value].toFixed(0);
    currentRequest.pageNumber = 1;
    hideAllTooltips();

    CallData();
}
// MONTHLY REPAYMENT
function slideMonthlyRepayment(e, ui, valueArray)
{
    $('#SliderValueRepayment').val(valueArray[ui.value]);
    $('#SliderHandleRepaymentValue').html(addCommas(valueArray[ui.value]));
    $('#FriendlyTextRepayment').show();
    $('#ActivationLineRepayment').hide();
    hideAllTooltips();
}
function changeMonthlyRepayment(e, ui, valueArray)
{
    $('#SliderValueRepayment').val(valueArray[ui.value]);
    $('#FriendlyTextRepayment').show();
    $('#ActivationLineRepayment').hide();
    $('#FriendlyTextPeriod').hide();
    $('#ActivationLinePeriod').show();

    $('#SliderHandleRepaymentValue').html(addCommas(valueArray[ui.value]));
    currentRequest.term = "";
    SetSlider('LoanPeriodSlider', 0);
    $('#SliderValuePeriod').val("0");

    currentRequest.monthlyRepayment = (valueArray[ui.value]).toFixed(0);
    currentRequest.pageNumber = 1;
    hideAllTooltips();
    CallData();
    UpdateGUI();
}

function SetSlider(id, index)
{
    fireSliderEvents = false;
    $('#' + id).slider("value", index);
    fireSliderEvents = true;
}

function flipAmountSlider(flipDirection)
{
    if (flipDirection == "more")
    {
        $('#LoanAmountSlider').slider("destroy");
        $('#LoanAmountSlider').slider(
        {
            min: 0,
            max: securedSliderAmountRange.length - 1,
            steps: securedSliderAmountRange.length,
            change: onChangeSecuredAmount,
            slide: onSlideSecuredAmount
        });
        $('#LoanAmountSlider').slider("value", 0, 0);

        $('#flipLinkAmountMore').hide();
        $('#flipLinkAmountLess').show();

        currentRequest.amountSlider = "more";
        currentRequest.amount = securedSliderAmountRange[0];
    }
    else
    {
        $('#LoanAmountSlider').slider("destroy");

        $('#LoanAmountSlider').slider(
        {
            min: 0,
            max: unsecuredSliderAmountRange.length - 1,
            steps: unsecuredSliderAmountRange.length,
            change: onChangeUnsecuredAmount,
            slide: onSlideUnsecuredAmount
        });
        $('#LoanAmountSlider').slider("value", unsecuredSliderAmountRange.length - 1, 0);

        $('#flipLinkAmountMore').show();
        $('#flipLinkAmountLess').hide();

        currentRequest.amountSlider = "less";
        currentRequest.amount = unsecuredSliderAmountRange[unsecuredSliderAmountRange.length - 1];

    }
    CallData();
    UpdateGUI();
}

function flipPeriodSlider(flipDirection)
{
    if (flipDirection == "more")
    {
        $('#LoanPeriodSlider').slider("destroy");
        $('#LoanPeriodSlider').slider(
        {
            min: 0,
            max: securedSliderPeriodRange.length - 1,
            steps: securedSliderPeriodRange.length,
            change: onChangeSecuredPeriod,
            slide: onSlideSecuredPeriod
        });
        $('#LoanPeriodSlider').slider("value", 0, 0);

        $('#flipLinkPeriodMore').hide();
        $('#flipLinkPeriodLess').show();

        currentRequest.periodSlider = "more";
        currentRequest.term = securedSliderPeriodRange[0];
    }
    else
    {
        $('#LoanPeriodSlider').slider("destroy");
        $('#LoanPeriodSlider').slider(
        {
            min: 0,
            max: unsecuredSliderPeriodRange.length - 1,
            steps: unsecuredSliderPeriodRange.length,
            change: onChangeUnsecuredPeriod,
            slide: onSlideUnsecuredPeriod
        });        
        $('#LoanPeriodSlider').slider("value", unsecuredSliderPeriodRange.length - 1, 0);

        $('#flipLinkPeriodMore').show();
        $('#flipLinkPeriodLess').hide();

        currentRequest.periodSlider = "less";
        currentRequest.term = unsecuredSliderPeriodRange[unsecuredSliderPeriodRange.length - 1];
    }

    currentRequest.monthlyRepayment = "";
    $('#ActivationLinePeriod').hide();
    CallData();
    UpdateGUI();
}

function GetIndex(valueArray, value)
{

    for (i = 0; i < valueArray.length; i++)
    {
        if (valueArray[i] == value)
        {
            return i;
        }
    }

    return NaN;
}


/// <summary>
/// Wire up the onload function for the initial call
/// </summary>
function InitialisePage()
{
    $('#InitialFilter').show();
    $('#SecuredLoansDialog').show();
    
    if (currentRequest.amountSlider == "less")
    {
        // unsecured amount
        $('#LoanAmountSlider').slider(
        {
            min: 0,
            max: unsecuredSliderAmountRange.length - 1,
            steps: unsecuredSliderAmountRange.length,
            change: onChangeUnsecuredAmount,
            slide: onSlideUnsecuredAmount
        });        
        $('#flipLinkAmountLess').hide();

        idx = GetIndex(unsecuredSliderAmountRange, currentRequest.amount);
        if (!isNaN(idx))
        {
            $('#LoanAmountSlider').slider("value", idx);
        }
    }
    else
    {
        // secured amount
        $('#LoanAmountSlider').slider(
        {
            min: 0,
            max: securedSliderAmountRange.length - 1,
            steps: securedSliderAmountRange.length,
            change: onChangeSecuredAmount,
            slide: onSlideSecuredAmount
        });         
        $('#flipLinkAmountMore').hide();

        idx = GetIndex(securedSliderAmountRange, currentRequest.amount);
        if (!isNaN(idx))
        {
            $('#LoanAmountSlider').slider("value", idx);
        }
    }

    if (currentRequest.periodSlider == "less")
    {
        // unsecured period
        $('#LoanPeriodSlider').slider(
        {
            min: 0,
            max: unsecuredSliderPeriodRange.length - 1,
            steps: unsecuredSliderPeriodRange.length,
            change: onChangeUnsecuredPeriod,
            slide: onSlideUnsecuredPeriod
        });         
        $('#flipLinkPeriodLess').hide();

        idx = GetIndex(unsecuredSliderPeriodRange, currentRequest.term);
        if (!isNaN(idx))
        {
            $('#LoanPeriodSlider').slider("value", idx);
        }
    }
    else
    {
        // secured period
        $('#LoanPeriodSlider').slider(
        {
            min: 0,
            max: securedSliderPeriodRange.length - 1,
            steps: securedSliderPeriodRange.length,
            change: onChangeSecuredPeriod,
            slide: onSlideSecuredPeriod
        });           
        $('#flipLinkPeriodMore').hide();

        idx = GetIndex(securedSliderPeriodRange, currentRequest.term);
        if (!isNaN(idx))
        {
            $('#LoanPeriodSlider').slider("value", idx);
        }
    }
    UpdateYearsCount();

    $('#LoanRepaymentSlider').slider(
    {
        min: 0,
        max: sliderRepaymentRange.length - 1,
        steps: sliderRepaymentRange.length,
        change: onChangeRepayment,
        slide: onSlideRepayment
    });   

    // find out which slider should be active
    if (currentRequest.monthlyRepayment == 0)
    {
        $('#ActivationLineRepayment').show();
        $('#ActivationLinePeriod').hide();
        UpdateYearsCount();
    }
    else
    {
        $('#ActivationLineRepayment').hide();
        $('#ActivationLinePeriod').show();

        idx = GetIndex(sliderRepaymentRange, currentRequest.monthlyRepayment);
        if (!isNaN(idx))
        {
            $('#LoanRepaymentSlider').slider("value", idx);
        }
    }

    UpdateGUI();

    $("#SliderValueAmount").bind("keypress", HandleKeyUp);
    $("#SliderValueRepayment").bind("keypress", HandleKeyUp);
    $("#SliderValuePeriod").bind("keypress", HandleKeyUp);

    // check if text amends are made to borrowing period
    $("#SliderValuePeriod").bind("keypress", UpdateYearsCount);

    // observe focus/blur on form fields so that tooltips can be shown
    $('#SliderValueAmount').bind('blur', function (event) { $('#ttAmount').hide(); });
    $('#SliderValueAmount').bind('focus', function (event) { $('#ttAmount').show() });
    $('#SliderValuePeriod').bind('blur', function (event) { $('#ttPeriod').hide() });
    $('#SliderValuePeriod').bind('focus', function (event) { $('#ttPeriod').show() });
    $('#SliderValueRepayment').bind('blur', function (event) { hideSelects('visible'); $('#ttRepayment').hide(); });
    $('#SliderValueRepayment').bind('focus', function (event) { hideSelects('hidden'); $('#ttRepayment').show(); });

    // Hook up the Loan Type Selectors
    $('#LoanTypeAll').bind('click', handleLoanType);
    $('#LoanTypeUnsecuredOnly').bind('click', handleLoanType);
    $('#LoanTypeSecuredOnly').bind('click', handleLoanType);

    $('#SecuredLoansDialog').dialog(
    {
        modal: true,
        autoOpen: false,
        height: 440,
        width: 500,
        resizable: false,
        overlay: { opacity: 0.5, background: "black" },
        buttons: { "Ok": function () { SetSecuredOptions(); } },
        open: function (e)
        {
            $('#LBError').hide();
            var employRadio = $('[name=rbEmploymentStatus][value=' + currentRequest.employmentStatus + ']');
            if (employRadio.length > 0)
            {
                employRadio[0].checked = true;
            }

            $('#rbJointApp')[0].checked = currentRequest.isJoint;
            $('#rbSingleApp')[0].checked = !currentRequest.isJoint;

        }
    });

    $('#SetSecuredAnswers').bind('click', function (e)
    {
        $('#SecuredLoansDialog').dialog("open");
    });

    // hide input help tooltips
    $('#ttAmount').hide();
    $('#ttPeriod').hide();
    $('#ttRepayment').hide();

    // halt form submit for safari
    $('#aspnetForm').bind("onsubmit", function () { return false; });    

    CallData();

}

// Wire up the Load event
$(document).ready(function ()
{
    InitialisePage();
});
