(function(f){window.setTimeout = f(window.setTimeout);window.setInterval = f(window.setInterval);})(function(f){return function(c,t){var a = Array.prototype.slice.call(arguments,2);if(typeof c != "function")c = new Function(c);return f(function(){c.apply(this, a)}, t)}});
jQuery.preloadImages = function(){
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

function ViewDPA(){
$('.dpa_declaration').dialog({
            bgiframe: true,
            modal: true,
	    title: "Data Protection",
            width: 450,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                }
            }
        });
}
function checkSelected(){
	//show selected on page refresh
	$("DIV.medicinfo UL LI INPUT.y").each(function(){
		var itemIndex = $(this).parents('DIV.application').children('FIELDSET').index($(this).parents("DIV.medicinfo").parents("FIELDSET"));
		if($(this).is(':checked')){
			$(this).parents("ul").nextUntil("P").show();
			$(this).parents("ul").nextUntil("P").children("FIELDSET").children("P").children("INPUT, TEXTAREA").addClass("required");
			$("DIV.application DIV.gpreport:eq("+itemIndex+")").show();		
			$("DIV.application DIV.gpreport:eq("+itemIndex+")").children("FIELDSET").children("P").children("INPUT, TEXTAREA").addClass("required");
		}							   
	});
	var counter = 0;	
	$("DIV.medicinfo UL LI INPUT.mq").each(function(){

		if($(this).is(':checked')){
			$(this).parents("DIV.uroute").siblings("DIV.fmu").show();
			counter++;
		}
	});
	if(counter == 0 && $("DIV.medicinfo UL LI INPUT.mq").length){
		//set all answers to no
		$("DIV.fmu").children("DIV.medicinfo").children('FIELDSET').children("UL").children("LI").children("INPUT.n").each(function(){
			$(this).attr("checked", "checked");	
			$(this).parents("UL").nextAll("DIV.addinfo").hide();
			$(this).parents("UL").nextAll("DIV.addinfo").children("FIELDSET").children("P").children("INPUT, TEXTAREA").removeClass("required error valid");
		});
		$("DIV.application DIV.gpreport:eq(0)").hide();
		$("DIV.application DIV.gpreport:eq(0)").children("FIELDSET").children("P").children("INPUT").removeClass("required error valid");
	}
}

function validateEmail(elementValue){
   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/;
   return emailPattern.test(elementValue);
}

function repositionButtons(defaultVal){
	var lookuptype = "postcode";
	if($("DIV.bankdetails").size()>0){
		lookuptype = "sortcode";
	}
	var initialVal = defaultVal;
	var btnVals = new Array;
	var fieldVals = new Array;
	var headSpace = $("DIV.genericheaderbox").offset();
	var headSpaceTop = Math.round(headSpace.top);
	if($("DIV.genericform").size()>0){
		headSpaceTop = headSpaceTop + 9;
	}
	var btnOffset = 0;
	$("DIV.findaddress").each(function(i){
		btnOffset = $(this).offset();
		var newPos = Math.round(btnOffset.top)-(headSpaceTop+3);		
		btnVals.push([i,newPos]);		
	});
	var fieldOffset = 0;
	$("INPUT."+lookuptype).each(function(i){
		fieldOffset = $(this).offset();
		var newPos = Math.round(fieldOffset.top)-(headSpaceTop+3);		
		fieldVals.push([i,newPos]);
	});
	
	var newVal = 100;
	
	for(i=0;i<$("DIV.findaddress").length;i++){
		if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
		initialVal = initialVal+14;
		}
		newVal = fieldVals[i][1]-initialVal;
		$("DIV.instance"+i).css({"top":newVal+"px"});
	}
	
}

$(document).ready(function() {
    $.preloadImages(
		"/Templates/assets/img/bg/loader.gif",
		"/Templates/assets/img/bg/nav1_l_o.gif",
		"/Templates/assets/img/bg/nav1_l_o_active2.gif",
		"/Templates/assets/img/bg/nav1_l_o_active3.gif",
		"/Templates/assets/img/bg/nav1_r_o.gif",
		"/Templates/assets/img/bg/nav2_l_active2_rollover1.gif",
		"/Templates/assets/img/bg/nav2_l_o.gif",
		"/Templates/assets/img/bg/nav2_l_o_active1.gif",
		"/Templates/assets/img/bg/nav2_l_o_active3.gif",
		"/Templates/assets/img/bg/nav2_r_active3.gif",
		"/Templates/assets/img/bg/nav2_r_o.gif",
		"/Templates/assets/img/bg/nav3_l_active2.gif",
		"/Templates/assets/img/bg/nav3_l_o.gif",
		"/Templates/assets/img/bg/nav3_l_o_active1.gif",
		"/Templates/assets/img/bg/nav3_l_o_active1_rollover2.gif",
		"/Templates/assets/img/bg/nav3_l_o_active2.gif",
		"/Templates/assets/img/bg/nav3_r_active2.gif",
		"/Templates/assets/img/bg/nav3_r_o.gif",
		"/Templates/assets/img/bg/purplenav_active.gif",
		"/Templates/assets/img/bg/purplenav_active_l.gif",
		"/Templates/assets/img/bg/purplenav_active_r.gif",
		"/Templates/assets/img/bg/greennav_active.gif",
		"/Templates/assets/img/bg/greennav_active_l.gif",
		"/Templates/assets/img/bg/greennav_active_r.gif",
		"/Templates/assets/img/bg/nav4_l_o.gif",
		"/Templates/assets/img/bg/nav4_r_o.gif",
		"/Templates/assets/img/bg/nav4_l.gif",
		"/Templates/assets/img/bg/nav4_r.gif"
	);
    //swfobject : http://code.google.com/p/swfobject/wiki/documentation
    //swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn)
    //swfobject.embedSWF("/Templates/assets/swf/sample.swf", "genericflash", "670", "220", "9.0.0", "/Templates/assets/swf/expressInstall.swf");
    //swfobject.embedSWF("/Templates/assets/swf/sample.swf", "genericflash_fullwidth", "940", "220", "9.0.0", "/Templates/assets/swf/expressInstall.swf");
    swfobject.embedSWF("/Templates/assets/swf/NationalFriendlyHome.swf", "homepageflash", "940", "324", "9.0.0", "/Templates/assets/swf/expressInstall.swf");

    //pre-loader spinner img for slow flash loading browsers
    if ($("DIV#homepageflash").size() > 0) {
        $('DIV.content').css({ "background-image": "url(/Templates/assets/img/bg/loader.gif)", "background-position": "center 142px", "background-repeat": "no-repeat" });
        setTimeout("$('DIV.content').css({'background':'#ffffff'});", 30000);
    }


    $("SPAN.printpage").click(function(e) {
        window.print();
        e.preventDefault();
    });
    //form validation
    if ($("DIV.hc_step5,DIV.tesp_step4").size() > 0) {
        jQuery.validator.messages.required = "";
        $("div.validationerrors").hide();
        $("FORM#aspnetForm").validate({
            invalidHandler: function(e, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    var message = errors == 1
							? 'You missed 1 field. It has been highlighted below'
							: 'You missed ' + errors + ' fields.  They have been highlighted below';
                    $("div.validationerrors UL LI").html(message);
                    $("div.validationerrors").show();
                    $('html, body').animate({ scrollTop: 0 }, 'fast');
                } else {
                    $("div.validationerrors").hide();
                }
            }
        }
		);

        $("FORM#aspnetForm").submit(function() {
            var submitOk = true;
            var errors = 0;
            //GP checkboxes
            $("UL.gpvalidation").each(function(e) {
                if ($(this).is(":visible")) {
                    if ($(this).children("LI").children("INPUT").is(':checked')) {
                    }
                    else {
                        errors++;
                        $(this).css({ "border-width": "1px", "border-color": "red", "border-style": "solid", "float": "left", "margin-bottom": "10px" });
                        submitOk = false;
                    }
                }
            });

            $("INPUT.valreq").each(function(e) {
                if ($(this).hasClass('error'))
                    $(this).removeClass('error');

                if ($(this).is(":visible")) {
                    if (!$(this).val().length) {
                        //errors++;
                        submitOk = false;
                        $(this).addClass('error');
                    }
                }
            });

            if (!submitOk) {
                errors += $('FORM INPUT.error').length + $('FORM TEXTAREA.error').length + $('FORM SELECT.error').length;

                var message = errors == 1
					? 'You missed 1 field. It has been highlighted below'
					: 'You missed ' + errors + ' fields.  They have been highlighted below';
                $("div.validationerrors UL LI").html(message);
                $("div.validationerrors").show();
                $('html, body').animate({ scrollTop: 0 }, 'fast');
            }
            return submitOk;

        });



    }
    //50+ application premium calculations
    if ($("DIV.fiftyplus").size() > 0) {
        $("DIV.premiumcalc_fp").each(function(i) {
            var minValue = $(this).children("SELECT").children("OPTION").eq(0).val();
            var totSteps = $(this).children("SELECT").children("OPTION").length;
            var maxValue = $(this).children("SELECT").children("OPTION").eq(totSteps - 1).val();
            var currentVal = $(this).children("SELECT").children("OPTION").index($(this).children("SELECT").children("OPTION:selected"));
            var initialVal = $(this).children("SELECT").children("OPTION").eq(currentVal).val();
            var defaultsumassured = fiftyPlus[applicants['applicant' + i].smoker][applicants['applicant' + i].age][initialVal];

            //hide select elem & create slider
            $("DIV.fiftyplus SELECT").hide();
            //append HTML for sliders
            $(this).children("A.help").slice(0, 1).after('<div class="slidercontainer"><div class="slider"></div><p class="minval">&pound;' + minValue + '</p><p class="maxval">&pound;' + maxValue + '</p>');
            //append HTML to show slider value
            $(this).children("LABEL").slice(0, 1).after('<span class="monthlypremium">&pound;' + $(this).children("SELECT").children("OPTION").eq(currentVal).val() + '</span>');
            //append HTML for total Lump sum & hidden field
            $(this).children("DIV.slidercontainer").after('<p class="sumassured">Lump sum: <span>&pound;' + defaultsumassured + '</span></p>');
            $(this).children("DIV.nominate").before('<input name="app' + (i + 1) + '_lumpsum" id="app' + (i + 1) + '_lumpsum" type="hidden" class="sumassured" value="' + defaultsumassured + '" \/>');

            //disable nomination amount field if chkbx not selected
            ($(this).children("DIV.nominate").children("INPUT.chk").is(":checked")) ? $(this).children("DIV.nominate").children("P").children("INPUT.amount").removeAttr("disabled") : $(this).children("DIV.nominate").children("P").children("INPUT.amount").attr("disabled", "disabled");

            $(this).children("DIV.nominate").children("INPUT.chk").change(function() {
                var checked = $(this).siblings("P").children("INPUT.amount").attr("disabled");
                (checked == true) ? $(this).siblings("P").children("INPUT.amount").removeAttr("disabled").focus().val('') : $(this).siblings("P").children("INPUT.amount").attr("disabled", "disabled").val('0');
            });


            if ($.browser.mozilla) {
                $("DIV.content DIV.main DIV.fiftyplus FIELDSET LEGEND SPAN").css({ "top": "-10px", "left": "0px" });
            }

            $(".slider").slider({
                value: currentVal + 1,
                min: 1,
                max: totSteps,
                step: 1,
                slide: function(event, ui) {
                    var sliderIndex = $('DIV.slider').index($(this));
                    //select the matching slider option in the dropdown
                    $(this).parent().siblings("SELECT").children("OPTION").eq((ui.value - 1)).attr("selected", "selected");
                    $(this).parent().siblings("SPAN.monthlypremium").html("&pound;" + $(this).parent().siblings("SELECT").val());
                    var premium = parseInt($(this).parent().siblings("SELECT").val());
                    var sumassured = fiftyPlus[applicants['applicant' + sliderIndex].smoker][applicants['applicant' + sliderIndex].age][premium];
                    $(this).parents("DIV.premiumcalc_fp").children("P.sumassured").children("SPAN").html("&pound;" + sumassured);
                    $(this).parents("DIV.premiumcalc_fp").children("INPUT.sumassured").val(sumassured);
                },
                change: function(event, ui) {
                    var sliderIndex = $('DIV.slider').index($(this));
                    $(this).parent().siblings("SELECT").children("OPTION").eq((ui.value - 1)).attr("selected", "selected");
                    //the monthly premium selected in the slider
                    var premium = parseInt($(this).parent().siblings("SELECT").val());
                    var sumassured = fiftyPlus[applicants['applicant' + sliderIndex].smoker][applicants['applicant' + sliderIndex].age][premium];
                    $(this).parents("DIV.premiumcalc_fp").children("P.sumassured").children("SPAN").html("&pound;" + sumassured);
                    $(this).parents("DIV.premiumcalc_fp").children("INPUT.sumassured").val(sumassured);
                }
            });
        });
    }
    //fifty plus bank details page
    if ($("DIV.secondaryaccount").size() > 0) {
        $("DIV.secondaryaccount").hide();
        if ($("INPUT.both:first").is(":checked")) {
            $("DIV.secondaryaccount").hide();
            $("DIV.instance1").hide();
        }
        else {
            $("DIV.secondaryaccount").show();
            $("DIV.instance1").show();
            if ($.browser.msie && $.browser.version.substr(0, 1) < 8) {
                $("DIV.instance1").css({ "top": "636px" });
            }
            else {
                $("DIV.instance1").css({ "top": "600px" });
            }
        }
        $("INPUT.both").click(function() {
            if ($(this).attr("class") == "both default") {
                $("DIV.secondaryaccount").hide();
                $("DIV.instance1").hide();
            }
            else {
                $("DIV.secondaryaccount").show();
                $("DIV.instance1").show();
                if ($.browser.msie && $.browser.version.substr(0, 1) < 8) {
                    ($("DIV.instance0").prev("FIELDSET").children("P.bankaddress").is(":visible")) ? $("DIV.instance1").css({ "top": "736px" }) : $("DIV.instance1").css({ "top": "624px" });
                }
                else {
                    ($("DIV.instance0").prev("FIELDSET").children("P.bankaddress").is(":visible")) ? $("DIV.instance1").css({ "top": "700px" }) : $("DIV.instance1").css({ "top": "600px" });
                }
            }
        });
    }

    //healthcare step 2
    if ($("INPUT.childpolicy").size() > 0) {
        if ($("INPUT.childpolicy").is(':checked')) {
            $("P.hc_numchild").show();
        }
        else {
            $("P.hc_numchild").hide();
        }
        $("INPUT.childpolicy").click(function() {
            $("P.hc_numchild").toggle();
        });
    }
    //healthcare step 3
    if ($("DIV.autocomplete").size() > 0) {
        $.preloadImages("/Templates/assets/img/spinner-small.gif");

        $('.invalid').dialog({
            bgiframe: true,
            modal: true,
            autoOpen: false,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                    //$("INPUT.email1").val("");
                    $("INPUT.email1").focus();
                }
            }
        });
        $('.nomatch').dialog({
            bgiframe: true,
            modal: true,
            autoOpen: false,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                    $("INPUT.email1").focus();
                    //$("INPUT.email1,INPUT.email2").val("");
                    $("SELECT.title").show();
                }
            }
        });
        $("DIV.autocomplete").hide();
        $("INPUT.email1").focus();
        $("INPUT.email1").blur(function() {
            var isValid = validateEmail($(this).val()); if (!isValid) { $(".invalid").dialog("open"); }
        });
        $("INPUT.email2").blur(function() {
            var email1 = jQuery.trim($("INPUT.email1").val());
            var email2 = jQuery.trim($("INPUT.email2").val());
            if (email1 == email2) {
                $("INPUT.email2").after("<img src='/Templates/assets/img/spinner-small.gif' alt='Validating email' class='spinnerSmall' />");
                $.ajax({
                    url: "/handlers/EmailValidator.ashx",
                    data: { "email": email1 },
                    async: true,
                    dataType: "json",
                    success: function(json) {
                        if (!json.hasError && json.emailIsInUse) {
                            $("DIV.autocomplete").show();
                            $("DIV.autocomplete INPUT.textField").focus();
                            repositionButtons(0);
                        }
                    }
                });
                $("SELECT.title").unbind("click");
                $(".spinnerSmall").remove();
            }
            else {
                $("SELECT.title").click(function() {
                    $(this).hide();
                });
                $(".nomatch").dialog("open");
                $("DIV.autocomplete").hide();
                repositionButtons(0);
            }
        });
        //kill focus if back or save btns are clicked
        $("SPAN.killfocus INPUT").click(function() {
            $(".invalid").dialog("destroy");
            $("INPUT.email,INPUT.email2").unbind("blur");
        });
    }


    //healthcare application premium calculations
    if ($("DIV.premiumcalc").size() > 0) {
        var overallPremium = 0;
        $("DIV.content DIV.main DIV.application DIV.summary DIV.premiumcalc").css({ "background-image": "url(/Templates/assets/img/bg/premiumcalc.gif)" });
        //sliders
        //hide select elem
        $("DIV.premiumcalc SELECT").hide();

        $("DIV.premiumcalc").css({ "padding-bottom": "85px" });
        var counter = 0;
        $("DIV.premiumcalc").each(function() {
            counter++;
            var minValue = $(this).children("SELECT").children("OPTION").eq(0).val();
            var currentVal = $(this).children("SELECT").children("OPTION:selected").val();
            var totSteps = $(this).children("SELECT").children("OPTION").length;

            //initial values
            var topupval = $(this).children("DIV.rbGroup").children("FIELDSET").children("UL").children("LI").children("INPUT").index($(this).children("DIV.rbGroup").children("FIELDSET").children("UL").children("LI").children("INPUT:checked"));
            var topup; //used for graph
            var topupPremium;
            if (topupval == 0) {
                topup = 30;
                topupPremium = 10;
            }
            else if (topupval == 1) {
                topup = 45;
                topupPremium = 15;
            }
            else {
                topup = 60;
                topupPremium = 20;
            }

            //Optional extra payment val
            var extraPayment = $(this).children("P").children("INPUT").val();
            if (isNaN(extraPayment) || extraPayment == "") {
                extraPayment = 0;
                $(this).parents("DIV.premiumcalc").children("P").children("INPUT").val(0);
            }
            extraPayment = parseInt(extraPayment);

            var credit = currentVal + extraPayment;


            var totalPremium = parseInt(currentVal) + topupPremium + extraPayment;
            /*
            var dentOptiCvr = 0;			
            var dentOptiCvrVals = new Array;
            dentOptiCvrVals[10] = 150;
            dentOptiCvrVals[20] = 300;
            dentOptiCvrVals[30] = 450;
            dentOptiCvrVals[40] = 600;
            dentOptiCvrVals[50] = 750;
            dentOptiCvrVals[60] = 900;
            dentOptiCvrVals[70] = 1050;
            dentOptiCvrVals[80] = 1200;
            dentOptiCvrVals[90] = 1350;
            dentOptiCvrVals[100] = 1500;
            dentOptiCvrVals[110] = 1650;			
            dentOptiCvrVals[120] = 1800;
            dentOptiCvrVals[130] = 1950;
            dentOptiCvrVals[140] = 2100;
            dentOptiCvrVals[150] = 2250;
            dentOptiCvrVals[160] = 2400;
            dentOptiCvrVals[170] = 2550;
            dentOptiCvrVals[180] = 2700;
            dentOptiCvrVals[190] = 2850;
            dentOptiCvrVals[200] = 3000;
			
			dentOptiCvr = dentOptiCvrVals[currentVal];
            */
            overallPremium = overallPremium + totalPremium;

            //append HTML for sliders
            $(this).children("A.help").slice(0, 1).after('<div class="slidercontainer"><div class="slider"></div><p class="minval">&pound;' + minValue + '</p><p class="maxval">&pound;200</p></div>');
            //append HTML to show slider value
            $(this).children("LABEL").slice(0, 1).after('<span class="monthlypremium">&pound;' + currentVal + '</span>');
            //Append HTML to show graph and calculated values
            $(this).after('<div class="benefitscalc">' +
									'<h3>Amount you can claim</h3>' +
									'<div class="legend"><p class="key1">Using your top-up allowance</p><p class="key2">Using your deposit account</p></div><br class="cb" />' +
									'<div class="graph" id="graph' + counter + '">' +
									'</div>' +
									'<P class="after10">After year 10 you will have the opportunity to renew your top-up allowance. <a href="#" class="help tooltip" title="<strong>What happens after year 10?</strong><br />After 10 years, we will offer you the chance to extend your top-up cover for a further 10 years. But the premiums and level of cover applicable at that date may be different from those currently available."><img src="/Templates/assets/img/icon/help.gif" alt="Help" /></a></p>' +
									'<p class="depacc"><span>Deposit account monthly credit:</span><strong>&pound;' + RoundFixed((currentVal * 0.25) + extraPayment, 2) + '</strong></p>' +
									'<p class="depbal"><span>Deposit balance at end of year 10:</span><strong>&pound;' + ((currentVal * 0.25) + extraPayment) * 120 + '</strong></p>' +
								'</div>'); //'<p class="dentopti"><span>Dental and optical cover:</span><strong>&pound;'+dentOptiCvr+'</strong></p><br class="cb" />'+

            var matchHeights = parseInt($(this).height()) + 70;
            if ($.browser.msie) {
                if ($.browser.version.substr(0, 1) < 7) {
                    $(this).siblings("DIV.benefitscalc").css({ "height": (matchHeights - 18) + "px" });
                }
                else {
                    $(this).siblings("DIV.benefitscalc").css({ "min-height": (matchHeights - 19) + "px" });
                }
            }
            else {
                if (counter > 1) { matchHeights = matchHeights + 30; }
                $(this).siblings("DIV.benefitscalc").css({ "min-height": matchHeights + "px" });
            }

            //draw graph
            line1 = [[0, topup], [1, topup], [2, topup], [3, topup], [4, topup], [5, topup], [6, topup], [7, topup], [8, topup], [9, topup], [10, topup], [10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0]];

            //calculate line2 values
            //check age to establish factor
            var factor;
            if (minValue > 60) {
                factor = 4;
            }
            else {
                factor = 10;
            }
            //Check premium to establish claim ceiling
            var claimCeiling = 0;
            var claimCeilingVals = new Array;
            claimCeilingVals[10] = 5000;
            claimCeilingVals[20] = 10000;
            claimCeilingVals[30] = 15000;
            claimCeilingVals[40] = 20000;
            claimCeilingVals[50] = 25000;
            claimCeilingVals[60] = 30000;
            claimCeilingVals[70] = 35000;
            claimCeilingVals[80] = 40000;
            claimCeilingVals[90] = 45000;
            claimCeilingVals[100] = 50000;
            claimCeilingVals[110] = 55000;
            claimCeilingVals[120] = 60000;
            claimCeilingVals[130] = 65000;
            claimCeilingVals[140] = 70000;
            claimCeilingVals[150] = 75000;
            claimCeilingVals[160] = 80000;
            claimCeilingVals[170] = 85000;
            claimCeilingVals[180] = 90000;
            claimCeilingVals[190] = 95000;
            claimCeilingVals[200] = 100000;

            claimCeiling = claimCeilingVals[currentVal];

            //loop through points and calculate values			
            line2 = [[0, 0]];
            var months = 0;
            var pointVal;
            for (i = 1; i < 16; i++) {
                months = months + 12;
                if (factor == 4) {
                    pointVal = (((currentVal * 0.25) + extraPayment) * months) / 250;
                }
                else {
                    pointVal = (((currentVal * 0.25) + extraPayment) * months) / 100;
                }
                if (pointVal > claimCeiling / 1000) {
                    pointVal = claimCeiling / 1000;
                }
                if (i < 15 && i != 10) {
                    line2.push([i, pointVal]);
                }
                else {
                    line2.push([i, pointVal]);
                    line2.push([i, pointVal]);
                }
            }

            plot1 = $.jqplot('graph' + counter, [line1, line2], {
                seriesColors: ["#006737", "#720a69"],
                stackSeries: true,
                title: 'Amount available for medical claims',
                seriesDefaults: { fill: true, showMarker: false },
                series: [
				{ label: 'Top up allowance' },
				{ label: 'Deposit account ' }
			  ],
                axes: {
                    xaxis: {
                        ticks: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                        tickOptions: { formatString: '%d' }
                    },
                    yaxis: {
                        min: 0,
                        numberTicks: 5,
                        tickOptions: { formatString: '&pound;%.0fk' }
                    }
                },
                grid: {
                    background: '#fff'
                }
            });
            //style tweaks for graph
            $("DIV.jqplot-title").css({ "font-family": "Arial,sans-serif", "font-weight": "bold" });

            //Append HTML to show premium total
            $(this).append('<p class="totprem">Total premium <span>&pound;' + totalPremium + '</span></p>');

            $(".slider").slider({
                value: (currentVal - (minValue - 10)) / 10,
                min: 1,
                max: totSteps,
                animate: true,
                step: 1,
                slide: function(event, ui) {

                    //select the matching slider option in the dropdown
                    $(this).parent().siblings("SELECT").children("OPTION").eq((ui.value - 1)).attr("selected", "selected");
                    $(this).parent().siblings("SPAN.monthlypremium").html("&pound;" + $(this).parent().siblings("SELECT").val());
                },
                change: function(event, ui) {
                    $("DIV.totpremium").stop().animate({ "marginTop": (($(this).offset().top) - 400) + "px" }, "slow");
                    $(this).parent().siblings("SELECT").children("OPTION").eq((ui.value - 1)).attr("selected", "selected");
                    //the monthly premium selected in the slider
                    var minValue = parseInt($(this).parent().siblings("SELECT").val());
                    //topup val 
                    var topupval = $(this).parents("DIV.premiumcalc").children("DIV.rbGroup").children("FIELDSET").children("UL").children("LI").children("INPUT").index($(this).parents("DIV.premiumcalc").children("DIV.rbGroup").children("FIELDSET").children("UL").children("LI").children("INPUT:checked"));
                    var topup; //used for graph
                    var topupPremium;
                    if (topupval == 0) {
                        topup = 30;
                        topupPremium = 10;
                    }
                    else if (topupval == 1) {
                        topup = 45;
                        topupPremium = 15;
                    }
                    else {
                        topup = 60;
                        topupPremium = 20;
                    }
                    //Optional extra payment val
                    var extraPayment = $(this).parents("DIV.premiumcalc").children("P").children("INPUT").val();
                    if (isNaN(extraPayment) || extraPayment == "") {
                        extraPayment = 0;
                        $(this).parents("DIV.premiumcalc").children("P").children("INPUT").val(0);
                    }
                    extraPayment = parseInt(extraPayment);
                    var credit = minValue + extraPayment;
                    var graphid = $(this).parents("DIV.premiumcalc").siblings("DIV.benefitscalc").children("DIV.graph").attr("id");

                    //redraw graph
                    line1 = [[0, topup], [1, topup], [2, topup], [3, topup], [4, topup], [5, topup], [6, topup], [7, topup], [8, topup], [9, topup], [10, topup], [10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0]];
                    //calculate line2 values
                    //check age to establish factor
                    var factor;
                    if ($(this).parents("DIV.premiumcalc").children("SELECT").children("OPTION").eq(0).val() > 60) {
                        factor = 4;
                    }
                    else {
                        factor = 10;
                    }
                    //Check premium to establish claim ceiling
                    var claimCeiling = 0;
                    var claimCeilingVals = new Array;
                    claimCeilingVals[10] = 5000;
                    claimCeilingVals[20] = 10000;
                    claimCeilingVals[30] = 15000;
                    claimCeilingVals[40] = 20000;
                    claimCeilingVals[50] = 25000;
                    claimCeilingVals[60] = 30000;
                    claimCeilingVals[70] = 35000;
                    claimCeilingVals[80] = 40000;
                    claimCeilingVals[90] = 45000;
                    claimCeilingVals[100] = 50000;
                    claimCeilingVals[110] = 55000;
                    claimCeilingVals[120] = 60000;
                    claimCeilingVals[130] = 65000;
                    claimCeilingVals[140] = 70000;
                    claimCeilingVals[150] = 75000;
                    claimCeilingVals[160] = 80000;
                    claimCeilingVals[170] = 85000;
                    claimCeilingVals[180] = 90000;
                    claimCeilingVals[190] = 95000;
                    claimCeilingVals[200] = 100000;
                    claimCeiling = claimCeilingVals[minValue];

                    //loop through points and calculate values					
                    line2 = [[0, 0]];
                    var months = 0;
                    var pointVal;
                    for (i = 1; i < 16; i++) {
                        months = months + 12;
                        if (factor == 4) {
                            pointVal = (((minValue * 0.25) + extraPayment) * months) / 250;
                        }
                        else {
                            pointVal = (((minValue * 0.25) + extraPayment) * months) / 100;
                        }
                        if (pointVal > claimCeiling / 1000) {
                            pointVal = claimCeiling / 1000;
                        }
                        if (i < 15 && i != 10) {
                            line2.push([i, pointVal]);
                        }
                        else {
                            line2.push([i, pointVal]);
                            line2.push([i, pointVal]);
                        }
                    }

                    plot1 = $.jqplot(graphid, [line1, line2], {
                        seriesColors: ["#006737", "#720a69"],
                        stackSeries: true,
                        title: 'Amount available for medical claims',
                        seriesDefaults: { fill: true, showMarker: false },
                        series: [
						{ label: 'Top up allowance' },
						{ label: 'Deposit account ' }
					  ],
                        axes: {
                            xaxis: {
                                ticks: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                                tickOptions: { formatString: '%d' }
                            },
                            yaxis: {
                                min: 0,
                                numberTicks: 5,
                                tickOptions: { formatString: '&pound;%.0fk' }
                            }
                        },
                        grid: {
                            background: '#fff'
                        }
                    });
                    plot1.redraw();
                    //style tweaks for graph
                    $("DIV.jqplot-title").css({ "font-family": "Arial,sans-serif", "font-weight": "bold" });
                    //update deposit account monthly credit amount
                    $(this).parents("DIV.summary").children("DIV.benefitscalc").children("P.depacc").children("STRONG").html("&pound;" + RoundFixed((minValue * 0.25) + extraPayment, 2));
                    //update deposit balance
                    $(this).parents("DIV.summary").children("DIV.benefitscalc").children("P.depbal").children("STRONG").html("&pound;" + (((minValue * 0.25) + extraPayment) * 12) * 10);
                    //update dental/optical cover amount
                    //$(this).parents("DIV.summary").children("DIV.benefitscalc").children("P.dentopti").children("STRONG").html("&pound;"+dentOptiCvrVals[minValue]);

                    //update total premium for this applicant amount
                    $(this).parents("DIV.slidercontainer").siblings("P.totprem").children("SPAN").html("&pound;" + (credit + topupPremium));
                    //update overallPremium
                    overallPremium = 0;
                    $("P.totprem SPAN").each(function() {
                        var currentVal = $(this).text();
                        currentVal = parseInt(currentVal.substring(1));
                        overallPremium = overallPremium + currentVal;
                    });
                    $("DIV.sidebar DIV.totpremium P").html("&pound;" + overallPremium + " pm");
                }
            });
        });

        $('input').not("SPAN INPUT").bind("click keyup", function() {
            $("DIV.totpremium").stop().animate({ "marginTop": (($(this).offset().top) - 400) + "px" }, "slow");
            if ($(this).val() != "") {
                //get values
                //slider premium value
                var minValue = parseInt($(this).parents("DIV.premiumcalc").children("SELECT").val());
                //topup & topup premium
                var topupval = $(this).parents("DIV.premiumcalc").children("DIV.rbGroup").children("FIELDSET").children("UL").children("LI").children("INPUT").index($(this).parents("DIV.premiumcalc").children("DIV.rbGroup").children("FIELDSET").children("UL").children("LI").children("INPUT:checked"));
                var topup; //used for graph
                var topupPremium;
                if (topupval == 0) {
                    topup = 30;
                    topupPremium = 10;
                }
                else if (topupval == 1) {
                    topup = 45;
                    topupPremium = 15;
                }
                else {
                    topup = 60;
                    topupPremium = 20;
                }
                //extra payment
                var extraPayment = $(this).parents("DIV.premiumcalc").children("P.extrapayment").children("INPUT").val();
                if (isNaN(extraPayment)) {
                    extraPayment = 0;
                    $('.NaN').dialog('open');
                    $(this).parents("DIV.premiumcalc").children("P.extrapayment").children("INPUT").val(0);
                }
                extraPayment = parseInt(extraPayment);
                if (extraPayment < 0) {
                    extraPayment = 0;
                    $('.NaN').dialog('open');
                    $(this).parents("DIV.premiumcalc").children("P..extrapayment").children("INPUT").val(0);
                }

                var credit = minValue + extraPayment;
                var graphid = $(this).parents("DIV.premiumcalc").siblings("DIV.benefitscalc").children("DIV.graph").attr("id");
                //redraw graph
                line1 = [[0, topup], [1, topup], [2, topup], [3, topup], [4, topup], [5, topup], [6, topup], [7, topup], [8, topup], [9, topup], [10, topup], [10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0]];
                //calculate line2 values
                //check age to establish factor
                var factor;
                if ($(this).parents("DIV.premiumcalc").children("SELECT").children("OPTION").eq(0).val() > 60) {
                    factor = 4;
                }
                else {
                    factor = 10;
                }
                //Check premium to establish claim ceiling
                var claimCeiling = 0;
                var claimCeilingVals = new Array;
                claimCeilingVals[10] = 5000;
                claimCeilingVals[20] = 10000;
                claimCeilingVals[30] = 15000;
                claimCeilingVals[40] = 20000;
                claimCeilingVals[50] = 25000;
                claimCeilingVals[60] = 30000;
                claimCeilingVals[70] = 35000;
                claimCeilingVals[80] = 40000;
                claimCeilingVals[90] = 45000;
                claimCeilingVals[100] = 50000;
                claimCeilingVals[110] = 55000;
                claimCeilingVals[120] = 60000;
                claimCeilingVals[130] = 65000;
                claimCeilingVals[140] = 70000;
                claimCeilingVals[150] = 75000;
                claimCeilingVals[160] = 80000;
                claimCeilingVals[170] = 85000;
                claimCeilingVals[180] = 90000;
                claimCeilingVals[190] = 95000;
                claimCeilingVals[200] = 100000;
                claimCeiling = claimCeilingVals[minValue];

                //loop through points and calculate values			
                line2 = [[0, 0]];
                var months = 0;
                var pointVal;
                for (i = 1; i < 16; i++) {
                    months = months + 12;
                    if (factor == 4) {
                        pointVal = (((minValue * 0.25) + extraPayment) * months) / 250;
                    }
                    else {
                        pointVal = (((minValue * 0.25) + extraPayment) * months) / 100;
                    }
                    if (pointVal > claimCeiling / 1000) {
                        pointVal = claimCeiling / 1000;
                    }
                    if (i < 15 && i != 10) {
                        line2.push([i, pointVal]);
                    }
                    else {
                        line2.push([i, pointVal]);
                        line2.push([i, pointVal]);
                    }
                }
                plot1 = $.jqplot(graphid, [line1, line2], {
                    seriesColors: ["#006737", "#720a69"],
                    stackSeries: true,
                    title: 'Amount available for medical claims',
                    seriesDefaults: { fill: true, showMarker: false },
                    series: [
				{ label: 'Top up allowance' },
				{ label: 'Deposit account ' }
			  ],
                    axes: {
                        xaxis: {
                            ticks: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                            tickOptions: { formatString: '%d' }
                        },
                        yaxis: {
                            min: 0,
                            numberTicks: 5,
                            tickOptions: { formatString: '&pound;%.0fk' }
                        }
                    },
                    grid: {
                        background: '#fff'
                    }
                });
                plot1.redraw();
                //style tweaks for graph
                $("DIV.jqplot-title").css({ "font-family": "Arial,sans-serif", "font-weight": "bold" });
                //update deposit account monthly credit amount
                $(this).parents("DIV.summary").children("DIV.benefitscalc").children("P.depacc").children("STRONG").html("&pound;" + RoundFixed(((minValue * 0.25) + extraPayment), 2));
                //update deposit balance
                $(this).parents("DIV.summary").children("DIV.benefitscalc").children("P.depbal").children("STRONG").html("&pound;" + (((minValue * 0.25) + extraPayment) * 12) * 10);
                /*update dental/optical cover amount
                var dentOptiCvr = 0;			
                var dentOptiCvrVals = new Array;
                dentOptiCvrVals[10] = 150;
                dentOptiCvrVals[20] = 300;
                dentOptiCvrVals[30] = 450;
                dentOptiCvrVals[40] = 600;
                dentOptiCvrVals[50] = 750;
                dentOptiCvrVals[60] = 900;
                dentOptiCvrVals[70] = 1050;
                dentOptiCvrVals[80] = 1200;
                dentOptiCvrVals[90] = 1350;
                dentOptiCvrVals[100] = 1500;
                dentOptiCvrVals[110] = 1650;			
                dentOptiCvrVals[120] = 1800;
                dentOptiCvrVals[130] = 1950;
                dentOptiCvrVals[140] = 2100;
                dentOptiCvrVals[150] = 2250;
                dentOptiCvrVals[160] = 2400;
                dentOptiCvrVals[170] = 2550;
                dentOptiCvrVals[180] = 2700;
                dentOptiCvrVals[190] = 2850;
                dentOptiCvrVals[200] = 3000;
                $(this).parents("DIV.summary").children("DIV.benefitscalc").children("P.dentopti").children("STRONG").html("&pound;"+dentOptiCvrVals[minValue]);
                */
                //update total premium for this applicant amount
                $(this).parents("DIV.premiumcalc").children("P.totprem").children("SPAN").html("&pound;" + (minValue + topupPremium + extraPayment));

                //update overallPremium
                overallPremium = 0;
                $("P.totprem SPAN").each(function() {
                    var currentVal = $(this).text();
                    currentVal = parseInt(currentVal.substring(1));
                    overallPremium = overallPremium + currentVal;
                });
                $("DIV.sidebar DIV.totpremium P").html("&pound;" + overallPremium + " pm");
            }
        });
        //create total monthly premium div
        $("DIV.sidebar").append('<div class="genericheaderbox green totpremium"><img class="arrow" src="/Templates/assets/img/content/arrowhead_green.gif" alt="" /><h3>Total monthly premium</h3><div class="hr"><hr /></div><p>&pound;' + overallPremium + ' pm</p>			</div>');

        //Total premiums scrolling box
        $(window).scroll(function() {
            $("DIV.totpremium").stop().animate({ "marginTop": ($(window).scrollTop()) + "px" }, "slow");
        });

        $("P.extrapayment INPUT").blur(function() {
            if ($(this).val() == "") { $(this).val(0); }
        });
        $(".app2_NaN,.app3_NaN").hide();

        if ($.browser.mozilla) {
            $("DIV.content DIV.main DIV.application.hc_calc FIELDSET LEGEND SPAN").css({ "top": "-10px", "left": "0px" });
        }

    }
    //show addinfo for medical questions
    if ($("DIV.addinfo").size() > 0) {
        $("DIV.addinfo").hide();
        $("DIV.gpreport").hide();
        $("DIV.fmu").hide();
        //show selected on page refresh
        checkSelected(); //see function above the opening line of the doc ready function
        $("DIV.medicinfo UL LI INPUT.y").click(function() {
            //append required to all fields			
            var startindex = parseInt($(this).parent("LI").parent("UL").parent("FIELDSET").children().index($(this).parent("LI").parent("UL")));
            var endIndex = parseInt($(this).parent("LI").parent("UL").parent("FIELDSET").children().index($(this).parent("LI").parent("UL").nextAll("UL")));
            if (endIndex != "-1") {
                var i;
                for (i = (startindex + 1); i <= endIndex - 2; i++) {
                    $(this).parent("LI").parent("UL").parent("FIELDSET").children(":eq(" + i + ")").show();
                    $(this).parent("LI").parent("UL").parent("FIELDSET").children(":eq(" + i + ")").children("FIELDSET").children("P").children("INPUT, TEXTAREA").addClass("required");
                }

            }
            else {
                $(this).parents("ul").nextAll("DIV.addinfo").show();
                $(this).parent("LI").parent("UL").nextAll("DIV.addinfo").children("FIELDSET").children("P").children("INPUT, TEXTAREA").addClass("required");
            }
            var itemIndex = $(this).parents('DIV.application').children('FIELDSET').index($(this).parents("DIV.medicinfo").parents("FIELDSET"));
            checkSelected();
        });
        $("DIV.medicinfo UL LI INPUT.n").click(function() {
            var startindex = parseInt($(this).parent("LI").parent("UL").parent("FIELDSET").children().index($(this).parent("LI").parent("UL")));
            var endIndex = parseInt($(this).parent("LI").parent("UL").parent("FIELDSET").children().index($(this).parent("LI").parent("UL").nextAll("UL")));
            if (endIndex != "-1") {
                var i;
                for (i = (startindex + 1); i <= endIndex - 2; i++) {
                    $(this).parent("LI").parent("UL").parent("FIELDSET").children(":eq(" + i + ")").hide();
                    $(this).parent("LI").parent("UL").parent("FIELDSET").children(":eq(" + i + ")").children("FIELDSET").children("P").children("INPUT, TEXTAREA").removeClass("required error valid");
                }

            }
            else {
                $(this).parents("ul").nextAll("DIV.addinfo").hide();
                $(this).parent("LI").parent("UL").nextAll("DIV.addinfo").children("FIELDSET").children("P").children("INPUT, TEXTAREA").removeClass("required error valid");
            }

            var itemIndex = $(this).parents('DIV.application').children('FIELDSET').index($(this).parents("DIV.medicinfo").parents("FIELDSET"));
            $("DIV.application DIV.gpreport:eq(" + itemIndex + ")").hide();
            $("DIV.application DIV.gpreport:eq(" + itemIndex + ")").children("FIELDSET").children("P").children("INPUT, TEXTAREA").removeClass("required error valid");
            checkSelected();
        });

        $("DIV.medicinfo UL LI INPUT.mq").click(function() {
            var itemIndex = $(this).parents('DIV.application').children('FIELDSET').index($(this).parents("DIV.medicinfo").parents("FIELDSET"));
            $(this).parents("DIV.uroute").siblings("DIV.fmu").show();
            checkSelected();
        });
        $("DIV.medicinfo UL LI INPUT.nmq").click(function() {
            var itemIndex = $(this).parents('DIV.application').children('FIELDSET').index($(this).parents("DIV.medicinfo").parents("FIELDSET"));
            $(this).parents("DIV.uroute").siblings("DIV.fmu").hide();
            $("DIV.application DIV.gpreport:eq(" + itemIndex + ")").hide();
            $("DIV.application DIV.gpreport:eq(" + itemIndex + ")").children("FIELDSET").children("P").children("INPUT").removeClass("required error valid");
            checkSelected();
        });

        $("DIV.addinfo A.addapplicant").live("click", function(e) {
            var btnTxt = "Remove this Applicant/Condition";

            //Change btn text for Tax free savings step 4
            var checkApp = $(this).parents("DIV.addinfo").children("FIELDSET").attr("class").indexOf("tfsinfo");
            if (checkApp != -1) {
                btnTxt = "Remove this condition";
            }
            var newDiv = $(this).parents("DIV.addinfo").html();
            var identifier = $(this).parents("DIV.addinfo").children("FIELDSET").children("P:eq(0)").children("LABEL").attr("for");

            identifier = identifier.match(/app([\d]+)/);
            var stringID = new RegExp(identifier[0], "g");
            newDiv = newDiv.replace(stringID, "app" + (parseInt(identifier[1]) + 1));
            //ensure datepicker initialiser is not cloned (class of hasDatePicker appended on init)
            newDiv = newDiv.replace(/ hasDatepicker/g, "");

            newDiv = newDiv.replace(/(<input[\s\S]*?value=)[^"]*?( name)/gi, "$1\"\"$2");

            //newDiv = newDiv.replace(/(<textarea class="medicalinfo" rows="" cols="" name="s_app[\d]{4}_q1_[a-z]+" id="s_app[\d]{4}_q1_[a-z]+">)[^<]*(<\/textarea>)/gi,"$1\"\"$2");
            newDiv = newDiv.replace(/(<textarea[\s\S]*?>)[^<]*(<\/textarea>)/gi, "$1$2");

            $(this).parents("DIV.addinfo").after("<div class='addinfo'>" + newDiv + "</div>");
            $(this).parents("SPAN").html('<a href="#" class="removeapplicant">' + btnTxt + '</a>');
            e.preventDefault();
        });
        $("DIV.addinfo A.removeapplicant").live("click", function(e) {
            var newDiv = $(this).parents("DIV.addinfo").remove();
            e.preventDefault();
        });

        $("DIV.gpdetails A.addgp").live("click", function(e) {
            var newDiv = $(this).parents("DIV.gpdetails").html();

            var identifier = $(this).parents("DIV.gpdetails").children("P:eq(0)").children("LABEL").attr("for");
            identifier = identifier.match(/app([\d]{1,2})/);
            var stringID = new RegExp(identifier[0], "g");
            newDiv = newDiv.replace(stringID, "app" + (parseInt(identifier[1]) + 1));

            $(this).parents("DIV.gpdetails").after("<div class='gpdetails'>" + newDiv + "</div>");
            $(this).parents("SPAN").html('<a href="#" class="removgp">Remove this GP</a>');
            e.preventDefault();
        });
        $("DIV.gpdetails A.removgp").live("click", function(e) {
            var newDiv = $(this).parents("DIV.gpdetails").remove();
            e.preventDefault();
        });
    }

    //ISA step 3 Transfer
    if ($("DIV.transfer").size() > 0) {
        $("INPUT.default, DIV.transfer INPUT.fullamount").attr("checked", "checked");
        $("DIV.transfer INPUT.transferamount").val('');
        $("DIV.transfer INPUT.transferamount").attr("disabled", "disabled")


        if ($("INPUT.taxyear:first").is(":checked")) {
            $("DIV.transfer").hide();
        }
        else {
            $("DIV.transfer").show();
        }

        $("INPUT.taxyear").click(function() {
            if ($(this).attr("class") == "taxyear default") {
                $("DIV.transfer").hide();
                $("INPUT.calendar_trns").parents("P:first").show();
                repositionButtons(0);
            }
            else {
                $("DIV.transfer").show();
                $("INPUT.calendar_trns").parents("P:first").hide();
                repositionButtons(0);
            }
        });
        $("DIV.transfer INPUT.fullamount").click(function() {
            var checked = $("DIV.transfer INPUT.transferamount").attr("disabled");
            (checked == true) ? $("DIV.transfer INPUT.transferamount").removeAttr("disabled").focus() : $("DIV.transfer INPUT.transferamount").attr("disabled", "disabled").val('');
        });
    }

    //ISA step 3 Create
    if ($("DIV.isa_invest").size() > 0) {
        //note: todo - THE DEBITCARD DETAILS CAPTURE SECTION HAS BEEN COMMENTED OUT IN THE createAnISA.vm FILE. 
        //The js below $("DIV.debitcard").hide(); etc has been left in for now incase NF change their minds and decide they want to capture some details here.
        $("DIV.isa_investoption").hide();
        $("P.nojs_msg").hide();
        $("DIV.debitcard").hide();

        if ($("INPUT.investmethod_dd").is(":checked")) {
            $("DIV.isa_investoption:first").show();
            $("DIV.isa_investoption:last").hide();
        }
        if ($("INPUT.investmethod_ls").is(":checked")) {
            $("DIV.isa_investoption:first").hide();
            $("DIV.isa_investoption:last").show();

            if ($("INPUT.paymethod:last").is(":checked")) {
                $("DIV.debitcard").show();
            }
            else {
                $("DIV.debitcard").hide();
            }
        }
        if ($("INPUT.investmethod_both").is(":checked")) {
            $("DIV.isa_investoption:first").show();
            $("DIV.isa_investoption:last").show();
            if ($("INPUT.paymethod:last").is(":checked")) {
                $("DIV.debitcard").show();
            }
            else {
                $("DIV.debitcard").hide();
            }
        }

        $("INPUT.investmethod_dd").click(function() {
            $("DIV.isa_investoption:first").show();
            $("DIV.isa_investoption:last").hide();
        });
        $("INPUT.investmethod_ls").click(function() {
            $("DIV.isa_investoption:first").hide();
            $("DIV.isa_investoption:last").show();
            if ($("INPUT.paymethod:last").is(":checked")) {
                $("DIV.debitcard").show();
            }
            else {
                $("DIV.debitcard").hide();
            }
        });
        $("INPUT.investmethod_both").click(function() {
            $("DIV.isa_investoption:first").show();
            $("DIV.isa_investoption:last").show();
            if ($("INPUT.paymethod:last").is(":checked")) {
                $("DIV.debitcard").show();
            }
            else {
                $("DIV.debitcard").hide();
            }
        });

        $('INPUT.paymethod').live('click', function() {
            if ($(this).attr("class") == "paymethod") {
                $("DIV.debitcard").show();
            }
            else {
                $("DIV.debitcard").hide();
            }
        });

        $('INPUT.debitdate').live('click', function() {
            var debitdate = $(this).val();
            if (debitdate == "1") {
                debitdate = 1;
            }
            else {
                debitdate = 15;
            }
            var currentday = new Date(now);
            currentday.setDate(currentday.getDate() + 18);
            var firstpaymentdate = parseInt(currentday.getDate());
            var firstpaymentmonth = parseInt(currentday.getMonth());
            var payments;
            if (firstpaymentmonth >= 4) {
                payments = 12 - (firstpaymentmonth - 4);
            }
            else {
                payments = 12 - (firstpaymentmonth + 8);
            }
            if (firstpaymentdate > 1 && debitdate == 1) {
                payments--;
            }
            if (firstpaymentdate < 15 && debitdate == 15) {
                payments--;
            }
            if (firstpaymentdate > 15 && debitdate == 15) {
                payments = payments - 2;
            }
            var total = $("INPUT.monthlyamount").val() * payments;
            if (isNaN(total)) { total = 0; }
            $("P.totalpayment STRONG").html("&pound;" + total + " (" + payments + " payments)");
        });
        /*
        $('INPUT.monthlyamount').live('keyup', function() {
        var debitdate = $('INPUT.debitdate:checked').val();
        if(debitdate == "debitdate_01"){								
        debitdate = 1;
        }
        else{
        debitdate = 15;
        }
        var currentday = new Date(now);
        currentday.setDate(currentday.getDate()+18);
        var firstpaymentdate = parseInt(currentday.getDate());
        var firstpaymentmonth = parseInt(currentday.getMonth());
        var payments;
        if(firstpaymentmonth>=4){
        payments = 12-(firstpaymentmonth-4);
        }
        else{
        payments = 12-(firstpaymentmonth+8);
        }
        if(firstpaymentdate > 1 && debitdate == 1){
        payments--;
        }
        if(firstpaymentdate < 15 && debitdate == 15){
        payments--;
        }
        if(firstpaymentdate > 15 && debitdate == 15){
        payments = payments-2;
        }
        var total = $(this).val()*payments;
        if(isNaN(total)){total = 0;}
        $("P.totalpayment STRONG").html("&pound;"+total+" ("+payments+" payments)");				 
        });
        */
        //total payments calculations		
        //backend values
        var today = settings.servertime.getDate();
        var debitdate = $('INPUT.monthlydirectdebitdate:checked').val();
        if (debitdate == 1) {
            debitdate = 1;
        }
        else {
            debitdate = 15;
        }
        var numPayments = settings.monthlyPayments;
        if ($("INPUT#currentyear").is(":checked")) {
            numPayments = settings.monthlyPayments;
            if (today > 15 && debitdate == 15 && $("DIV.isa_investoption:first").is(":visible")) {
                numPayments = numPayments - 1;
            }
        }
        else {
            numPayments = 12;
        }
        //create pod
        $("DIV.sidebar DIV.genericheaderbox").after('<div class="genericheaderbox green totpayments"><img class="arrow" src="/Templates/assets/img/content/arrowhead_green.gif" alt=""><h3>Total payments</h3><div class="hr"><hr></div><h4>Total monthly contribution:</h4><p class="monthlytot">&pound;<span>0</span></p><h4>Lump sum:</h4><p class="lump">&pound;<span>0</span></p><h4><strong>Total ISA investment:</strong></h4><p class="total" style="margin-bottom:7px;">&pound;<span>0</span></p><div class="hr"><hr></div><p class="disclaimer"><strong>Please note:</strong> This is for illustration purposes only as the amount you can invest between now and the end of the tax year is reliant on when the first payment is made.</p><div class="btmcnr"><img src="/Templates/assets/img/spacer.gif" alt=""></div></div>');

        //calculate default values
        if ($("DIV.isa_investoption:first").is(":visible")) {
            monthly = parseInt($("INPUT#monthlyamount").val());
            if (isNaN(monthly)) { monthly = 0; };
        }
        else {
            monthly = 0;
        }
        $("DIV.totpayments P.monthlytot SPAN").text(monthly * numPayments);

        if ($("DIV.isa_investoption:last").is(":visible")) {
            lumpsum = parseInt($("INPUT#lumpsum").val());
            if (isNaN(lumpsum)) { lumpsum = 0; };
        }
        else {
            lumpsum = 0;
        }
        $("DIV.totpayments P.lump SPAN").text(lumpsum);
        $("DIV.totpayments P.total SPAN").text((monthly * numPayments) + lumpsum);

        //calculate values as input
        $("INPUT#monthlyamount").keyup(function() {
            if ($("INPUT#currentyear").is(":checked")) {
                numPayments = settings.monthlyPayments;
                if (today > 15 && debitdate == "15") {
                    numPayments--;
                }
            }
            else {
                numPayments = 12;
            }
            if ($("DIV.isa_investoption:last").is(":visible")) {
                lumpsum = parseInt($("INPUT#lumpsum").val());
                if (isNaN(lumpsum)) { lumpsum = 0; };
            }
            else {
                lumpsum = 0;
            }
            var fieldval = $(this).val();
            var fieldval_trimmed = parseInt(fieldval.replace(/[^0-9\\.]/g, '').replace(/^(\d*\.\d*)\..*$/, "$1") * 1.0);
            $("DIV.totpayments P.monthlytot SPAN").text(fieldval_trimmed * numPayments);
            $("DIV.totpayments P.lump SPAN").text(lumpsum);
            $("DIV.totpayments P.total SPAN").text((fieldval_trimmed * numPayments) + lumpsum);
        });
        $("INPUT#lumpsum").keyup(function() {
            if ($("INPUT#currentyear").is(":checked")) {
                numPayments = settings.monthlyPayments;
                if (today > 15 && debitdate == 15 && $("DIV.isa_investoption:first").is(":visible")) {
                    numPayments = numPayments - 1;
                }
            }
            else {
                numPayments = 12;
            }
            if ($("DIV.isa_investoption:first").is(":visible")) {
                monthly = parseInt($("INPUT#monthlyamount").val());
                if (isNaN(monthly)) { monthly = 0; };
            }
            else {
                monthly = 0;
            }
            var fieldval = $(this).val();
            var fieldval_trimmed = parseInt(fieldval.replace(/[^0-9\\.]/g, '').replace(/^(\d*\.\d*)\..*$/, "$1") * 1.0);
            $("DIV.totpayments P.monthlytot SPAN").text(monthly * numPayments);
            $("DIV.totpayments P.lump SPAN").text(fieldval_trimmed);
            $("DIV.totpayments P.total SPAN").text((monthly * numPayments) + fieldval_trimmed);
        });

        //correct totals if 'how would you like to invest' answer changes
        $("INPUT.investmethod_dd").click(function() {
            if ($("INPUT#currentyear").is(":checked")) {
                numPayments = settings.monthlyPayments;
                if (today > 15 && debitdate == 15 && $("DIV.isa_investoption:first").is(":visible")) {
                    numPayments = numPayments - 1;
                }
            }
            else {
                numPayments = 12;
            }
            monthly = parseInt($("INPUT#monthlyamount").val());
            if (isNaN(monthly)) { monthly = 0; };
            $("DIV.totpayments P.monthlytot SPAN").text((monthly * numPayments));
            $("DIV.totpayments P.lump SPAN").text(0);
            $("DIV.totpayments P.total SPAN").text((monthly * numPayments));
        });
        $("INPUT.investmethod_ls").click(function() {
            if ($("INPUT#currentyear").is(":checked")) {
                numPayments = settings.monthlyPayments;
                if (today > 15 && debitdate == 15 && $("DIV.isa_investoption:first").is(":visible")) {
                    numPayments = numPayments - 1;
                }
            }
            else {
                numPayments = 12;
            }
            lumpsum = parseInt($("INPUT#lumpsum").val());
            if (isNaN(lumpsum)) { lumpsum = 0; };
            $("DIV.totpayments P.monthlytot SPAN").text(0);
            $("DIV.totpayments P.lump SPAN").text(lumpsum);
            $("DIV.totpayments P.total SPAN").text(lumpsum);
        });
        $("INPUT.investmethod_both").click(function() {
            if ($("INPUT#currentyear").is(":checked")) {
                numPayments = settings.monthlyPayments;
                if (today > 15 && debitdate == 15 && $("DIV.isa_investoption:first").is(":visible")) {
                    numPayments = numPayments - 1;
                }
            }
            else {
                numPayments = 12;
            }
            monthly = parseInt($("INPUT#monthlyamount").val());
            if (isNaN(monthly)) { monthly = 0; };
            lumpsum = parseInt($("INPUT#lumpsum").val());
            if (isNaN(lumpsum)) { lumpsum = 0; };
            $("DIV.totpayments P.monthlytot SPAN").text(monthly * numPayments);
            $("DIV.totpayments P.lump SPAN").text(lumpsum);
            $("DIV.totpayments P.total SPAN").text((monthly * numPayments) + lumpsum);
        });

        //correct totals if 'TAX YEAR' answer changes
        $("INPUT#currentyear").click(function() {
            numPayments = settings.monthlyPayments;
            if (today > 15 && debitdate == 15 && $("DIV.isa_investoption:first").is(":visible")) {
                numPayments = numPayments - 1;
            }
            var val1 = parseInt($("DIV.totpayments P.monthlytot SPAN").text());
            var val2 = parseInt($("DIV.totpayments P.lump SPAN").text());

            $("DIV.totpayments P.monthlytot SPAN").text((val1 / 12) * numPayments);
            $("DIV.totpayments P.lump SPAN").text(val2);
            $("DIV.totpayments P.total SPAN").text(((val1 / 12) * numPayments) + val2);
        });
        $("INPUT#prevyear").click(function() {
            numPayments = settings.monthlyPayments;
            if (today > 15 && debitdate == 15 && $("DIV.isa_investoption:first").is(":visible")) {
                numPayments = numPayments - 1;
            }
            var val1 = parseInt($("DIV.totpayments P.monthlytot SPAN").text());
            var val2 = parseInt($("DIV.totpayments P.lump SPAN").text());

            $("DIV.totpayments P.monthlytot SPAN").text((val1 / numPayments) * 12);
            $("DIV.totpayments P.lump SPAN").text(val2);
            $("DIV.totpayments P.total SPAN").text(((val1 / numPayments) * 12) + val2);
            numPayments = 12;
        });

        //corect totals if debit date changes
        $('INPUT#debitdate_01').click(function() {
            numPayments = settings.monthlyPayments;
            debitdate = 1;
            var val1 = parseInt($("DIV.totpayments P.monthlytot SPAN").text());
            var val2 = parseInt($("DIV.totpayments P.lump SPAN").text());

            if (today > 15) {
                $("DIV.totpayments P.monthlytot SPAN").text((val1 / (numPayments - 1)) * numPayments);
                $("DIV.totpayments P.lump SPAN").text(val2);
                $("DIV.totpayments P.total SPAN").text(((val1 / (numPayments - 1)) * numPayments) + val2);
            }
            else {
                $("DIV.totpayments P.monthlytot SPAN").text(val1);
                $("DIV.totpayments P.lump SPAN").text(val2);
                $("DIV.totpayments P.total SPAN").text(val1 + val2);
            }
        });
        $('INPUT#debitdate_15').click(function() {
            numPayments = settings.monthlyPayments;
            debitdate = 15;
            if (today > 15) {
                var val1 = parseInt($("DIV.totpayments P.monthlytot SPAN").text());
                var val2 = parseInt($("DIV.totpayments P.lump SPAN").text());

                $("DIV.totpayments P.monthlytot SPAN").text((val1 / numPayments) * (numPayments - 1));
                $("DIV.totpayments P.lump SPAN").text(val2);
                $("DIV.totpayments P.total SPAN").text(((val1 / numPayments) * (numPayments - 1)) + val2);

            }
            numPayments = numPayments - 1;
        });
    }
    // Datepicker
    //fix for ie - it was jumping to top of page when selecting a date
    $("TABLE.ui-datepicker-calendar A").live('click', function(e) { e.preventDefault(); });
    $('.calendar_ps').datepicker({
        minDate: 0,
        maxDate: '+2m',
        dateFormat: 'dd/mm/yy',
        inline: true
    });
    $('.calendar_gen').datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        inline: true
    });
    if ($(".calendar_trns").size() > 0) {
        var currentyear = now.getFullYear();
        var currentmonth = now.getMonth();
        var currentday = now.getDate();

        var taxyear = currentyear;
        if (currentmonth < 4) {
            if (currentmonth < 3) {
                taxyear--;
            }
            if (currentmonth == 3 && currentday < 6) {
                taxyear--;
            }
        }

        $('.calendar_trns').datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd/mm/yy',
            minDate: new Date(taxyear, 3, 6),
            maxDate: now,
            defaultDate: new Date(taxyear, 3, 6),
            inline: true
        });
    }
    //live function added for step 5 of the healthcare application
    $('.calendar_m1').live('click', function() {
        $(this).datepicker({
            changeMonth: true,
            changeYear: true,
            maxDate: 0,
            dateFormat: 'dd/mm/yy',
            inline: true,
            showOn: 'focus',
            onClose: function() {
                $(this).removeClass("error");
            }
        }).focus();
    });
    //special case to allow future date to be entered
    $('.calendar_future').live('click', function() {
        $(this).datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd/mm/yy',
            inline: true,
            showOn: 'focus',
            onClose: function() {
                $(this).removeClass("error");
            }
        }).focus();
    });

    $('.calendar_m2,.calendar_m3,.calendar_m4').datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        inline: true
    });
    $('.calendar_dob,.calendar_dob_partner,.calendar_dob_ISA').datepicker({
        changeMonth: true,
        changeYear: true,
        defaultDate: "-40y",
        yearRange: "-100:+100",
        minDate: "-70y +1d",
        maxDate: "-18y -2d",
        dateFormat: 'dd/mm/yy',
        inline: true
    });

    $('.calendar_dob_child').datepicker({
        changeMonth: true,
        changeYear: true,
        defaultDate: "-10y",
        yearRange: "-100:+100",
        minDate: "-18y +1d",
        maxDate: "0",
        dateFormat: 'dd/mm/yy',
        inline: true
    });
    $('.calendar_dob_50plus').datepicker({
        changeMonth: true,
        changeYear: true,
        defaultDate: "-60y",
        yearRange: "-30:+30",
        minDate: "-79y +1d",
        maxDate: "-50y",
        dateFormat: 'dd/mm/yy',
        inline: true
    });

    $('.calendar_dob_TFS').datepicker({
        changeMonth: true,
        changeYear: true,
        defaultDate: "-20y",
        yearRange: "-100:+100",
        minDate: "-64y +1d",
        maxDate: "-16y -2d",
        dateFormat: 'dd/mm/yy',
        inline: true
    });

    $('.calendar_dob_TFSchild').datepicker({
        changeMonth: true,
        changeYear: true,
        defaultDate: "-10y",
        yearRange: "-100:+100",
        minDate: "-16y +1d",
        maxDate: "0",
        dateFormat: 'dd/mm/yy',
        inline: true
    });

    //agecheck
    $(".calendar_dob,.calendar_dob_partner,.calendar_dob_child,.calendar_dob_50plus, .calendar_dob_ISA, .calendar_dob_TFS, .calendar_dob_TFSchild").change(function() {
        var dob = $(this).val().split('/');
        //var age = displayage(dob[2], dob[1], dob[0], "years", 0, "rounddown");

        var currentyear = now.getFullYear();
        var currentmonth = now.getMonth();
        var currentday = now.getDate();

        var appdob = new Date(dob[2], dob[1] - 1, dob[0]);
        var dobyear = appdob.getFullYear();
        var dobmonth = appdob.getMonth();
        var dobday = appdob.getDate();

        //check year
        var ageyears = (currentyear - dobyear) - 1;
        //check month
        var agemonths = currentmonth - dobmonth;
        //check day
        var agedays = currentday - dobday;

        if (ageyears == 15 && agemonths >= 0 && agedays >= 0) {
            ageyears++;
        }
        if (ageyears == 17 && agemonths >= 0 && agedays >= 0) {
            ageyears++;
        }
        if (ageyears == 49 && agemonths >= 0 && agedays >= 0) {
            ageyears++;
        }
        if (ageyears == 63 && agemonths >= 0 && agedays >= 0) {
            ageyears++;
        }
        if (ageyears == 69 && agemonths >= 0 && agedays >= 0) {
            ageyears++;
        }
        if (ageyears == 79 && agemonths >= 0 && agedays >= 0) {
            ageyears++;
        }

        var isChild = $(this).attr("class").indexOf("child");
        var isFiftyPlus = $(this).attr("class").indexOf("50plus");
        var isISA = $(this).attr("class").indexOf("ISA");
        var isTFS = $(this).attr("class").indexOf("TFS");
        if (isChild != -1) {
            //child age check
            if (ageyears >= 18) {
                //over 18
                $('.over18').dialog('open');
            }
        }
        else if (isFiftyPlus != -1) {
            //50+ age check
            if (ageyears < 50) {
                //under 50
                $('.noteligible50').dialog('open');
            }
            else if (ageyears >= 80) {
                //over 79
                $('.noteligible50').dialog('open');
            }
        }
        else if (isISA != -1) {
            //ISA age check - must be over 18
            if (ageyears < 18) {
                //over 18
                $('.noteligibleISA').dialog('open');
            }
        }
        else if (isTFS != -1) {
            //16+ age check
            if (ageyears < 16) {
                //under 16
                $('.noteligibleTFS').dialog('open');
            }
            else if (ageyears >= 64) {
                //over 64
                $('.noteligibleTFS').dialog('open');
            }
        }
        else {
            //adult age check
            if (ageyears < 18) {
                //under 18
                $('.noteligible').dialog('open');
            }
            else if (ageyears >= 70) {
                //over 70
                $('.noteligible').dialog('open');
            }
        }

    });

    $(".noteligible").html("Unfortunately you are not eligible to apply for this policy. You need to be between the age of 18 and 70 when you apply. Please click cancel and your personal information will not be stored. If you have any queries with this please contact our customer services team on 0800 195 9246");
    $(".noteligible50").html("Unfortunately you are not eligible to apply for this policy. You need to be between the age of 50 and 79 when you apply. Please click cancel and your personal information will not be stored. If you have any queries with this please contact our customer services team on 0800 195 9246");
    $(".noteligibleISA").html("Unfortunately you are not eligible to create or transfer an ISA. You must be over the age of 18 when you apply to create or transfer an ISA. Please click cancel and your personal information will not be stored. If you have any queries with this please contact our customer services team on 0800 195 9246");
    $(".noteligibleTFS").html("Unfortunately you are not eligible to apply for this policy. You need to be between the age of 16 and 64 when you apply. Please click cancel and your personal information will not be stored. If you have any queries with this please contact our customer services team on 0800 195 9246");
    $(".over18").html("Unfortunately your child is not eligible to apply for this policy. Children must be under the age of 18 when you apply for their policy. Please click cancel and your personal information will not be stored. If you have any queries with this please contact our customer services team on 0800 195 9246");


    // Dialogs
    $("P.exitwarning").dialog({
        bgiframe: true,
        resizable: false,
        autoOpen: false,
        modal: true,
        height: 216,
        width: 350,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            'Continue application': function() {
                $(this).dialog('close');
                return false;
            },
            Cancel: function() {
                $(this).dialog('close');
                window.location.href = '/';
                return false;
            }
        }
    });
    $(".cancel").live("click", function(e) {
        $("P.exitwarning").dialog('open');
        e.preventDefault();
    });

    $('.numchildalert, .NaN').dialog({
        bgiframe: true,
        modal: true,
        autoOpen: false,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });

    $('.dobcheck, .dobcheck50, .dobcheckISA').dialog({
        bgiframe: true,
        resizable: false,
        autoOpen: false,
        height: 140,
        modal: true,
        height: 220,
        width: 350,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            'Re-enter Date of Birth': function() {
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
                window.location.href = '/';
            }
        }
    });


    $("SELECT.numchild").change(function() {
        $("select option:selected").each(function() {
            if ($(this).val() > 1) {
                $('.numchildalert').dialog('open');
            }
        });
    })
        .change();

    //appnav rollovers
    if ($("UL.appnav").size() > 0) {
        $("DIV.header UL.appnav LI A").hover(
			function() {
			    $(this).css({ "text-decoration": "underline", "cursor": "pointer" });
			    $(this).siblings("A.stepnum").css({ "background-image": "url(/Templates/assets/img/bg/sphere.gif)", "color": "#333333" });
			},
			function() {
			    $(this).css({ "text-decoration": "none", "cursor": "default" });
			    $(this).siblings("A.stepnum").css({ "background-image": "none", "color": "#ffffff" });
			});
        $("DIV.header UL.appnav LI A.stepnum").hover(
			function() {
			    $(this).siblings("A").css({ "text-decoration": "underline" });
			    $(this).css({ "background-image": "url(/Templates/assets/img/bg/sphere.gif)", "color": "#333333", "text-decoration": "none" });
			},
			function() {
			    $(this).siblings("A").css({ "text-decoration": "none" });
			    $(this).css({ "background-image": "none", "color": "#ffffff" });
			});
    }
    //callbackform callbacktime settings
    if ($("INPUT#asap").size() > 0) {
        if ($("INPUT#asap").is(':checked')) {
            $("SELECT#calltime").attr("disabled", "disabled");
        }
        else {
            $("SELECT#calltime").removeAttr("disabled");
        }

        $("INPUT#asap").click(function() {
            if ($("INPUT#asap").is(':checked')) {
                $("SELECT#calltime").attr("disabled", "disabled");
            }
            else {
                $("SELECT#calltime").removeAttr("disabled");
            }
        });

    }
    //faq show hide behavior
    if ($("UL.faq").size() > 0) {
        $("DIV.answertxt").hide();
        $("UL.faq LI H2").css({ "background-image": "url(/Templates/assets/img/icon/plus.gif)" });
        $("UL.faq LI H2").hover(
		  function() {
		      $(this).css({ "cursor": "pointer" });
		  },
		  function() {
		      $(this).css({ "cursor": "default" });
		  });

        $("UL.faq LI H2").click(function() {
            if ($(this).hasClass("revealed")) {
                $(this).siblings("DIV.answertxt").slideUp();
                $(this).removeClass("revealed");
                $(this).css({ "background-image": "url(/Templates/assets/img/icon/plus.gif)" });
            }
            else {
                $(this).siblings("DIV.answertxt").slideDown();
                $(this).addClass("revealed");
                $(this).css({ "background-image": "url(/Templates/assets/img/icon/minus.gif)" });
            }

        });

    }
    //findaddress
    if ($("INPUT.postcode").size() > 0) {
        // pre-load spinner graphic
        $.preloadImages('/Templates/assets/img/spinner.gif');

        //add btn
        $("INPUT.postcode").each(function(i) {
            if ($(this).parents("DIV.bankdetails").attr("class") != undefined) {
                $(this).parents("FIELDSET").slice(0, 1).after("<div class='findaddress instance" + i + "'><span class='genericbutton silverbtn'><a href='#' class='lookup'>Find bank</a></span></div><div class='addresslookup" + i + "' title='Address look-up'><select size='17' style='width:100%;' class='fl' id='addresses" + i + "'></select></div>");
            }
            else {
                $(this).parents("FIELDSET").slice(0, 1).after("<div class='findaddress instance" + i + "'><span class='genericbutton silverbtn'><a href='#' class='lookup'>Find address</a></span></div><div class='addresslookup" + i + "' title='Address look-up'><select size='17' style='width:100%;' class='fl' id='addresses" + i + "'></select></div>");
            }

            $('.addresslookup' + i).dialog({
                bgiframe: true,
                resizable: false,
                autoOpen: false,
                //height:140, Why twice?
                modal: true,
                height: 420,
                width: 550,
                overlay: {
                    backgroundColor: '#000',
                    opacity: 0.5
                },
                buttons: {
                    'Select': function() {
                        var selectedAddress = $("#addresses" + i + " :selected").text();
                        var AddressNodes = selectedAddress.split(',');
                        if (AddressNodes.length > 2 && AddressNodes.length < 4) {
                            var address1 = jQuery.trim(AddressNodes[0]);
                            var address2 = jQuery.trim(AddressNodes[1]);
                            var city = jQuery.trim(AddressNodes[2]);
                        }
                        else if (AddressNodes.length > 3 && AddressNodes.length < 5) {
                            var bankname = jQuery.trim(AddressNodes[0]);
                            var address1 = jQuery.trim(AddressNodes[1]);
                            var address2 = "";
                            var city = jQuery.trim(AddressNodes[2]);
                            var postcode = jQuery.trim(AddressNodes[3]);
                        }
                        else if (AddressNodes.length > 3) {
                            var bankname = jQuery.trim(AddressNodes[0]);
                            var address1 = jQuery.trim(AddressNodes[1]);
                            var address2 = jQuery.trim(AddressNodes[2]);
                            var city = jQuery.trim(AddressNodes[3]);
                            var postcode = jQuery.trim(AddressNodes[4]);
                        }
                        else {
                            var address1 = jQuery.trim(AddressNodes[0]);
                            var address2 = "";
                            var city = jQuery.trim(AddressNodes[1]);
                        }
                        $("A.lookup").eq(i).parents("DIV.findaddress").prev("FIELDSET").children("P").children("INPUT.bankname").val(bankname);
                        $("A.lookup").eq(i).parents("DIV.findaddress").prev("FIELDSET").children("P").children("INPUT.address1").val(address1);
                        $("A.lookup").eq(i).parents("DIV.findaddress").prev("FIELDSET").children("P").children("INPUT.address2").val(address2);
                        $("A.lookup").eq(i).parents("DIV.findaddress").prev("FIELDSET").children("P").children("INPUT.city").val(city);

                        if (postcode != '')
                            $("A.lookup").eq(i).parents("DIV.findaddress").prev("FIELDSET").children("P").children("INPUT.postcode").val(postcode);
                        $(this).dialog('close');
                    },
                    'Enter manually': function() {
                        $(this).dialog('close');
                    }
                }
            });
        });
        //btn positioning
        $("DIV.tfs_step2").size() > 0 ? repositionButtons(0) : repositionButtons(11);

        //only allow numeric chars in bankcode
        $('.sortcode').numeric();
        //end

        $('DIV.findaddress A').click(function(e) {
            //required to keep 2nd 'find bank' btn in the right place on 50+ bank details
            if ($("DIV.fp_step5").size() > 0) {
                if ($.browser.msie && $.browser.version.substr(0, 1) < 8) {
                    $("DIV.instance1").css({ "top": "736px" });
                }
                else {
                    $("DIV.instance1").css({ "top": "700px" });
                }
            }
            e.preventDefault();
            var btnInstance = $(this).parents("DIV.findaddress").attr("class");
            var RegExp = (/(instance[\d]{1,2})/);
            var test = RegExp.exec(btnInstance);
            if (test) {
                btnInstance = test[0];
            }
            else {
                btnInstance = "instance0"; //should never occur
            }
            var btnIndex = $('A.lookup').index($(this));
            var postcode = $(this).parents("DIV." + btnInstance).prev("FIELDSET").children("P").children("INPUT.postcode").val();
            var sortcode = $(this).parents("DIV." + btnInstance).prev("FIELDSET").children("P").children("INPUT.sortcode:first").val();
            sortcode += $(this).parents("DIV." + btnInstance).prev("FIELDSET").children("P").children("INPUT.sortcode").not("INPUT.sortcode:first,INPUT.sortcode:last").val();
            sortcode += $(this).parents("DIV." + btnInstance).prev("FIELDSET").children("P").children("INPUT.sortcode:last").val();
            if (sortcode.length)
                sortcode = sortcode.replace(/,/g, "-");

            if (sortcode.length < 6) {
                $('<p>Please make sure you have entered a valid sort code</p>').dialog({ title: "Invalid Sort Code", buttons: { "Ok": function() { $(this).dialog("close"); } } });
                $(this).parents("DIV." + btnInstance).prev("FIELDSET").children("P.bankaddress").html("");
                return;
            }
            if ($(this).parents("DIV.bankdetails").attr("class") != undefined) {

                //ajaxcall: banklookup
                //$("#addresses"+btnIndex).after('<img class="spinner' + btnIndex + '" style="position:relative;left:5px;top:90px;" src="/Templates/assets/img/spinner.gif" alt="Loading" />');
                //$("#addresses"+btnIndex).hide();
                $.getJSON("/handlers/BankLookup.ashx", { sortcode: sortcode },
			function(json) {
			    if (json.length) {
			        var branch = json[0];
			        if (jQuery.trim(branch.name) != "") {
			            $("A.lookup").eq(btnIndex).parents("DIV." + btnInstance).prev("FIELDSET").children("INPUT.bankname").val(jQuery.trim(branch.name));
			            $("A.lookup").eq(btnIndex).parents("DIV." + btnInstance).prev("FIELDSET").children("INPUT.address1").val(jQuery.trim(branch.address1));
			            $("A.lookup").eq(btnIndex).parents("DIV." + btnInstance).prev("FIELDSET").children("INPUT.address2").val(jQuery.trim(branch.address2));
			            $("A.lookup").eq(btnIndex).parents("DIV." + btnInstance).prev("FIELDSET").children("INPUT.city").val(jQuery.trim(branch.city));
			            $("A.lookup").eq(btnIndex).parents("DIV." + btnInstance).prev("FIELDSET").children("INPUT.county").val(jQuery.trim(branch.county));
			            $("A.lookup").eq(btnIndex).parents("DIV." + btnInstance).prev("FIELDSET").children("INPUT.postcode").val(jQuery.trim(branch.postcode));


			            if ($("DIV." + btnInstance).prev("FIELDSET").children("P.bankaddress").size() > 0) {
			                //$("P.bankaddress")
			                $("DIV." + btnInstance).prev("FIELDSET").children("P.bankaddress").html("<strong>" + jQuery.trim(branch.name) + "</strong><br />" + jQuery.trim(branch.address1) + "<br />" + jQuery.trim(branch.address2) + "<br />" + jQuery.trim(branch.city) + "<br />" + jQuery.trim(branch.county) + "<br />" + jQuery.trim(branch.postcode));
			            }
			            else {
			                //$("P.notify")
			                $("DIV." + btnInstance).prev("FIELDSET").children("P.notify").after("<p class='bankaddress'><strong>" + jQuery.trim(branch.name) + "</strong><br />" + jQuery.trim(branch.address1) + "<br />" + jQuery.trim(branch.address2) + "<br />" + jQuery.trim(branch.city) + "<br />" + jQuery.trim(branch.county) + "<br />" + jQuery.trim(branch.postcode) + "</p>");
			            }
			        } else {
			            $('<p>Please make sure you have entered a valid sort code</p>').dialog({ title: "Invalid Sort Code", buttons: { "Ok": function() { $(this).dialog("close"); } } });
			            $(this).parents("DIV." + btnInstance).prev("FIELDSET").children("P.bankaddress").html("");
			        }
			    }
			    else {
			        $('<p>No bank branch could be found for the specified sortcode.</p>').dialog({ title: "Invalid Bank Branch", buttons: { "Ok": function() { $(this).dialog("close"); } } });
			        $(this).parents("DIV." + btnInstance).prev("FIELDSET").children("P.bankaddress").html("");
			    }
			});
            }
            else {
                //ajaxcall: address lookup
                $("#addresses" + btnIndex).after('<img class="spinner' + btnIndex + '" style="position:relative;left:5px;top:90px;" src="/Templates/assets/img/spinner.gif" alt="Loading" />');
                $("#addresses" + btnIndex).hide();
                $.getJSON("/handlers/PostcodeLookup.ashx", { postcode: postcode },
			function(json) {
			    $("#addresses" + btnIndex).empty();
			    $(json).each(function(i) {
			        var option = "<option>";
			        if (i == 0) {
			            option = "<option selected='selected'>";
			        }
			        if (this.street == "") {
			            option = option + this.house + ", " + this.city + "</option>";
			        }
			        else {
			            option = option + this.house + ", " + this.street + ", " + this.city + "</option>";
			        }
			        $("#addresses" + btnIndex).append(option);
			    });
			    $("#addresses" + btnIndex).show();
			    $(".spinner" + btnIndex).remove();
			});
            }

            if ($(this).parents("DIV.bankdetails").attr("class") == undefined) {
                $('.addresslookup' + btnIndex).dialog('open');
            }

            e.preventDefault();
        });
    }

    //qtip
    if ($("A.tooltip").size() > 0) {
        $("A.tooltip").qtip({
            show: 'mouseover',
            hide: 'mouseout',
            position: {
                corner: {
                    target: 'rightTop',
                    tooltip: 'bottomLeft'
                },
                adjust: {
                    x: 8
                }
            },
            style: {
                background: '#fff',
                color: '#333',
                border: {
                    width: 3,
                    radius: 3,
                    color: '#616d79'

                },
                tip: 'leftBottom',
                name: 'cream' // Inherit from preset style
            }
        })
        $("A.tooltip").click(function() { return false; })
    }

    //Tax free savings application : step1
    if ($("DIV.parentguardian").size() > 0) {
        $("DIV.parentguardian").hide();
        if ($("DIV.whoplanfor INPUT.toggle").is(":checked")) {
            $("DIV.parentguardian").show();
        }
        $("DIV.whoplanfor INPUT").click(function() {
            if ($(this).attr("class") == "toggle") {
                $("DIV.parentguardian").show();
            }
            else {
                $("DIV.parentguardian").hide();
            }
        });
    }
    //Tax free savings application : step2
    if ($("DIV.existingpolicies").size() > 0) {
        $("DIV.existingpolicies").hide();
        $("DIV.instance1").css({ "top": (parseInt($('DIV.instance1').css('top'), 10) - 65) + "px" });
        $("DIV.instance2").css({ "top": (parseInt($('DIV.instance2').css('top'), 10) - 65) + "px" });
        $("DIV.taxexempt INPUT").click(function() {
            if ($(this).attr("class") != "default") {
                $("DIV.existingpolicies").show();
                $("DIV.instance1").css({ "top": (parseInt($('DIV.instance1').css('top'), 10) + 65) + "px" });
                $("DIV.instance2").css({ "top": (parseInt($('DIV.instance2').css('top'), 10) + 65) + "px" });
            }
            else {
                $("DIV.existingpolicies").hide();
                $("DIV.instance1").css({ "top": (parseInt($('DIV.instance1').css('top'), 10) - 65) + "px" });
                $("DIV.instance2").css({ "top": (parseInt($('DIV.instance2').css('top'), 10) - 65) + "px" });
            }
        });

        $("DIV.app2_existingpolicies").hide();
        $("DIV.app2_taxexempt INPUT").click(function() {
            if ($(this).attr("class") != "default") {
                $("DIV.app2_existingpolicies").show();

            }
            else {
                $("DIV.app2_existingpolicies").hide();
            }
        });

    }

    //Tax free savings application : step3
    if ($("DIV.taxfreepremiums").size() > 0) {
        $("SPAN.premiumoption").remove();
        //hide select elem & create slider
        $("DIV.taxfreepremiums SELECT").hide();

        var term = $("DIV.taxfreepremiums SELECT").val();
        var pp = $("INPUT.investmentterm:checked").val();
        pp = (pp == "0" ? "m" : "a");
        if (pp == "m") {
            var maturityvalue = (25 * 12) * term;
        }
        else {
            var maturityvalue = 270 * term;
        }
        $("DIV.maturityvalue SPAN").html("&pound;" + maturityvalue);

        $("DIV.taxfreepremiums SELECT").each(function(counter) {
            var minValue = $(this).children("OPTION").eq(0).val();
            var totSteps = $(this).children("OPTION").length;
            var maxValue = $(this).children("OPTION").eq(totSteps - 1).val();

            //append HTML for sliders
            //append HTML to show slider value

            $(this).prev("LABEL").after('<span class="term">' + term + ' years</span>');
            $(this).after('<div class="slidercontainer"><div class="slider"></div><p class="minval">' + minValue + '</p><p class="maxval">' + maxValue + '</p>');
            $(".slider").slider({
                value: term - 10,
                min: 1,
                max: totSteps,
                step: 1,
                slide: function(event, ui) {
                    $(this).parent().prev("SELECT").children("OPTION").eq((ui.value - 1)).attr("selected", "selected");
                    $(this).parent().siblings("SPAN.term").html($(this).parent().prev("SELECT").val() + " years");
                    //the monthly premium selected in the slider
                    var premium = parseInt($("SPAN.premium").next("SELECT").val());
                    var term = parseInt($("SPAN.term").next("SELECT").val());
                    var pp = $("INPUT.investmentterm:checked").val();
                    pp = (pp == "0" ? "m" : "a");
                    if (pp == "m") {
                        var maturityvalue = (25 * 12) * term;
                    }
                    else {
                        var maturityvalue = 270 * term;
                    }
                    $("DIV.maturityvalue SPAN").html("&pound;" + maturityvalue);
                },
                change: function(event, ui) {
                    var sliderIndex = $('DIV.slider').index($(this));
                    $(this).prev("SELECT").children("OPTION").eq((ui.value - 1)).attr("selected", "selected");
                    //the monthly premium selected in the slider
                    var premium = parseInt($("SPAN.premium").next("SELECT").val());
                    var term = parseInt($("SPAN.term").next("SELECT").val());
                    var pp = $("INPUT.investmentterm:checked").val();
                    pp = (pp == "0" ? "m" : "a");
                    if (pp == "m") {
                        var maturityvalue = (25 * 12) * term;
                    }
                    else {
                        var maturityvalue = 270 * term;
                    }
                    $("DIV.maturityvalue SPAN").html("&pound;" + maturityvalue);
                }
            });

            $("INPUT.investmentterm").click(function() {
                var term = $("DIV.taxfreepremiums SELECT").val();
                var pp = $(this).val();
                pp = (pp == "0" ? "m" : "a");
                if (pp == "m") {
                    var maturityvalue = (25 * 12) * term;
                    $("DIV.maturityvalue SPAN").html("&pound;" + maturityvalue);
                }
                else {
                    var maturityvalue = 270 * term;
                    $("DIV.maturityvalue SPAN").html("&pound;" + maturityvalue);
                }
            });



        });
        //create total monthly premium div
        $("DIV.sidebar").append('<div class="genericheaderbox green maturityvalue"><img class="arrow" src="/Templates/assets/img/content/arrowhead_green.gif" alt="" /><h3 style="line-height:1.2em">Total premiums paid in at end of term</h3><div class="hr"><hr /></div><p><span>&pound;' + maturityvalue + '</span></div>');
        //re-initialise tooltip
        $("A.tooltip1").qtip({
            show: 'mouseover',
            hide: 'mouseout',
            position: {
                corner: {
                    target: 'topLeft',
                    tooltip: 'bottomRight'
                },
                adjust: {
                    x: 2,
                    y: -6
                }
            },
            style: {
                background: '#fff',
                color: '#333',
                border: {
                    width: 3,
                    radius: 3,
                    color: '#616d79'

                },
                tip: 'bottomRight',
                name: 'cream' // Inherit from preset style
            }
        })
        $("A.tooltip1").click(function() { return false; })
        if ($.browser.mozilla) {
            $("DIV.content DIV.main DIV.application.taxfreepremiums FIELDSET LEGEND SPAN").css({ "top": "-10px", "left": "0px" });
        }
    }

    //Simple form selection highlights
    if ($("INPUT.inforequest").size() > 0) {
        $("DIV.hc_only").hide();
        repositionButtons(0);
        $("INPUT.inforequest").each(
			function(i) {
			    if ($(this).attr("checked")) {
			        $(this).parents("DIV").slice(0, 1).addClass("selected");
			    }
			    if (i == 0 && $(this).attr("checked")) {
			        $("DIV.hc_only").show();
			        repositionButtons(5);
			    }
			});
        $("INPUT.inforequest").click(
        	function() {
        	    if ($(this).attr("type") == "radio") {
        	        $("INPUT.inforequest").parents("DIV").removeClass("selected");
        	    }
        	    var whichcolor = $(this).parents("DIV").slice(0, 1).attr("class").substr(17);
        	    if ($(this).parents("DIV").slice(0, 1).hasClass("selected")) {
        	        $(this).parents("DIV").slice(0, 1).removeClass("selected");
        	        if (whichcolor == "green selected") {
        	            $("DIV.hc_only").hide();
        	            repositionButtons(-7);
        	        }
        	    }
        	    else {
        	        $(this).parents("DIV").slice(0, 1).addClass("selected");
        	        if (whichcolor == "green") {
        	            $("DIV.hc_only").show();
        	            repositionButtons(-7);
        	        }
        	    }
        	});
    }
    //top Nav first level rollover states
    if ($("UL.topnav").size() > 0) {
        //check OS
        if (navigator.appVersion.indexOf("Mac") != -1) {
            //adjust subnav position fo macs
            //This is neccessary as mac's render fonts slightly larger than PC's
            if ($.browser.mozilla) {
                //Adjust for firefox
                $("DIV.header UL.subnav.purple").css({ "margin-left": "339px" });
                $("DIV.header UL.subnav.green").css({ "margin-left": "122px" });
            }
            if ($.browser.safari) {
                //Adjust for safari
                //$("DIV.header UL.subnav.purple").css({"margin-left":"339px"});
                $("DIV.header UL.subnav.green").css({ "margin-left": "122px" });
            }
        }


        $("UL.topnav A, UL.subnav A").css({ "text-decoration": "none" });
        var navstate = $("UL.topnav").attr("class").substr(7);

        switch (navstate) {
            case "active1":

                $("UL.topnav LI A").hover(
			  function() {

			      var itemIndex = $(this).parent('li').parent('ul').find('li').index($(this).parent('li'));

			      if (itemIndex > 0) {

			          $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_l_o_active1.gif)" });
			          $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_r_o.gif)" });
			          if (itemIndex == 1) {
			              $("UL.topnav LI.item3 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav3_l_o_active1_rollover2.gif)" });
			          }
			          if (itemIndex == 2) {
			              $("UL.topnav LI.item4 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav4_l_o_active1_rollover2.gif)" });
			          }
			      }
			  },
			  function() {
			      var itemIndex = $(this).parent('li').parent('ul').find('li').index($(this).parent('li'));

			      if (itemIndex > 0) {
			          $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_l.gif)" });
			          $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_r.gif)" });
			          if (itemIndex == 1) {
			              $("UL.topnav LI.item3 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav3_l.gif)" });
			          }
			          if (itemIndex == 2) {
			              $("UL.topnav LI.item4 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav4_l.gif)" });
			          }
			      }
			  }
			);

                break;
            case "active2":

                $("UL.topnav LI A").hover(
			  function() {
			      var itemIndex = $(this).parent('li').parent('ul').find('li').index($(this).parent('li'));

			      if (itemIndex != 1) {
			          $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_l_o_active2.gif)" });
			          $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_r_o.gif)" });
			          if (itemIndex == 0) {
			              $("UL.topnav LI.item2 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav2_l_active2_rollover1.gif)" });
			          }
			          if (itemIndex == 2) {

			              $("UL.topnav LI.item4 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav4_l_o_active1_rollover2.gif)" });
			          }
			          if (itemIndex == 3) {
			              $("UL.topnav LI.item4 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav4_l_o_active1.gif)" });
			          }
			      }
			  },
			  function() {
			      var itemIndex = $(this).parent('li').parent('ul').find('li').index($(this).parent('li'));

			      if (itemIndex != 1) {
			          $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_l.gif)" });
			          $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_r.gif)" });
			          if (itemIndex == 0) {
			              $("UL.topnav LI.item2 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav2_l_o.gif)" });
			          }
			          if (itemIndex == 2) {
			              $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_r_active2.gif)" });
			              $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_l_active2.gif)" });
			              $("UL.topnav LI.item4 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav4_l.gif)" });
			          }
			      }
			  }
			);

                break;
            case "active3":

                $("UL.topnav LI A").hover(
			  function() {
			      var itemIndex = $(this).parent('li').parent('ul').find('li').index($(this).parent('li'));
			      console.log("E Item Index: " + itemIndex);
			      if (itemIndex != 2) {
			          $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_l_o_active3.gif)" });
			          $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_r_o.gif)" });
			          if (itemIndex == 0) {
			              $("UL.topnav LI.item2 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav2_l_active3_rollover1.gif)" });
			          }
			          if (itemIndex == 1) {
			              $("UL.topnav LI.item3 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav3_l_o_active2.gif)" });
			          }
			          if (itemIndex == 3) {
			              $("UL.topnav LI.item4 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav4_l_o_active3_rollover2.gif)" })
			          }

			      }
			  },
			  function() {
			      var itemIndex = $(this).parent('li').parent('ul').find('li').index($(this).parent('li'));
			      console.log("F Item Index: " + itemIndex);
			      if (itemIndex != 2) {
			          $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_l.gif)" });
			          $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_r.gif)" });
			          if (itemIndex == 0) {
			              $("UL.topnav LI.item2 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav2_l_active3.gif)" });
			          }
			          if (itemIndex == 1) {
			              $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav2_l_active3.gif)" });
			              $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav2_r_active3.gif)" });
			              $("UL.topnav LI.item3 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav3_l_o.gif)" });
			          }
			          if (itemIndex == 3) {
			              $("UL.topnav LI.item4 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav4_l_o_active1_rollover2.gif)" });
			          }
			      }
			  }
			);

                break;
            case "active4":

                $("UL.topnav LI A").hover(
			  function() {
			      var itemIndex = $(this).parent('li').parent('ul').find('li').index($(this).parent('li'));
			      console.log("G Item Index: " + itemIndex);
			      if (itemIndex != 3) {
			          $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_l_o_active3.gif)" });
			          $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_r_o.gif)" });
			          if (itemIndex == 1) {
			              $("UL.topnav LI.item3 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav3_l_active2.gif)" });
			          }
			          if (itemIndex == 2) {
			              $("UL.topnav LI.item3 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav3_l_o_active1.gif)" });
			              $("UL.topnav LI.item4 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav4_l_o_active3_rollover2.gif)" });
			          }
			      }
			  },
			  function() {
			      var itemIndex = $(this).parent('li').parent('ul').find('li').index($(this).parent('li'));
			      console.log("H Item Index: " + itemIndex);
			      if (itemIndex != 3) {
			          $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_l.gif)" });
			          $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav" + (itemIndex + 1) + "_r.gif)" });
			          if (itemIndex == 1) {
			              $("UL.topnav LI.item3 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav3_l.gif)" });
			              $("UL.topnav LI.item2 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav2_l_active3.gif)" });
			          }
			          if (itemIndex == 2) {
			              $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav3_l_active2.gif)" });
			              $(this).css({ "background-image": "url(/Templates/assets/img/bg/nav3_r_active2.gif)" });
			              $("UL.topnav LI.item4 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav4_l_o.gif)" });
			              $("UL.topnav LI.item3 A SPAN").css({ "background-image": "url(/Templates/assets/img/bg/nav3_l.gif)" });
			          }

			      }
			  }
			);

                break;
            default:
                //code to be executed if navstate is different from case 1,2 and 3
                $("UL.topnav LI A").hover(
			  function() {
			      $(this).css({ "text-decoration": "underline" });
			  },
			  function() {
			      $(this).css({ "text-decoration": "none" });
			  }
			);
        }
        var itemIndex = $("UL.subnav LI").index($("UL.subnav LI.current"));
        if (itemIndex > 0) {
            $("DIV.header UL.subnav LI:eq(" + (itemIndex - 1) + ") A").css({ "background-image": "none" });
        }

        //top Nav subnav rollover states
        $("UL.subnav A").not("UL.subnav LI.current A").hover(
			  function() {
			      var subnavcolour = $(this).parents("UL").attr("class").substr(7);
			      $(this).children("SPAN").css({ "background-image": "url(/Templates/assets/img/bg/" + subnavcolour + "nav_active.gif)", "background-position": "center bottom", "background-repeat": "no-repeat" });
			      if (jQuery.support.cssFloat) {
			          //not ie
			          $(this).children("SPAN").css({ "padding": "4px 0 18px" });
			      }
			      else {
			          //ie
			          $(this).children("SPAN").css({ "padding": "4px 0 17px" });
			      }
			      $(this).parents("LI").slice(0, 1).css({ "background-image": "url(/Templates/assets/img/bg/" + subnavcolour + "nav_active_r.gif)", "background-position": "right 0", "background-repeat": "no-repeat" });
			      $(this).css({ "background-image": "url(/Templates/assets/img/bg/" + subnavcolour + "nav_active_l.gif)", "background-position": "0 0", "background-repeat": "no-repeat" });

			      var itemIndex = parseInt($(this).parent('li').parent('ul').find('li').index($(this).parent('li')));
			      var selectedIndex = parseInt($(this).parent('li').parent('ul').find('li').index($(this).parent('li').parent('ul').find('li.current')));
			      if (itemIndex > 0 && itemIndex != (selectedIndex + 1)) {
			          $("DIV.header UL.subnav." + subnavcolour + " LI:eq(" + (itemIndex - 1) + ") A").css({ "background-image": "none" });
			      }
			      if ($(this).parents("LI").attr("class") == "last") {
			          $(this).css({ "padding-right": "20px" });
			      }
			  },
			  function() {
			      var subnavcolour = $(this).parents("UL").attr("class").substr(7);
			      $(this).children("SPAN").css({ "background-image": "none", "padding": "0 0 22px" });
			      $(this).parents("LI").slice(0, 1).css({ "background-image": "url(/Templates/assets/img/bg/" + subnavcolour + "nav.gif)", "background-position": "0 0", "background-repeat": "repeat-x" });
			      var itemIndex = parseInt($(this).parent('li').parent('ul').find('li').index($(this).parent('li')));
			      var selectedIndex = parseInt($(this).parent('li').parent('ul').find('li').index($(this).parent('li').parent('ul').find('li.current')));
			      if ($("UL.subnav LI").index($("UL.subnav LI.current")) != 0 && itemIndex < $("UL.subnav LI").index($("UL.subnav LI.current")) && (parseInt($("UL.subnav LI").index($("UL.subnav LI.current")) - itemIndex)) == 1) {
			          $(this).css({ "background-image": "none" });
			      }
			      else {
			          $(this).css({ "background-image": "url(/Templates/assets/img/bg/" + subnavcolour + "navsep.gif)", "background-position": "right 0", "background-repeat": "no-repeat" });
			      }
			      if (itemIndex > 0 && itemIndex != (selectedIndex + 1)) {
			          $("DIV.header UL.subnav." + subnavcolour + " LI:eq(" + (itemIndex - 1) + ") A").css({ "background-image": "url(/Templates/assets/img/bg/greennavsep.gif)" });
			      }
			      if ($(this).parents("LI").attr("class") == "last") {
			          $(this).parents("LI").css({ "background-image": "url(/Templates/assets/img/bg/" + subnavcolour + "navedge_r.gif)", "background-position": "right 0", "background-repeat": "no-repeat" });
			          $(this).css({ "background-image": "none", "padding-right": "28px" });
			      }
			  }
			);
    }

    //add corners - but not for ie6
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        //no bottom corners for you ie6!! (Ie6 cannot calculate the positioning of the bottom cnr if there is animation on the page that moves content around)
        $("DIV.genericheaderbox, DIV.genericbox").not("DIV.sidebar DIV.genericheaderbox,DIV.homepage1,DIV.homepage2,DIV.homepage3,DIV.double").append('<div class="topcnr"><img src="/Templates/assets/img/spacer.gif" alt="" /></div>');
        $("DIV.simpleform DIV.sidebar DIV.genericheaderbox").append('<div class="topcnr"><img src="/Templates/assets/img/spacer.gif" alt="" /></div>');
    }
    else {
        $("DIV.genericheaderbox, DIV.genericbox").append('<div class="btmcnr"><img src="/Templates/assets/img/spacer.gif" alt="" /></div>');
        $("DIV.genericheaderbox, DIV.genericbox").not("DIV.sidebar DIV.genericheaderbox,DIV.homepage1,DIV.homepage2,DIV.homepage3,DIV.double").append('<div class="topcnr"><img src="/Templates/assets/img/spacer.gif" alt="" /></div>');
        $("DIV.simpleform DIV.sidebar DIV.genericheaderbox").append('<div class="topcnr"><img src="/Templates/assets/img/spacer.gif" alt="" /></div>');
    }

    //autocomplete for calendar fields
    $("INPUT.hasDatepicker").attr("autocomplete", "off");

    // Added by backend
    clickOnEnter('.searchfield', '.searchbtn');
    clickOnEnter('.loginemail', '#login');
    clickOnEnter('.loginpassword', '#login');

    $('a[rel="external"]').addClass('external').click(function(e) { window.open($(this).attr('href')); e.preventDefault(); });


    // Flash
    if ($("DIV#hccalc").length) {
        $("DIV#hccalc").html("<div id='flashholder'></div>");
        $("DIV#hccalc").css({ 'margin-left': -14 + 'px', 'margin-top': -14 + 'px' });
        swfobject.embedSWF("/Templates/assets/swf/calculators/HealthcareCalculator.swf", "flashholder", "680", "572", "10.0.0", "/Templates/assets/swf/expressInstall.swf");
    }

    if ($("DIV#fiftycalc").length) {
        $("DIV#fiftycalc").html("<div id='flashholder'></div>");
        $("DIV#fiftycalc").css({ 'margin-left': -5 + 'px', 'margin-top': -10 + 'px' });
        swfobject.embedSWF("/Templates/assets/swf/calculators/50PlusCalculator.swf", "flashholder", "664", "268", "10.0.0", "/Templates/assets/swf/expressInstall.swf");
    }
});







//format number as currency
function Round(Number, DecimalPlaces) {
   return Math.round(parseFloat(Number) * Math.pow(10, DecimalPlaces)) / Math.pow(10, DecimalPlaces);
}
function RoundFixed(Number, DecimalPlaces) {
   return Round(Number, DecimalPlaces).toFixed(DecimalPlaces);
}

function clickOnEnter(fieldSelector, buttonSelector)
{
	if (jQuery(fieldSelector).length)
	{
		jQuery(fieldSelector).bind("keydown", function(e)
		{
			var keyCode = (e.keyCode ? e.keyCode : e.which);
					
			if (keyCode == 13)
			{
				var button = jQuery(buttonSelector, jQuery(this).parent());
				
				if (button.length)
				{
					button.click();
					e.preventDefault();
				}
			}
		});
	}
}