﻿$(document).ready(function() {
    $("a.iframe").fancybox({
        'transitionIn': 'fade',
        'transitionOut': 'fade',
        'speedIn': 600,
        'speedOut': 200,
        'overlayShow': true,
        'width': 520,
        'height': 592,
        'titleShow': false,
        'autoDimensions': false,
        'scrolling': 'no'
    });


    $("#aPrivacy").fancybox({
        'transitionIn': 'fade',
        'transitionOut': 'fade',
        'speedIn': 600,
        'speedOut': 200,
        'overlayShow': true,
        'width': 800,
        'height': 470,
        'titleShow': false,
        'autoDimensions': false
    });

    $("input[type=text][title]").each(function() {

        $(this).val($(this).attr("title"));
        if ($.trim($(this).val()) == "")
            $(this).val($(this).attr("title"));
        $(this)

        .focus(function() {
            if ($(this).val() == $(this).attr("title")) $(this).val("");
        })

        .blur(function() {
            if ($.trim($(this).val()) == "") $(this).val($(this).attr("title"));
        });

    });



    $("[id$='hypHere']").click(function(e) {
        parent.$.fancybox.close();
    });


    $("[id$='iBtnGetAdviceIncomeProtection']").click(function(e) {

        if (ValidateIncomeProtectionForm('ctl00_ctl01')) {
            return true;
        }
        else { return false; }
    });

    $("[id$='iBtnGetAdviceLife']").click(function(e) {

        if (ValidateLifeForm('ctl00_ctl01')) {
            return true;
        }
        else { return false; }
    });

    $("[id$='iBtnGetAdviceMortgage']").click(function(e) {

        var loc = $(location).attr('href');

        if ((loc.indexOf("mortgage-popup.aspx") > 0) || (loc.indexOf("Mortgage-Popup.aspx")) > 0) {

            if (ValidateMortgageForm('Mortgage1')) {
                return true;
            }
            else { return false; }
        }
        else {
            if (ValidateMortgageForm('ctl00_ctl01')) {
                return true;
            }
            else { return false; }
        }
    });


    $("[id$='iBtnGetAdviceEquity']").click(function(e) {
        if (ValidateEquityForm('ctl00_ctl01')) {
            return true;
        }
        else { return false; }

    });

//    $("[id$='iBtnGetAdviceDebt']").click(function(e) {
//        if (ValidateDebtForm('ctl00_ctl01')) {
//            return true;
//        }
//        else { return false; }

//    });


    $("[id$='iBtnGetAdviceLoans']").click(function(e) {
        if (ValidateLoanForm('ctl00_ctl01')) {
            return true;
        }
        else { return false; }

    });


    $("[id$='iBtnGetAdviceHealth']").click(function(e) {
        if (ValidateHealthForm('ctl00_ctl01')) {
            return true;
        }
        else { return false; }

    });


    $("[id$='iBtnGetAdviceWill']").click(function(e) {
        if (ValidateWillForm('ctl00_ctl01')) {
            return true;
        }
        else { return false; }

    });


//    $("[id$='iBtnGetAdvicePPI']").click(function(e) {
//        if (ValidateGeneric('ctl00_ctl01')) {
//            return true;
//        }
//        else { return false; }
//    });




 //   $("[id$='aSubmitNewsletter']").click(function(e) {

 //       xmlHttpNewsletter = GetXmlHttpObject();

 //       if (xmlHttpNewsletter == null) {
 //           alert("Your browser does not support AJAX!");
 //           return;
 //       }

 //       var url = "/Common/Newsletter.aspx";
 //       var queryString = "";

//        var nameTextBox = $("[id$='txtNewsletterFirstName']");
//        var emailTextBox = $("[id$='txtNewsletterEmailAddress']");

//        if (($.trim(nameTextBox.val()) == '') || ($.trim(emailTextBox.val()) == '')) {

 //           $('#divShowNewsletterError').html('<b style="color: #FF0000;">Please enter a valid name and e-mail to subscribe to the MoneyHospital newsletter.</b>');

 //           return false;
        //}

//        queryString += "?Name=" + $.trim(nameTextBox.val());
//        queryString += "&EmailAddress=" + $.trim(emailTextBox.val());

//        url = url + queryString;

        // make an async call
//        xmlHttpNewsletter.onreadystatechange = newsletterChanged;
//        xmlHttpNewsletter.open("GET", url, true);
//        xmlHttpNewsletter.send(null);


//    });

//    function newsletterChanged() {

//        if (xmlHttpNewsletter.readyState == 4) {

//            if (xmlHttpNewsletter.responseText == 'Success') {

//                $('#divShowForm').hide();
//                $('.divThankyou').fadeIn('slow');
//            }
//            else {
//                $('#divShowNewsletterError').html('Please enter valid details to subscribe to the MoneyHospital newsletter.');
//            }
//       }
//    }

    // Mortgage Form ==========================================================


    $("[id$='ddlMortgageType']").change(function(e) {

        var mortgageType = $("[id$='ddlMortgageType']");

        if ($.trim(mortgageType.val()) == '6') // Buy a property
        {
            document.getElementById("divFirstTimeBuyer").style.display = "inline";
            document.getElementById("divDebts").style.display = "none";
        }

        if ($.trim(mortgageType.val()) == '1') // remortgage
        {
            document.getElementById("divFirstTimeBuyer").style.display = "none";
            document.getElementById("divDebts").style.display = "inline";
        }

        if ($.trim(mortgageType.val()) == '5') // buy to let
        {
            document.getElementById("divFirstTimeBuyer").style.display = "none";
            document.getElementById("divDebts").style.display = "none";
        }
    });

    $("[id$='rblFirstTimeBuyer_0']").change(function(e) {

        document.getElementById("divFoundProperty").style.display = "inline";
        document.getElementById("divPropertyOnMarket").style.display = "none";
    });

    $("[id$='rblFirstTimeBuyer_1']").change(function(e) {

        document.getElementById("divFoundProperty").style.display = "none";
        document.getElementById("divPropertyOnMarket").style.display = "inline";
    });

});


function SubmitMortgage(controlPrefix, ipAddress) {

    $('#divShowLoading').hide();
    $('#divShowButton').hide();
    $('#brokerText').hide();
    
    if (ValidateMortgageFormForExpressConsent(controlPrefix)) {


        $('#divError').fadeOut('slow');

        xmlHttpMortgages = GetXmlHttpObject();

        if (xmlHttpMortgages == null) {
            alert("Your browser does not support AJAX!");
            return;
        }

        var url = "/Common/BrokerRequest.aspx";
        var queryString = "";

        queryString += "?Type=Mortgage";
        queryString += "&MortgageType=" + document.getElementById(controlPrefix + "_ddlMortgageType").value;
        queryString += "&MortgageSize=" + document.getElementById(controlPrefix + "_txtMortgageAmount").value;
        queryString += "&PropertyValue=" + document.getElementById(controlPrefix + "_txtPropertyValue").value;

        var selfCert = document.getElementById(controlPrefix + "_rblSelfCertify_1").checked;

        if (selfCert) {
            queryString += "&SelfCert=0";
        }
        else { queryString += "&SelfCert=1"; }

        queryString += "&BadCredit=0";

        if (document.getElementById(controlPrefix + "_ddlMortgageType").value == '6') {

            var ftb = document.getElementById(controlPrefix + "_rblFirstTimeBuyer_0").checked;

            if (ftb) {
                queryString += "&FTB=1";
            }
            else { queryString += "&FTB=0"; }

            var fp = document.getElementById(controlPrefix + "_rblFoundProperty_0").checked;

            if (fp) {
                queryString += "&FP=1";
            }
            else { queryString += "&FP=0"; }

            var pom = document.getElementById(controlPrefix + "_rblPropertyOnMarket_0").checked;

            if (pom) {
                queryString += "&IsPropertyOnMarket=1";
            }
            else { queryString += "&IsPropertyOnMarket=0"; }
        }
        else {
            queryString += "&FTB=0";
            queryString += "&FP=0";
            queryString += "&IsPropertyOnMarket=0";
        }

        queryString += "&postcode=" + document.getElementById(controlPrefix + "_txtPostcode").value;
        queryString += "&ipAddress=" + ipAddress;
        queryString += "&hiddenFieldName=" + controlPrefix + "_hidSessionId";

        url = url + queryString;
        
        // make an async call
        xmlHttpMortgages.onreadystatechange = mortgagestateChanged;
        xmlHttpMortgages.open("GET", url, true);
        xmlHttpMortgages.send(null);

        $('#divShowLoading').show();
        $('#divShowButton').hide();
        $('#brokerText').hide();
    }
}

function ChangeLifeInsuranceAmount(controlPrefix) {


    if (document.getElementById(controlPrefix + "_chkCover").checked) {

        document.getElementById(controlPrefix + "_txtCoverAmount").readOnly = true;
        document.getElementById(controlPrefix + "_txtCoverAmount").value = "";
        document.getElementById(controlPrefix + "_txtCoverAmount").setAttribute("class", "txtSmallFade");
    }
    else {
        document.getElementById(controlPrefix + "_txtCoverAmount").readOnly = false;
        document.getElementById(controlPrefix + "_txtCoverAmount").setAttribute("class", "txtSmall");
    }
}

function SubmitLifeInsurance(controlPrefix, ipAddress) {

    var jointPolicy = document.getElementById(controlPrefix + "_rblCoverFor_1").checked;

    if (jointPolicy) {
        document.getElementById("divShowPartnerDetails").style.display = "inline";
        document.getElementById("divShowSinglePolicyText").style.display = "none";
    }
    else {
        document.getElementById("divShowPartnerDetails").style.display = "none";
        document.getElementById("divShowSinglePolicyText").style.display = "inline";
    }    
    
    if (ValidateLifeFormExpressConsent(controlPrefix)) {

        xmlHttpLife = GetXmlHttpObject();

        if (xmlHttpLife == null) {
            alert("Your browser does not support AJAX!");
            return;
        }

        var url = "/Common/BrokerRequest.aspx";
        var queryString = "";

        queryString += "?Type=Life";
        queryString += "&LeadType=" + document.getElementById(controlPrefix + "_ddlPolicyType").value;
        queryString += "&CoverAmount=" + document.getElementById(controlPrefix + "_ddlCoverAmount").value;
        queryString += "&CoverUnsure=0";

        if (document.getElementById(controlPrefix + "_rblCoverFor_1").checked) {
            queryString += "&ApplicantType=2";
        }
        else { queryString += "&ApplicantType=1"; }

        if (document.getElementById(controlPrefix + "_chkCriticalIlless").checked) {
            queryString += "&CriticalIllness=1";
        }
        else { queryString += "&CriticalIllness=0"; }

        queryString += "&Applicant1Profession=" + document.getElementById(controlPrefix + "_ddlProfession").value;

        if (document.getElementById(controlPrefix + "_rblCoverFor").value == 1) {
            queryString += "&Applicant2Profession=" + document.getElementById(controlPrefix + "_ddlPartnerProfession").value;
        }
        else { queryString += "&Applicant2Profession=-1"; }

        queryString += "&postcode=" + document.getElementById(controlPrefix + "_txtPostcode").value;
        queryString += "&ipAddress=" + ipAddress;
        queryString += "&hiddenFieldName=" + controlPrefix + "_hidSessionId";

        url = url + queryString;
        
        // make an async call
        xmlHttpLife.onreadystatechange = lifestateChanged;
        xmlHttpLife.open("GET", url, true);
        xmlHttpLife.send(null);
    }
}


function SubmitHealth(controlPrefix, ipAddress) {

    $('#divShowLoading').hide();
    $('#divShowButton').hide();
    $('#brokerText').hide();
    
    if (ValidateHealthFormExpressConsent(controlPrefix)) {

        xmlHttpHealth = GetXmlHttpObject();

        if (xmlHttpHealth == null) {
            alert("Your browser does not support AJAX!");
            return;
        }

        var url = "/Common/BrokerRequest.aspx";
        var queryString = "";

        queryString += "?Type=Health";
        queryString += "&CoverType=" + document.getElementById(controlPrefix + "_ddlCoverFor").value;
        queryString += "&postcode=" + document.getElementById(controlPrefix + "_txtPostcode").value;
        queryString += "&ipAddress=" + ipAddress;
        queryString += "&hiddenFieldName=" + controlPrefix + "_hidSessionId";

        url = url + queryString;

        // make an async call
        xmlHttpHealth.onreadystatechange = healthstateChanged;
        xmlHttpHealth.open("GET", url, true);
        xmlHttpHealth.send(null);

        $('#divShowLoading').show();
        $('#divShowButton').hide();
        $('#brokerText').hide();
    }
}

function ValidateLifeFormExpressConsent(controlPrefix) {

    if ((!document.getElementById(controlPrefix + "_rblCoverFor_0").checked) && (!document.getElementById(controlPrefix + "_rblCoverFor_1").checked)) {

        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlPolicyType").value == '') {

        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlCoverAmount").value == '') {

        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlCoverPeriod").value == '') {

        return false;
    }

    if (document.getElementById(controlPrefix + "_rblCoverFor").value == 1) {

        if ((document.getElementById(controlPrefix + "_ddlPartnerDOBDay").value == '') && (document.getElementById(controlPrefix + "_ddlPartnerDOBMonth").value == '') && (document.getElementById(controlPrefix + "_ddlPartnerDOBYear").value == '')) {

            return false;
        }
        if (document.getElementById(controlPrefix + "_ddlPartnerProfession").value == '') {

            return false;
        }
    } 
    
    if (document.getElementById(controlPrefix + "_txtPostcode").value == '') {

        return false;
    } else {
        if (document.getElementById(controlPrefix + "_txtPostcode").length < 6) {


            return false;
        }
    }

    if (document.getElementById(controlPrefix + "_ddlProfession").value == '') {

        return false;
    }
    return true;
}

function ValidateLifeForm(controlPrefix) {

    if ((!document.getElementById(controlPrefix + "_rblCoverFor_0").checked) && (!document.getElementById(controlPrefix + "_rblCoverFor_1").checked)) {
        $('#divError p').html('Please select if you require a single or joint policy');
        $('#divError').fadeIn('slow');
        return false;
    }
    
    if (document.getElementById(controlPrefix + "_ddlPolicyType").value == '') {
        $('#divError p').html('Please select the type of life insurance policy you are after');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlCoverAmount").value == '') {
    
        $('#divError p').html('Please select how much cover you need');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlCoverPeriod").value == '') {

        $('#divError p').html('Please select how long you would like your policy to last');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (!ValidateGeneric(controlPrefix)) {
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlProfession").value == '') {
        $('#divError p').html('Please select your profession');
        $('#divError').fadeIn('slow');
        return false;
    }
    
    if (document.getElementById(controlPrefix + "_rblCoverFor").value == 1) {

        if ((document.getElementById(controlPrefix + "_ddlPartnerDOBDay").value == '') && (document.getElementById(controlPrefix + "_ddlPartnerDOBMonth").value == '') && (document.getElementById(controlPrefix + "_ddlPartnerDOBYear").value == '')) {
            $('#divError p').html('Please enter a valid date of birth for your partner');
            $('#divError').fadeIn('slow');
            return false;
        }
        if (document.getElementById(controlPrefix + "_ddlPartnerProfession").value == '') {
            $('#divError p').html('Please select your partners profession');
            $('#divError').fadeIn('slow');
            return false;
        }
    }

    if (document.getElementById(controlPrefix + "_hidSessionId").value == '') {

        $('#divError p').html('You cannot proceed until we find a match for your information. Please wait a few more seconds.');
        $('#divError').fadeIn('slow');

        SubmitLifeInsurance(controlPrefix, '127.0.0.1');
        return false;
    }


    return true;
}

function ValidateWillForm(controlPrefix) {

    if ((!document.getElementById(controlPrefix + "_rblAlreadyHaveWill_0").checked) && (!document.getElementById(controlPrefix + "_rblAlreadyHaveWill_1").checked)) {
        $('#divError p').html('Please select if you already have a will');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_rblAlreadyHaveWill_0").checked) {
        if (document.getElementById(controlPrefix + "_ddlLastUpdated").value == '') {

            $('#divError p').html('Please select when your will was last updated');
            $('#divError').fadeIn('slow');
            return false;
        }
    }

    if ((!document.getElementById(controlPrefix + "_rblIsMarried_0").checked) && (!document.getElementById(controlPrefix + "_rblIsMarried_1").checked)) {
        $('#divError p').html('Please select if you are married');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlDependantChildren").value == '') {

        $('#divError p').html('Please select how many dependant children you have');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (!ValidateGeneric(controlPrefix)) {
        return false;
    }

    return true;
}
function ValidateHealthFormExpressConsent(controlPrefix) {


    if (document.getElementById(controlPrefix + "_ddlCoverFor").value == '') {

        return false;
    } 
    
    if (document.getElementById(controlPrefix + "_txtPostcode").value == '') {

        return false;
    } else {
        if (document.getElementById(controlPrefix + "_txtPostcode").length < 6) {


            return false;
        }
    }
    
    return true;
}

function ValidateHealthForm(controlPrefix) {


    if (document.getElementById(controlPrefix + "_ddlCoverFor").value == '') {
        $('#divError p').html('Please select who the cover is for');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlCoverFor").value == '4') {
        if (document.getElementById(controlPrefix + "_ddlNumberOfEmployees").value == '') {
            $('#divError p').html('Please select how many employees the health insurance will cover');
            $('#divError').fadeIn('slow');
            return false;
        }
    }
    
    if ((!document.getElementById(controlPrefix + "_rblHaveInsurance_0").checked) && (!document.getElementById(controlPrefix + "_rblHaveInsurance_1").checked)) {
        $('#divError p').html('Please select if you currently have medical cover');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (!ValidateGeneric(controlPrefix)) {
        return false;
    }

    return true;
}

//function ValidateDebtForm(controlPrefix) {

//    if (document.getElementById(controlPrefix + "_txtDebtAmount").value == '') {
//        $('#divError p').html('Please enter your total amount of debt');
//        $('#divError').fadeIn('slow');
//        return false;
//    }

//    if (document.getElementById(controlPrefix + "_txtDebtAmount").value < 1000) {
//        $('#divError p').html('Your total debt must be over &pound;250');
//        $('#divError').fadeIn('slow');
//        return false;
//    }

//    if (document.getElementById(controlPrefix + "_txtDebtAmount").value > 1000000) {
//        $('#divError p').html('Your total debt must be under &pound;1,000,000');
//        $('#divError').fadeIn('slow');
//        return false;
//    }

//    if (document.getElementById(controlPrefix + "_ddlTotalCreditors").value == '') {
//        $('#divError p').html('Please select how many creditors you have');
//        $('#divError').fadeIn('slow');
//        return false;
//    }

//    if (document.getElementById(controlPrefix + "_ddlEmploymentStatus").value == '') {
//        $('#divError p').html('Please select your employment status');
//        $('#divError').fadeIn('slow');
//        return false;
//    }

//    if (!ValidateGeneric(controlPrefix)) {
//        return false;
//    }

//    return true;
//}

function ValidateLoanForm(controlPrefix) {

    if (document.getElementById(controlPrefix + "_txtLoanAmount").value == '') {
        $('#divError p').html('Please enter the amount you wish to borrow');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtLoanAmount").value < 250) {
        $('#divError p').html('The amount you want to borrow must be over &pound;250');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtLoanAmount").value > 1000000) {
        $('#divError p').html('The amount you want to borrow must be under &pound;1,000,000');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlLoanPeriod").value == '') {
        $('#divError p').html('Please select how long you would like to take the loan over');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlLoanPurpose").value == '') {
        $('#divError p').html('Please select the loan purpose');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlEmploymentStatus").value == '') {
        $('#divError p').html('Please select your employment status');
        $('#divError').fadeIn('slow');
        return false;
    }

    if ((!document.getElementById(controlPrefix + "_rblIsHomeowner_0").checked) && (!document.getElementById(controlPrefix + "_rblIsHomeowner_1").checked)) {
        $('#divError p').html('Please select if you are a homeowner');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (!ValidateGeneric(controlPrefix)) {
        return false;
    }

    return true;
}


function ValidateIncomeProtectionFormExpressContent(controlPrefix) {

    if (document.getElementById(controlPrefix + "_ddlCoverAgainst").value == '') {

        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlClaimLength").value == '') {

        return false;
    }

    if (document.getElementById(controlPrefix + "_txtPostcode").value == '') {

        return false;
    }
    else {
        if (document.getElementById(controlPrefix + "_txtPostcode").length < 6) {
            return false;
        }
    }

    return true;
}


function ValidateIncomeProtectionForm(controlPrefix) {

    if (document.getElementById(controlPrefix + "_ddlCoverAgainst").value == '') {
        $('#divError p').html('Please select what you would like to cover against');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlClaimLength").value == '') {
        $('#divError p').html('Please select how long you would be willing to wait for your claim payout');
        $('#divError').fadeIn('slow');
        return false;
    }
    
    if (!ValidateGeneric(controlPrefix)) {
        return false;
    }

    return true;
}

function ValidateEquityForm(controlPrefix) {

    if (!ValidateGeneric(controlPrefix)) {
    
        return false;
    }

    var age = Age(document.getElementById(controlPrefix + "_ddlDOBDay").value, document.getElementById(controlPrefix + "_ddlDOBMonth").value, document.getElementById(controlPrefix + "_ddlDOBYear").value);

    if (age < 55) {
        $('#divError p').html('You must by 55 or over to receive advice about an equity release mortgage.');
        $('#divError').fadeIn('slow');
        return false;
    }

    return true;
}

function Age(bdya, bmo, byr) {
    var age;
    var now = new Date();
    tday = now.getDate();
    tmo = (now.getMonth());
    tyr = (now.getFullYear());

    {
        if ((tmo > bmo) || (tmo == bmo & tday >= bday))
        { age = byr }

        else
        { age = byr + 1 }

    }

    return tyr - age;
}


function ValidateGeneric(controlPrefix) {

    if (document.getElementById(controlPrefix + "_txtFirstName").value == '') {
        $('#divError p').html('Please enter your first name');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtLastName").value == '') {
        $('#divError p').html('Please enter your last name');
        $('#divError').fadeIn('slow');
        return false;
    }

    if ((document.getElementById(controlPrefix + "_ddlDOBDay").value == '') && (document.getElementById(controlPrefix + "_ddlDOBMonth").value == '') && (document.getElementById(controlPrefix + "_ddlDOBYear").value == '')) {
        $('#divError p').html('Please enter a valid date of birth');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtAddressLine1").value == '') {
        $('#divError p').html('Please enter the first line of your address');
        $('#divError').fadeIn('slow');
        return false;
    }
    if (document.getElementById(controlPrefix + "_txtPostcode").value == '') {
        $('#divError p').html('Please enter your postcode');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtContactNumber").value == '') {
        $('#divError p').html('Please enter your contact number');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtEmailAddress").value == '') {
        $('#divError p').html('Please enter your email address');
        $('#divError').fadeIn('slow');
        return false;
    }

    return true;
}


function SubmitIncomeProtection(controlPrefix, ipAddress) {

    $('#divShowLoading').hide();
    $('#divShowButton').hide();
    $('#brokerText').hide();
    
    if (ValidateIncomeProtectionFormExpressContent(controlPrefix)) {

        xmlHttpIncome = GetXmlHttpObject();

        if (xmlHttpIncome == null) {
            alert("Your browser does not support AJAX!");
            return;
        }

        var url = "/Common/BrokerRequest.aspx";
        var queryString = "";

        queryString += "?Type=Income";
        queryString += "&CoverAgainst=" + document.getElementById(controlPrefix + "_ddlCoverAgainst").value;
        queryString += "&ClaimLength=" + document.getElementById(controlPrefix + "_ddlClaimLength").value;
        queryString += "&Postcode=" + document.getElementById(controlPrefix + "_txtPostcode").value;
        queryString += "&ipAddress=" + ipAddress;
        queryString += "&hiddenFieldName=" + controlPrefix + "_hidSessionId";

        url = url + queryString;

        // make an async call
        xmlHttpIncome.onreadystatechange = incomestateChanged;
        xmlHttpIncome.open("GET", url, true);
        xmlHttpIncome.send(null);
        
        $('#divShowLoading').show();
        $('#divShowButton').hide();
        $('#brokerText').hide();
    }
}

function YN_to_10(input) {
    if (input == 'Y')
        return '1';
    if (input == 'N')
        return '0';

    return '0';
}


//============================= creates XmlHttp object for different browsers ==================================================
function GetXmlHttpObject() {
    var xmlHttp = null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

//========================== The stateChanged() function executes every time the state of the XMLHTTP object changes.==============
function stateChanged() {

    /* ============ XML structure ====================
    <root>
    <strErrorCode>num</strErrorCode>" +
    <strErrorMessage>string</strErrorMessage>" +
    <strSessionId>string</strSessionId>" +
    <strDisplayText>string</strDisplayText>" +
    <strLeadPrice>num<strLeadPrice>
    </root>      
    ============ END XML structure ================= */
    //alert("Hello");

    // if a response has been received from the server

    $('#divShowLoading').hide();
    $('#divShowButton').hide();
    $('#brokerText').hide();
    
    if (xmlHttp.readyState == 4) {
        if (window.ActiveXObject) {
            var doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = "false";
            doc.loadXML(xmlHttp.responseText);
        }
        // code for Mozilla, Firefox, Opera, etc.
        else {
            var parser = new DOMParser();
            var textXml = xmlHttp.responseText;
            var doc = parser.parseFromString(textXml, "text/xml");
        }

        // documentElement always represents the root node  
        var xmlDoc = doc.documentElement;

        if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "-1") {
            // DO Nothing
        }
        else {

            $('#divShowLoading').hide();
            $('#divShowButton').show();
            
            // Fade button in
            var getAdviceButton = $("[id$='iBtnGetAdviceMortgage']");
            getAdviceButton.css("filter", "alpha(opacity=100");

            var loc = $(location).attr('href');
            
            //check the errocode xml node
            if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "0") {

                if ((loc.indexOf("mortgage-popup.aspx") > 0) || (loc.indexOf("Mortgage-Popup.aspx")) > 0) {

                    $.fancybox.close();
                    return false;
                }
                else {
                    // display success message
                    $('#brokerText').show();
                    document.getElementById("brokerText").innerHTML = xmlDoc.childNodes[3].childNodes[0].nodeValue;
                    document.getElementById(xmlDoc.childNodes[6].childNodes[0].nodeValue).value = xmlDoc.childNodes[2].childNodes[0].nodeValue;
                }
            }
            else {
                // display error message

                if ((loc.indexOf("mortgage-popup.aspx") > 0) || (loc.indexOf("Mortgage-Popup.aspx")) > 0) {

                    return false;
                }
                else {
                    $('#brokerText').show();
                    $('#divShowButton').hide();
                    document.getElementById("brokerText").innerHTML = "There has been a problem trying to find an FSA regulated broker: " + xmlDoc.childNodes[1].childNodes[0].nodeValue;
                }
            }
        }
    }
}


//========================== The stateChanged() function executes every time the state of the XMLHTTP object changes.==============
function lifestateChanged() {

    /* ============ XML structure ====================
    <root>
    <strErrorCode>num</strErrorCode>" +
    <strErrorMessage>string</strErrorMessage>" +
    <strSessionId>string</strSessionId>" +
    <strDisplayText>string</strDisplayText>" +
    <strLeadPrice>num<strLeadPrice>
    </root>      
    ============ END XML structure ================= */
    //alert("Hello");

    // if a response has been received from the server

    if (xmlHttpLife.readyState == 4) {
        if (window.ActiveXObject) {
            var doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = "false";
            doc.loadXML(xmlHttpLife.responseText);
        }
        // code for Mozilla, Firefox, Opera, etc.
        else {
            var parser = new DOMParser();
            var textXml = xmlHttpLife.responseText;
            var doc = parser.parseFromString(textXml, "text/xml");
        }

        // documentElement always represents the root node  
        var xmlDoc = doc.documentElement;

        if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "-1") {
            // DO Nothing
        }
        else {
            // Fade button in
            var getAdviceButton = $("[id$='iBtnGetAdviceLife']");
            getAdviceButton.css("filter", "alpha(opacity=100");


            //check the errocode xml node
            if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "0") {


                $('#brokerText').show();
                document.getElementById("brokerText").innerHTML = xmlDoc.childNodes[3].childNodes[0].nodeValue;
                document.getElementById(xmlDoc.childNodes[6].childNodes[0].nodeValue).value = xmlDoc.childNodes[2].childNodes[0].nodeValue;

            }
            else {

                document.getElementById("brokerText").innerHTML = "There has been a problem trying to find an FSA regulated broker: " + xmlDoc.childNodes[1].childNodes[0].nodeValue;

            }
        }
    }
}


function incomestateChanged() {

    /* ============ XML structure ====================
    <root>
    <strErrorCode>num</strErrorCode>" +
    <strErrorMessage>string</strErrorMessage>" +
    <strSessionId>string</strSessionId>" +
    <strDisplayText>string</strDisplayText>" +
    <strLeadPrice>num<strLeadPrice>
    </root>      
    ============ END XML structure ================= */
    //alert("Hello");

    // if a response has been received from the server

    if (xmlHttpIncome.readyState == 4) {
        if (window.ActiveXObject) {
            var doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = "false";
            doc.loadXML(xmlHttpIncome.responseText);
        }
        // code for Mozilla, Firefox, Opera, etc.
        else {
            var parser = new DOMParser();
            var textXml = xmlHttpIncome.responseText;
            var doc = parser.parseFromString(textXml, "text/xml");
        }


        $('#divShowLoading').hide();
        $('#divShowButton').hide();
        $('#brokerText').hide();
        
        // documentElement always represents the root node  
        var xmlDoc = doc.documentElement;

        if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "-1") {
            // DO Nothing
        }
        else {

            $('#divShowLoading').hide();
            $('#divShowButton').show();
            // Fade button in
            var getAdviceButton = $("[id$='iBtnGetAdviceIncomeProtection']");
            getAdviceButton.css("filter", "alpha(opacity=100");


            //check the errocode xml node
            if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "0") {


                    $('#brokerText').show();
                    document.getElementById("brokerText").innerHTML = xmlDoc.childNodes[3].childNodes[0].nodeValue;
                    document.getElementById(xmlDoc.childNodes[6].childNodes[0].nodeValue).value = xmlDoc.childNodes[2].childNodes[0].nodeValue;
                
            }
            else {

                    $('#brokerText').show();
                    $('#divShowButton').hide();
                    document.getElementById("brokerText").innerHTML = "There has been a problem trying to find an FSA regulated broker: " + xmlDoc.childNodes[1].childNodes[0].nodeValue;
                
            }
        }
    }
}


function mortgagestateChanged() {


    /* ============ XML structure ====================
    <root>
    <strErrorCode>num</strErrorCode>" +
    <strErrorMessage>string</strErrorMessage>" +
    <strSessionId>string</strSessionId>" +
    <strDisplayText>string</strDisplayText>" +
    <strLeadPrice>num<strLeadPrice>
    </root>      
    ============ END XML structure ================= */
    //alert("Hello");

    // if a response has been received from the server

    if (xmlHttpMortgages.readyState == 4) {
        
        if (window.ActiveXObject) {
            var doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = "false";
            doc.loadXML(xmlHttpMortgages.responseText);
        }
        // code for Mozilla, Firefox, Opera, etc.
        else {
            var parser = new DOMParser();
            var textXml = xmlHttpMortgages.responseText;
            var doc = parser.parseFromString(textXml, "text/xml");
        }

        $('#divShowLoading').hide();
        $('#divShowButton').hide();
        $('#brokerText').hide();
        
        // documentElement always represents the root node  
        var xmlDoc = doc.documentElement;

        if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "-1") {
            return false;
        }
        else {

            $('#divShowLoading').hide();
            $('#divShowButton').show();
            
            // Fade button in
            var getAdviceButton = $("[id$='iBtnGetAdviceMortgage']");
            getAdviceButton.css("filter", "alpha(opacity=100");

            var loc = $(location).attr('href');

            //check the errocode xml node
            if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "0") {

                if ((loc.indexOf("mortgage-popup.aspx") > 0) || (loc.indexOf("Mortgage-Popup.aspx")) > 0) {

                    $.fancybox.close();
                    return false;
                }
                else {
                    $('#brokerText').show();
                    // display success message
                    document.getElementById("brokerText").innerHTML = xmlDoc.childNodes[3].childNodes[0].nodeValue;
                    document.getElementById(xmlDoc.childNodes[6].childNodes[0].nodeValue).value = xmlDoc.childNodes[2].childNodes[0].nodeValue;
                }
            }
            else {
                // display error message

                if ((loc.indexOf("mortgage-popup.aspx") > 0) || (loc.indexOf("Mortgage-Popup.aspx")) > 0) {

                    return false;
                }
                else {
                    $('#brokerText').show();
                    $('#divShowButton').hide();
                    document.getElementById("brokerText").innerHTML = "There has been a problem trying to find an FSA regulated broker: " + xmlDoc.childNodes[1].childNodes[0].nodeValue;
                }
            }
        }
    }
}

function healthstateChanged() {

    /* ============ XML structure ====================
    <root>
    <strErrorCode>num</strErrorCode>" +
    <strErrorMessage>string</strErrorMessage>" +
    <strSessionId>string</strSessionId>" +
    <strDisplayText>string</strDisplayText>" +
    <strLeadPrice>num<strLeadPrice>
    </root>      
    ============ END XML structure ================= */
    //alert("Hello");

    // if a response has been received from the server

    if (xmlHttpHealth.readyState == 4) {
        if (window.ActiveXObject) {
            var doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = "false";
            doc.loadXML(xmlHttpHealth.responseText);
        }
        // code for Mozilla, Firefox, Opera, etc.
        else {
            var parser = new DOMParser();
            var textXml = xmlHttpHealth.responseText;
            var doc = parser.parseFromString(textXml, "text/xml");
        }

        $('#divShowLoading').hide();
        $('#divShowButton').hide();
        $('#brokerText').hide();
        
        // documentElement always represents the root node  
        var xmlDoc = doc.documentElement;

        if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "-1") {
            // DO Nothing
        }
        else {

            $('#divShowLoading').hide();
            $('#divShowButton').show();
            // Fade button in
            var getAdviceButton = $("[id$='iBtnGetAdviceHealth']");
            getAdviceButton.css("filter", "alpha(opacity=100");

            var loc = $(location).attr('href');

            //check the errocode xml node
            if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "0") {

                if ((loc.indexOf("mortgage-popup.aspx") > 0) || (loc.indexOf("Mortgage-Popup.aspx")) > 0) {

                    $.fancybox.close();
                    return false;
                }
                else {
                    // display success message
                    $('#brokerText').show();
                    document.getElementById("brokerText").innerHTML = "<p><strong>" + xmlDoc.childNodes[3].childNodes[0].nodeValue + "</strong></p>";
                    document.getElementById(xmlDoc.childNodes[6].childNodes[0].nodeValue).value = xmlDoc.childNodes[2].childNodes[0].nodeValue;
                }
            }
            else {
                // display error message

                if ((loc.indexOf("mortgage-popup.aspx") > 0) || (loc.indexOf("Mortgage-Popup.aspx")) > 0) {

                    return false;
                }
                else {
                    $('#divShowButton').hide();
                    $('#brokerText').show();
                    document.getElementById("brokerText").innerHTML = "<p><strong>There has been a problem trying to find an FSA regulated broker: " + xmlDoc.childNodes[1].childNodes[0].nodeValue + "</strong></p>";
                }
            }
        }
    }
}



function ValidateMortgageFormForExpressConsent(controlPrefix) {

    var ltv = 85;

    if (document.getElementById(controlPrefix + "_ddlMortgageType").value == '') {

        return false;
    }

    if (document.getElementById(controlPrefix + "_txtMortgageAmount").value == '') {

        return false;
    }

    if (document.getElementById(controlPrefix + "_txtMortgageAmount").value < 25000) {

        return false;
    }

    if (document.getElementById(controlPrefix + "_txtMortgageAmount").value > 5000000) {

        return false;
    }

    if (document.getElementById(controlPrefix + "_txtPropertyValue").value == '') {

        return false;
    }

    if (document.getElementById(controlPrefix + "_txtPropertyValue").value < 25000) {

        return false;
    }

    if (document.getElementById(controlPrefix + "_txtPropertyValue").value > 5000000) {

        return false;
    }

    var amount = (document.getElementById(controlPrefix + "_txtMortgageAmount").value / document.getElementById(controlPrefix + "_txtPropertyValue").value);

    amount = amount * 100;

    if (amount > ltv) {
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtPostcode").value == '') {

        return false;
    } else {
        if (document.getElementById(controlPrefix + "_txtPostcode").length < 6) {


            return false;
        }
    }
    
    return true;
}

function ValidateMortgageForm(controlPrefix) {

    var ltv = 85;
    
    if (document.getElementById(controlPrefix + "_ddlMortgageType").value == '') {

        $('#divError p').html('Please select the mortgage type');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtMortgageAmount").value == '') {
        $('#divError p').html('Please enter the mortgage amount');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtMortgageAmount").value < 25000) {
        $('#divError p').html('The mortgage amount must be a above &pound;25,000');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtMortgageAmount").value > 5000000) {
        $('#divError p').html('The mortgage amount must be a below &pound;5,000,000');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtPropertyValue").value == '') {
        $('#divError p').html('Please enter the property value');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtPropertyValue").value < 25000) {
        $('#divError p').html('The property value must be a above &pound;25,000');
        $('#divError').fadeIn('slow');
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtPropertyValue").value > 5000000) {
        $('#divError p').html('The property value must be a below &pound;5,000,000');
        $('#divError').fadeIn('slow');
        return false;
    }

    var amount = (document.getElementById(controlPrefix + "_txtMortgageAmount").value / document.getElementById(controlPrefix + "_txtPropertyValue").value);

    amount = amount * 100;

    if (amount > ltv) {
        $('#divError p').html('The mortgage loan to value is incorrect, please adjust the amount you wish to borrow or your property value');
        $('#divError').fadeIn('slow');
        return false;
    }
    
    if (!ValidateGeneric(controlPrefix)) {
        return false;
    }
    
    if (document.getElementById(controlPrefix + "_ddlEmploymentStatus").value == '') {
        $('#divError p').html('Please select your employment status');
        $('#divError').fadeIn('slow');
        return false;
    }

    return true;
}
