//Get Message
function ClickMessage(updatediv) {
    updatediv.innerHTML = "An insurance consultant will try to contact you within 1 business day.";
}
// sort function - ascending (case-insensitive)
function sortFuncAsc(record1, record2) {
    var value1 = record1.optValue.toLowerCase();
    var value2 = record2.optValue.toLowerCase();
    if (value1 * 1 > value2 * 1) return (1);
    if (value1 * 1 < value2 * 1) return (-1);
    return (0);
}

// sort function - descending (case-insensitive)
function sortFuncDesc(record1, record2) {
    var value1 = record1.optValue.toLowerCase();
    var value2 = record2.optValue.toLowerCase();
    if (value1 * 1 > value2 * 1) return (-1);
    if (value1 * 1 < value2 * 1) return (1);
    return (0);
}
function sortSelect(selectToSort, ascendingOrder, valsel) {
    if (arguments.length == 1) ascendingOrder = true;    // default to ascending sort

    // copy options into an array
    var myOptions = [];
    for (var loop = 0; loop < selectToSort.options.length; loop++) {
        myOptions[loop] = { optText: selectToSort.options[loop].text, optValue: selectToSort.options[loop].value };
    }

    // sort array
    if (ascendingOrder) {
        myOptions.sort(sortFuncAsc);
    }
    else {
        myOptions.sort(sortFuncDesc);
    }

    // copy sorted options from array back to select box
    selectToSort.options.length = 0;
    for (var loop = 0; loop < myOptions.length; loop++) {
        var optObj = document.createElement('option');
        optObj.text = myOptions[loop].optText;
        optObj.value = myOptions[loop].optValue;
        selectToSort.options.add(optObj);
    }
    // select a specific value
    for (var loop = 0; loop < myOptions.length; loop++) {
        if (selectToSort[loop].value == valsel) {

            selectToSort[loop].selected = true;
            break;
        }
    }
}

function rememberinputs(a, b) {
    if (a.value == b) { a.value = ''; } else if (a.value == '') { a.value = b; } else { a.value = a.value; }
}
function checkinputs(a, b) {
    if (a.value == '') { a.value = b; } else { a.value = a.value; }
}

//for getting date into the hidden field
function getdateintoidden(newval, dateval) {
    document.getElementById(dateval).value = newval;
}

function checksession(newval, dateval) {
    newval = document.getElementById(dateval).value;
}

//for the purpose of showing Best Rate reports in a loop
//global variables
var newp;
var newp1 = new Array();
var fadeobj;
var timer = 4000;
var currindex = 0;
var userclicks = new Boolean(false); // the boolean value capturing the event when user moves mouse over the tabs
//function that gets triggered when the page is loaded

function OnPageLoad() {    
    //when user moves the mouse over the report panel, the animation is stopped    
    if (navigator.userAgent.indexOf('MSIE 8') == 0) {
        userclicks = true;
    }
    else {
        userclicks = false;
    }
    jQuery('#FeaturedProducts').mouseover(function() { userclicks = true; });
    jQuery('#TargetFeaturedReport').mouseover(function() { userclicks = true; });
    if (jQuery('#TargetFeaturedReport').val() != null) {   
        //setTimeout("Startloop()", timer);
        newp = jQuery('#FeaturedProducts a');
    }
    return;
}
// function that starts the infinate loop till the user does a mouse over on the report panel
function Startloop() {
    var lis = jQuery('#TargetFeaturedReport').get(0);
    //when user moves the mouse over the report panel, the animation is stopped
    lis.onmouseover = function() { userclicks = true; };
    if (userclicks == false) {        
        if (currindex < 3) {
            currindex++;
        }
        else {
            currindex = 0;
        }

        setTab((jQuery('#FeaturedProducts li a').get(currindex)), "FeaturedProducts", "on");
        jQuery('#FeaturedProducts li a').each(function(index) { if (index == currindex) { jQuery(this).click(); } });
        setTimeout("Startloop()", timer);
    }
}

// function to highlight the tab that has been selected
function settabs(index) {
    
    switch (index) {
        case 0: jQuery("#" + newp[0]).attr('class', 'on'); jQuery("#" + newp[1]).attr('class', ''); jQuery("#" + newp[2]).attr('class', ''); ; jQuery("#" + newp[3]).attr('class', ''); ; break;
        case 1: jQuery("#" + newp[1]).attr('class', 'on'); jQuery("#" + newp[0]).attr('class', ''); jQuery("#" + newp[2]).attr('class', ''); ; jQuery("#" + newp[3]).attr('class', ''); ; break;
        case 2: jQuery("#" + newp[2]).attr('class', 'on'); jQuery("#" + newp[1]).attr('class', ''); jQuery("#" + newp[0]).attr('class', ''); ; jQuery("#" + newp[3]).attr('class', ''); ; break;
        case 3: jQuery("#" + newp[3]).attr('class', 'on'); jQuery("#" + newp[1]).attr('class', ''); jQuery("#" + newp[2]).attr('class', ''); ; jQuery("#" + newp[0]).attr('class', ''); ; break;
    }
}
//to fade in the element
function fadeIn(elem, duration) {
    function nudgeOpacity(to) {
        if (to > 1) { return; }
        elem.style.opacity = to; elem.style.filter = 'alpha(opacity=' + to * 100 + ')';
        setTimeout(function() { nudgeOpacity(to + 0.1); }, duration / 10);
    } nudgeOpacity(0.1);
}
// variables to be used for showCalc, hideCalc, showmenu and hidemenu
var t;
var mnu;
// Show drop down menu
function showCalc(element, mnu) {
    if (mnu == 'calc')
        jQuery('#mmReg').hide();
    else if (mnu == 'reg')
        jQuery('#mmCalc').hide();

    clearTimeout(t);
    showmenu(element);
}

function showmenu(element) {
    jQuery(element).attr('style', 'display=block');
    return element;
}
// Hide dropdown menu
function hideCalc(element) {
    t = setTimeout("hidemenu('" + element + "')", 10);
}

function hidemenu(element) {
    if (jQuery('#' + element).parent().id != 'mmCalc')
        jQuery('#' + element).attr('style', 'display=none');
    return element;
}

jQuery.fn.toggleText = function(a, b) {
	return this.each(function() {
		jQuery(this).text(jQuery(this).text() == a ? b : a);
	});
};

function ToggleAdvancedOptions() {
    jQuery('#ic_selectorAdvanced').toggle();
    jQuery("#advanceOptions").each(function() 
    {
	    var a = 'Show advanced search options';
	    var b = 'Hide advanced search options';
		jQuery(this).text(jQuery(this).text() == a ? b : a);
});
}
function ShowAllResults() {
    var maxResultCount = jQuery('#MaxResultCount').val();
    var minResultCount = "20";
    //Show All    
    if (maxResultCount == minResultCount) {
        jQuery('#MaxResultCount').val("-1");
        jQuery('#topResultText').text("All results shown");
        jQuery('#topResult').attr('src', "/IMG/Template/btn-show-first20-results.gif");
    }
    else //Show 20
    {
        jQuery('#MaxResultCount').val(minResultCount);
        jQuery('#topResultText').text("Top " + minResultCount + " results shown");
        jQuery('#topResult').attr('src', "/IMG/Template/btn-show-all-results.gif");
    }
    GenReport(1);
}
function ValidateProductSelector() {
    var ps = jQuery("#ProductSelectorSchemaName");
    switch (ps.val()) {
        case "PersonalLoanSelector":
            ValidatePersonalLoanSelector();
            break;
        case "HomeLoanSelector":
            ValidateHomeLoanSelector();
            break;
        case "SavingsAccountSelector":
            ValidateSavingsAccountSelector();
            break;
        case "CreditCardSelector":
            ValidateCreditCardSelector();
            break;
        case "TransactionAccountSelector":
            ValidateTransactionAccountSelector();
            break;
        case "SmallBusinessBanking107TermDeposit90AtCallSelector":
            ValidateSmallBusinessBanking107TermDeposit90AtCallSelector();
            break;
        default:
            GenReport(1);
    }
}

function ValidateSmallBusinessBanking107TermDeposit90AtCallSelector() {
    var valid = true;
    var msg = '';

    if (jQuery("input[name*='AccountPurpose']:checked").val() == 'FixedTerm') {
        if (!jQuery('#ProductType_0').is(':checked')
        && !jQuery('#ProductType_1').is(':checked')
        && !jQuery('#ProductType_2').is(':checked')
        && !jQuery('#ProductType_3').is(':checked')) {
            valid = false;
            msg += 'Please select at least one fixed term account type.';
        }
    }

    if (jQuery("input[name*='AccountPurpose']:checked").val() == 'AtCallSavings') {
        if (!jQuery('#AccountType_0').is(':checked')
        && !jQuery('#AccountType_1').is(':checked')) {
            valid = false;
            msg += 'Please select at least one at call account type.';
        }
    }

    if (!valid) { alert(msg); return false; }
    GenReport(1);
}

function ValidateTransactionAccountSelector() {
    var valid = true;
    var msg = '';
    GenReport(1);
}

function ValidateCreditCardSelector() {
    GenReport(1);
    //Ensure that this is crossbrower
    //parent.document.dyniframesize();
}

function ValidateSavingsAccountSelector() {
    
    var valid = true;
    var msg = '';

    //Round Decimal, set to left of '.'
    if (jQuery('#SavingsAmount').val().indexOf(".") > 0) {
        jQuery('#SavingsAmount').val(jQuery('#SavingsAmount').get(0) - jQuery('#SavingsAmount').val().indexOf("."));
    }

    //Validate Amount length
    if (jQuery('#SavingsAmount').get(0).length > 10) {
        msg += "\nPlease enter an amount lower than $99,999,999";
        valid = false;
    }

    //AtCallSavings - Must have at least one type selected.
    if (jQuery("input[name='AtCallSavings']:checked").val() == 'AtCallSavings') {
        if (!jQuery('#AccountTypeLeft_0').is(':checked')
        && !jQuery('#AccountTypeLeft_1').is(':checked')
        && !jQuery('#AccountTypeLeft_2').is(':checked')
        && !jQuery('#AccountTypeLeft_3').is(':checked')
        && !jQuery('#AccountTypeLeft_4').is(':checked')
        && !jQuery('#AccountTypeRight_0').is(':checked')
        && !jQuery('#AccountTypeRight_1').is(':checked')
        && !jQuery('#AccountTypeRight_2').is(':checked')
        && !jQuery('#AccountTypeRight_3').is(':checked')) {
            valid = false;
            msg += 'Please select at least one type of account.';
        }
        // Ensure it exists as the primary savings page has no report tabs causing next command to kill js
    
    }
    if (jQuery("input[name='AccountPurpose']:checked").val() == 'FixedTerm') {
        // Ensure it exists as the primary savings page has no report tabs causing next command to kill js
        jQuery('#ProductSelectorReport2').hide();
    }
    else {
        jQuery('#ProductSelectorReport2').show();
    }
    

    if (!valid) { alert(msg); return false; }
    GenReport(1);
}

//Product Selector Validation
function ValidateHomeLoanSelector() {
    var valid = true;
    valid = DoValidateHomeLoanSelector();

    if (!valid) {
        return false;
    }
    GenReport(1);
}

function ValidateHomeLoanSelectorIndex() {

    var valid = true;
    valid = DoValidateHomeLoanSelector();

    if (!valid) {
        return false;
    }
    var f = jQuery('#ic_product_select').get(0);
    f.submit();
}

function DoValidateHomeLoanSelector() {
    var msg = '';
    var f = jQuery('#ic_product_select').get(0);
    var valid = true;
    //Loan Amount
    if (jQuery('#LoanAmount').get(0).length > 10) {
        msg += "\nPlease enter an amount lower than $99,999,999.";
        valid = false;
    }

    //Availability
    if (jQuery("#Availability_0").is(':checked') == false && jQuery("#Availability_1").is(':checked') == false) {
        msg += "\nPlease select an availability.";
        valid = false;        
    }

    //LoanType
    if (jQuery("#LoanType_0").is(':checked') == false && jQuery("#LoanType_1").is(':checked') == false && jQuery("#LoanType_2").is(':checked') == false) {
        msg += "\nPlease select a loan type.";
        valid = false;
    }
    if (!valid) {
        alert(msg);
    }

    return valid;
}

//Sort
function Sort(field, defaultColumnSorting) {

    if (typeof Validate == "function") {
        Validate();
    }

    var sortOrder = jQuery('#SortOrder').val();
    var sortField = jQuery('#SortField').val();
    
    if (sortField == field) {
        sortOrder = ToggleSortDirection(sortOrder);        
    } else {
        sortOrder = defaultColumnSorting;                    
    }
    
    jQuery('#SortField').val(field);
    jQuery('#SortOrder').val(sortOrder);
    jQuery('#SortReportName').val("ProductList_" + jQuery('#ProductDefinitionId').val() + "_" + jQuery('#ReportName').val());

    if (typeof GenerateReport == "function") {
        // Used by the new selectors
        GenerateReport('productSelectorReportResults', 1);
    }
    else {
        GenReport(1);
    }
}

function ToggleSortDirection(direction) {
    return direction == 'Ascending' ? 'Descending' : 'Ascending';
}
function PageReport(pageNo)
{
    if (typeof GenerateReport == "function")
    {
        // Used by the new selectors
        GenerateReport('productSelectorReportResults', pageNo);
    }
    else
    {
        GenReport(pageNo);
    }
}

function GroupByApply(o)
{
    jQuery('#IsGroupBy').val(o.checked);
    // sync up the all list featured product first checkboxes
    jQuery(".chkGroupBy").attr('checked', o.checked)
    GenReport(1);
}


//Gen Standard Report - regenerates
function GenReport(pageNo)
{
    try 
    {
        jQuery('#PageNo').val(pageNo);
        //alert(jQuery('#PageNo'));
        AjaxSelector(jQuery('#productSelectorReportResults'), jQuery('#productSelectorHumanFilterSummaryResults'));
    }
    catch (ex) {
        alert(ex);
    }
}
function QueryStringSort(field, el) {

    var loc = location.href;
    if (loc.indexOf("?") == -1) { loc = loc + "?"; }
    var qs = new Hash(jQuery(loc.toQueryParams()));
    var o = ToggleOrder(qs.get('SortOrder'), qs.get('SortField'), field);

    qs.set('ReportName', jQuery('#ReportName').val());
    qs.set('SortField', field);
    qs.set('SortOrder', o);
    //alert(qs.inspect());
    window.location.href = "List.aspx?" + qs.toQueryString();
}

function ToggleOrder(o, qf, f) {
    //Only toggle when QS field is passed field
    if (qf == f) {
        if (o == 'undefined') { return 'Ascending' };
        if (o == 'Ascending') { return 'Descending' };
    }
    return 'Ascending';
}

//Compare button redirect
function Compare(dest) {
    var pIds = '';
    jQuery('input[type="checkbox"][id^="chkProductListCompare_"]').each(function(i) {        
        if (jQuery(this).is(':checked')) {
            pIds += jQuery(this).get(0).id.replace('chkProductListCompare_', '') + ',';
        }
    });       
    window.location.href = dest + '?productId=' + pIds;
}

function ReverseMortgageSelectorClick(el) {
    HomeLoanSelectorClick(el);
}

function InitializeHomeLoanSelector()
{
    if (jQuery('#LoanTypeExtra_2').is(':checked')) {
        HomeLoanSelectorClick(jQuery('#LoanTypeExtra_2').get(0));
    }
}

//function to enable or disable controls
function HomeLoanSelectorClick(el) {
    var isOn = false;    
    if (el.type == 'checkbox' && el.checked) isOn = true;
    
    if (el.id == 'LoanTypeExtra_2') {
        var onControls = "";
        var offControls = "Availability_0,Availability_1,LoanType_0,LoanType_1,LoanType_2,LoanTypeIntroRate_0,LoanTypeExtra_0,LoanTypeExtra_1,Features_0,Features_1,Features_2,Features_3,RepaymentFrequency_0,RepaymentFrequency_1,RepaymentFrequency_2,FeesUpfront,FeesMonthly,FeesEarlyTermination,LoanAmount,PropertyValue";

        //Set hidden ProductDefinitionId
        jQuery('#ProductDefinitionId').val(isOn ? '29' : '27');
        
        if (isOn) {
            EnableControls(false, offControls);
        }
        else {
            EnableControls(true, offControls);
        }
    }

    //Low Doc
    if (el.id == 'LoanTypeExtra_0') {
        var onControls = "LoanTypeExtra_2";
        var offControls = "LoanTypeExtra_1,LoanTypeExtra_2,FeesEarlyTermination,LoanTypeIntroRate_0";

        //Set hidden ProductDefinitionId
        jQuery('#ProductDefinitionId').val(isOn ? '24' : '27');

        if (isOn) {
            EnableControls(false, offControls);
        }
        else {
            EnableControls(true, offControls);
        }
    }

    //Interest Only
    if (el.id == 'LoanTypeExtra_1') {
        var onControls = "";
        var offControls = "LoanTypeIntroRate_0,LoanTypeExtra_2";

        if (isOn) {
            EnableControls(false, offControls);
        }
        else {
            EnableControls(true, offControls);
        }
    }

    //Line of credit
    if (el.id == 'LoanType_2') {
        var onControls = "";
        var offControls = "LoanTypeIntroRate_0";

        if (isOn) {
            EnableControls(false, offControls);
        }
        else {
            EnableControls(true, offControls);
        }
    }

    //Intro rate
    if (el.id == 'LoanTypeIntroRate_0') {
        var onControls = "";
        var offControls = "LoanType_2,LoanTypeExtra_0,LoanTypeExtra_1,LoanTypeExtra_2";

        if (isOn) {
            EnableControls(false, offControls);
        }
        else {
            EnableControls(true, offControls);
        }
    }
}

function InitializeSavingsSelector() 
{
    SavingsAccountSelectorClick(jQuery('#AccountPurpose').get(0));

    if (jQuery("input[name='AccountPurpose']:checked").val() == 'FixedTerm') {
        // Ensure it exists as the primary savings page has no report tabs causing next command to kill js
        jQuery('#ProductSelectorReport2').hide();
    }
    else {
        jQuery('#ProductSelectorReport2').show();
    }    
}

function SavingsAccountSelectorClick(el) {
   
    var isOn = false;
    if (jQuery('#' + el.id).is(':checked')) {
        isOn = true;
    }
   
    var FoundMatch = false;

    var AccountPurpose = jQuery("input[name='AccountPurpose']:checked").val();
    
    if (el.id == 'AccountPurpose') {

        if (AccountPurpose == 'FixedTerm') {
            //Set hidden ProductDefinitionId
            jQuery('#ProductDefinitionId').val(isOn ? '107' : '34');
            jQuery('#SortReportName').val("ProductList_" + jQuery('#ProductDefinitionId').val() + "_" + jQuery('#ReportName').val());

            var onControls = "SavingsTerm,ProductType_0,ProductType_1,ProductType_2,ProductType_3";
            var offControls = "AccountTypeLeft_0,AccountTypeLeft_1,AccountTypeLeft_2,AccountTypeLeft_3,AccountTypeLeft_4,AccountTypeRight_0,AccountTypeRight_1,AccountTypeRight_2,AccountTypeRight_3";
            FoundMatch = true;
            //Hide Feature tab for FixedTerm. Also ensure it exists as the primary savings page has no report tabs causing next command to kill js
            if (jQuery('#productselectorreport1').val() != null) jQuery('#ProductSelectorReport1').hide();
        }

        if (AccountPurpose == 'AtCallSavings') {
            //Set hidden ProductDefinitionId
            jQuery('#ProductDefinitionId').val(isOn ? '107' : '34');
            jQuery('#SortReportName').val("ProductList_" + jQuery('#ProductDefinitionId').val() + "_" + jQuery('#ReportName').val());

            var onControls = "AccountTypeLeft_0,AccountTypeLeft_1,AccountTypeLeft_2,AccountTypeLeft_3,AccountTypeLeft_4,AccountTypeRight_0,AccountTypeRight_1,AccountTypeRight_2,AccountTypeRight_3";
            var offControls = "SavingsTerm,ProductType_0,ProductType_1,ProductType_2,ProductType_3";
            FoundMatch = true;
            //Display Feature tab for AtCallSaving. Also ensure it exists as the primary savings page has no report tabs causing next command to kill js
            if (jQuery('#productselectorreport1').val() != null) jQuery('#productselectorreport1').show();
        }
    }
    
    //First Home Savers
    if (el.id == "AccountTypeLeft_4") {
        if (el.value == "FirstHomeSaver") {
            if (isOn) 
            {
                var onControls = "AccountTypeLeft_4";
                var offControls = "AccountTypeLeft_0,AccountTypeLeft_1,AccountTypeLeft_2,AccountTypeLeft_3,AccountTypeRight_0,AccountTypeRight_1,AccountTypeRight_2,AccountTypeRight_3";
                FoundMatch = true;
            }
            else 
            {
                var offControls = "";
                var onControls = "AccountTypeLeft_0,AccountTypeLeft_1,AccountTypeLeft_2,AccountTypeLeft_3,AccountTypeLeft_4,AccountTypeRight_0,AccountTypeRight_1,AccountTypeRight_2,AccountTypeRight_3";
                FoundMatch = true;
            }
        }
    }
    
    if (FoundMatch) {
        EnableControls(false, offControls);
        EnableControls(true, onControls);        
    }
    return;
}
function InitializeSmallBusinessSavingsSelector() {
    jQuery(document).ready(SmallBusinessBanking107TermDeposit90AtCallSelectorClick(jQuery('#AccountPurpose').get(0)));
}

function SmallBusinessBanking107TermDeposit90AtCallSelectorClick(el) {

    var isOn = false;
    if (jQuery('#' + el.id).is(':checked')) {
        isOn = true;
    }

    var FoundMatch = false;

    // Savings account selector
    if (el.id == 'AccountPurpose') {
        if (el.value == "FixedTerm") {
            //Set hidden ProductDefinitionId
            jQuery('#ProductDefinitionId').val(isOn ? '90' : '107');
            jQuery('#SortReportName').val("ProductList_" + jQuery('#ProductDefinitionId').val() + "_" + jQuery('#ReportName').val());
            jQuery('#SortField').value = 'CalcInterestEarned';

            var onControls = "SavingsTerm,ProductType_0,ProductType_1,ProductType_2,ProductType_3";
            var offControls = "AccountType_0,AccountType_1";
            FoundMatch = true;
            //Hide Feature tab for FixedTerm. Also ensure it exists as the primary savings page has no report tabs causing next command to kill js
            if (jQuery('#productselectorreport1').val() != null) jQuery('#ProductSelectorReport1').hide();
        }

        if (el.value == "AtCallSavings") {
            //Set hidden ProductDefinitionId
            jQuery('#ProductDefinitionId').val(isOn ? '107' : '90');
            jQuery('#SortReportName').val("ProductList_" + jQuery('#ProductDefinitionId').val() + "_" + jQuery('#ReportName').val());
            jQuery('#SortField').val('InterestMore_10000');

            var onControls = "AccountType_0,AccountType_1";
            var offControls = "SavingsTerm,ProductType_0,ProductType_1,ProductType_2,ProductType_3";
            FoundMatch = true;
            //Display Feature tab for AtCallSaving. Also ensure it exists as the primary savings page has no report tabs causing next command to kill js
            if (jQuery('#productselectorreport1').val() != null) jQuery('#productselectorreport1').show();
        }
    }

    if (FoundMatch) {
        EnableControls(false, offControls);
        EnableControls(true, onControls);        
    }
}

function CreditCardSelectorClick(el) {

    var isOn = false;
    if (jQuery('#' + el.id).is(':checked')) {
        isOn = true;
    }

    // Credit Card selector
    if (el.id == 'AccountType') {
        var FoundMatch = false;
        if (el.get(0).value == "Credit") {
            var onControls = "CardStatus_0,CardStatus_1,CardStatus_2,Feature_0,Feature_1,Feature_2,Feature_3";
            EnableControls(true, onControls);
        }
        if (el.get(0).value == "Debit") {
            var offControls = "CardStatus_0,CardStatus_1,CardStatus_2,Feature_0,Feature_1,Feature_2,Feature_3";
            EnableControls(false, offControls);
        }
        if (el.get(0).value == "Charge") {
            var offControls = "CardStatus_0,CardStatus_1,CardStatus_2,Feature_0,Feature_1,Feature_2,Feature_3";
            EnableControls(false, offControls);
        }
    }
}

function InitializeTransactionAccountSelector() {
    TransactionAccountSelectorClick(jQuery('#TransactionAccountType').get(0));
}

function TransactionAccountSelectorClick(el) {
    if (el.id == "Transaction") {
        var onControls = "TransactionAccessToAccountLeft_0,TransactionAccessToAccountLeft_1,TransactionAccessToAccountLeft_2,TransactionAccessToAccountRight_0,TransactionAccessToAccountRight_1";
        EnableControls(true, onControls);
    }
    if (el.id == "Passbook") {
        var onControls = "TransactionAccessToAccountLeft_0,TransactionAccessToAccountLeft_1,TransactionAccessToAccountLeft_2,TransactionAccessToAccountRight_0,TransactionAccessToAccountRight_1";
        EnableControls(false, onControls);
    }
    if (el.id == "Cheque") {
        var onControls = "TransactionAccessToAccountLeft_0,TransactionAccessToAccountLeft_1,TransactionAccessToAccountLeft_2,TransactionAccessToAccountRight_0,TransactionAccessToAccountRight_1";
        EnableControls(true, onControls);
    }
}

//********************************************************************************
// Personal Loans
//********************************************************************************
function InitializePersonalLoanSelector()
{
    jQuery("input[name='IcLoanType']").each(function(i)
    {
        if (this.checked)
        {
            PersonalLoanSelectorClick(this);
        }
    });
}

var personalLoanInterestRateChanged = false;

function PersonalLoanSelectorClick(el)
{
    if (el.name == "IcLoanType")
    {
        // Turn on Secured Loan for Personal Loan
        EnableControls(el.value == "GeneralPurpose", "IcPersonalLoanSecurity_0");

        // Turn off Time to repay and insterest rate selectros for Overdraft
        EnableControls(el.value != "Overdraft", "LoanPeriod");

        if (el.value == "Overdraft")
        {
            jQuery("#LoanPeriod").val(3);
        }
        
        // Need to select the controls by name for Interest Rate
        EnableControl(el.value != "Overdraft", jQuery("input[name='InterestRate']"));

        if (el.value == "Overdraft")
        {
            jQuery("input[name='InterestRate']").each(function(i)
            {
                if (this.value == "Variable")
                {
                    this.checked = true;

                    PersonalLoanInterestRateChanged();
                }
            });
        }
    }
    if (el.name == "InterestRate")
    {
        PersonalLoanInterestRateChanged();
    }
}
function PersonalLoanInterestRateChanged()
{
    personalLoanInterestRateChanged = true;

    var interestType = jQuery("input[name='InterestRate']:checked").val();

    jQuery("#SelectedTabName").val("Rates" + interestType);
    jQuery("#ReportName").val("Rates" + interestType);
}
function ValidatePersonalLoanSelector()
{
    var valid = true;
    var msg = '';
    //Loan Amount
    if (jQuery('#LoanAmount').get(0).value == '')
    {
        valid = false;
        msg += '\n Please enter a loan amount.';
    }

    if (!valid)
    {
        alert(msg); 
        return false;
    }

    if (personalLoanInterestRateChanged)
    {
        if (jQuery("input[name='InterestRate']:checked").val() == "Fixed")
        {
            setTabList("ProductSelectorReport0", "ProductSelectorReport", "on");
        }
        else
        {
            setTabList("ProductSelectorReport1", "ProductSelectorReport", "on");
        }
        personalLoanInterestRateChanged = false;
    }
       
    GenReport(1);
}

//********************************************************************************
// General
//********************************************************************************
function EnableControls(isOn, els)
{
    if (els != null && els != "")
    {
        for (i = 0; i < els.split(",").length; i++) 
        {
            var item = els.split(",")[i];
            EnableControl(isOn, jQuery('#' + item));
        }
    }   
}
function EnableControl(isOn, obj)
{
    if (obj != null)
    {
        if (isOn)
        {
            obj.removeAttr("disabled");
        }
        else
        {
            obj.attr('disabled', 'disabled');
        }
    }
}

function EnableRadio(enable, radio) {    
    var form = jQuery('#ic_product_select');    

    if (enable) {
        var buttons = form.getInputs('radio', radio);
        buttons.invoke('enable');
    }
    else {
        var buttons = form.getInputs('radio', radio);
        buttons.invoke('disable');
    }
    return true;
}

//FactSheet remove column from display by stripping productId from QS and redirecting
function FactSheetRemove(removeId) {    
    var loc = location.href.replace(removeId, '');
    loc = loc.replace(",,", ",");
    loc = loc.replace("productId=,", "productId=");
    if (loc.charAt( loc.length-1 ) == ',') { loc = loc.slice(0, loc.length - 1); }
    window.location.href = loc;
    return false;
}

//Load report by reportId and target element name
function processSelector(reportId, submitType, formName, url, targetElement) {
    if (submitType == 'ajax') {
        loadReportById(reportId, targetElement);
    }
    else {
        var f = jQuery('#' + formName);
        f.action = url;
        f.submit();
    }
}

//Set Hidden value and submit
function SetView(reportName, resultTarget, summaryTarget)
{
    jQuery('#ReportName').val(reportName);
    AjaxSelector(jQuery('#' + resultTarget), jQuery('#' + summaryTarget));
}

function CrossPageSubmit(targetUrl)
{
    SelectorSubmitOld(targetUrl);
}
function SelectorSubmitOld(targetUrl) 
{
    var f = jQuery('#aspnetForm').get(0);

    jQuery("#__VIEWSTATE").remove();

    f.action = targetUrl;
    f.submit();
}

//Load AJAX ProductSelector
function AjaxSelector(resultTarget, summaryTarget) {
    if (jQuery(resultTarget).val() != null) {
        AjaxProductSelectorReport(jQuery(resultTarget).get(0).id);
    }
    if (jQuery(summaryTarget).val() != null) {
        AjaxProductSelectorHumanFilterSummary(jQuery(summaryTarget).get(0).id);
    }
}

//Handle product selector with target element name
function AjaxProductSelectorReport(targetElement)
{
    var params = jQuery('#aspnetForm').serialize(true);
    jQuery('#' + targetElement).prepend("<div class='loading'>Loading</div>");
    jQuery.ajax({
        type: "POST",
        url: "/Handler/ProductSelectorReportHandler.ashx",
        data: params,
        success: function(html) {
        jQuery('#' + targetElement).html(html);            
            if (jQuery.browser.version < 7) {
                jQuery(targetElement).supersleight();
            }
        },
        error: function() {
            AjaxError;
        }
    });
}

//Selector summary with target element name
function AjaxProductSelectorHumanFilterSummary(targetElement) {
    var params = jQuery('#aspnetForm').serialize(true);
    jQuery('#' + targetElement).prepend("<div class='loading'>Loading</div>");
    jQuery.ajax({
        type: "POST",
        url: "/Handler/ProductSelectorHumanFilterSummaryHandler.ashx",
        data: params,
        success: function(html) {            
            jQuery('#' + targetElement).html(html);
        },
        error: function() {
            AjaxError;
        }
    });
}

//Load report by reportId and target element name
function loadReportById(reportId, targetElement, locationId) 
{
    try {        
        jQuery('#' + targetElement).prepend("<div class='loading'>Loading</div>");
        jQuery.ajax({
            type: "POST",
            url: "/Handler/ReportHandlerHtml.ashx?reportId=" + reportId + "&locationId=" + locationId,
            data: "['']",
            success: function(html) {
                jQuery('#' + targetElement).html(html);
            },
            error: function() {
                AjaxError;
            }
        });
    }
    catch (ex) {
        alert(ex);
    }
}

function loadReportByName(reportName, targetElement, locationId)
{
    try {        
        jQuery('#' + targetElement).prepend("<div class='loading'>Loading</div>");
        jQuery.ajax(
        {
            type: "POST",
            url: "/Handler/ReportHandlerHtml.ashx?reportName=" + reportName + "&locationId=" + locationId,
            data: "['']",
            success: function(html) {
                jQuery('#' + targetElement).html(html);
            },
            error: function() {
                AjaxError;
            }
        });
    }
    catch (ex) {
        alert(ex);
    }
}

//Load help tooltip by HtmlSnippet name and the target element
function showTip(tipName, el) {
    jQuery.ajax({
        type: "POST",
        url: '/Handler/HtmlSnippetHandler.ashx?name=' + tipName,
        data: params,
        success: function(html) {
            jQuery('#' + el.html(html));
        },
        error: function() {
            AjaxError;
        }
    });

}

function AjaxError(error) {
    alert("An error occured: " + error.responseText);
}

//Clears anchors of 'on' class then adds to passed item.
function setTab(tabA, tabList, cssClass) {
    jQuery('#' + tabList + ' a').removeClass(cssClass); //Clear class
    jQuery(tabA).addClass(cssClass); //Add class
}

//Clears anchors of 'on' class then adds to passed item.
function setReportOn(divName, toSetId, numberOfReports) {
    for (i = 0; i < numberOfReports; i++) document.getElementById(divName + i).style.display = "none";
    document.getElementById(divName + toSetId).style.display = "block";
}

//Clears anchors of 'on' class then adds to passed item.
function setTabList(tabA, tabList, cssClass) {
    jQuery('#' + tabList + ' li').removeClass(cssClass); //Clear class
    jQuery('#' + tabA).addClass(cssClass); //Add class
}

function selectTab(tabIndex) {
    if (tabIndex == 0) {
        jQuery("divOtherCharges").removeClass("hide");
        jQuery("divFeeAndRepayments").addClass("hide");
        jQuery("liFeeAndRepayments").removeClass("on");
        jQuery("liOtherCharges").addClass("on");
    } else {
        jQuery("divFeeAndRepayments").removeClass("hide");
        jQuery("divOtherCharges").addClass("hide");
        jQuery("liFeeAndRepayments").addClassName("on");
        jQuery("liOtherCharges").removeClassName("on");
    }  
}

//Toggle inner text of ele
function toggleMsg(el, msg1, msg2) {
    if (jQuery(el).html == msg1) {
        jQuery(el).html = msg2;
    } else {
        jQuery(el).html = msg1;
    }
}

function UpdateUrl(o, clkValue)
{
    if (o.href != null && o.href.indexOf("CLK") == -1)
    {
        o.href = o.href + "&CLK=" + clkValue;
    }
}
/*
Affiliate Campaign (Deprecated)
*/
/*
// Affiliate Campaign Click Events
function AffiliateCampaignClick(publisherId, buttonTypeId, productDataId, location)
{
    //    alert('publisherId: ' + publisherId);
    //    alert('buttonTypeId: ' + buttonTypeId);
    //    alert('productDataId: ' + productDataId);
    //    alert('location: ' + location);
    try
    {
        var clickId = -12;
        return (jQuery.ajax({
            async: false,
            type: "POST",
            url: "/Handler/AffiliateCampaignClickHandler.ashx",
            data: { PublisherId: publisherId, ButtonTypeId: buttonTypeId, ProductDataId: productDataId, Location: location },
            success: function(html)
            {
                clickId = html;
            },
            error:
                AjaxError
        }) == null ? -10 : clickId);
    }
    catch (ex) {
        alert("AffiliateCampaignClick: " + ex);
    }
    return -5;
}
*/

/*
Life Insurance
*/
// sort function - ascending (case-insensitive)
function sortFuncAsc(record1, record2)
{
    var value1 = record1.optValue.toLowerCase();
    var value2 = record2.optValue.toLowerCase();
    if (value1 * 1 > value2 * 1) return (1);
    if (value1 * 1 < value2 * 1) return (-1);
    return (0);
}

// sort function - descending (case-insensitive)
function sortFuncDesc(record1, record2) {
    var value1 = record1.optValue.toLowerCase();
    var value2 = record2.optValue.toLowerCase();
    if (value1 * 1 > value2 * 1) return (-1);
    if (value1 * 1 < value2 * 1) return (1);
    return (0);
}
function sortSelectnew(selectToSort, nn) {
    //    alert(nn);
    //    selectToSort[nn].selected = true;
}

function sortSelect(selectToSort, ascendingOrder, valsel) {
    if (arguments.length == 1) ascendingOrder = true;    // default to ascending sort

    // copy options into an array
    var myOptions = [];
    for (var loop = 0; loop < selectToSort.options.length; loop++) {
        myOptions[loop] = { optText: selectToSort.options[loop].text, optValue: selectToSort.options[loop].value };
    }

    // sort array
    if (ascendingOrder) {
        myOptions.sort(sortFuncAsc);
    } else {
        myOptions.sort(sortFuncDesc);
    }

    // copy sorted options from array back to select box
    selectToSort.options.length = 0;
    for (var loop = 0; loop < myOptions.length; loop++) {
        var optObj = document.createElement('option');
        optObj.text = myOptions[loop].optText;
        optObj.value = myOptions[loop].optValue;
        selectToSort.options.add(optObj);
    }
    // select a specific value
    for (var loop = 0; loop < myOptions.length; loop++) {
        if (selectToSort[loop].value == valsel) {

            selectToSort[loop].selected = true;
            break;
        }
    }
}

function LifeInsuranceContactMeClick(ddlControlId, quoteControlId) {

    var ddlContactMe = jQuery("#" + ddlControlId).get(0);
    var quoteId = jQuery("#" + quoteControlId).val();

    var contactMeOption = ddlContactMe.options[ddlContactMe.selectedIndex].text;

    jQuery.ajax({
        type: "POST",
        url: "/Handler/LifeInsuranceContactMeClickHandler.ashx",
        data: {ContactMeOption: contactMeOption, QuoteId: quoteId },
        success: function(html) {
            var text = html || 'no response text';
            jQuery('#update_div').html(text);
        },
        error: function() {
            // Do nothing. 
            //jQuery('#update_div').html('');
        }
    });
}

function selectTabCreditCards(tabIndex) 
{ //This will be rewritten to use jQuery tabs ui asap....
        jQuery("#divOtherCharges").toggle();
        jQuery("#divFeeAndRepayments").toggle();
        jQuery("#liFeeAndRepayments").toggleClass("on");
        jQuery("#liOtherCharges").toggleClass("on");  
}

String.prototype.trim = function() {
    return
    (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
}

String.prototype.startsWith = function(str)
{ return (this.match("^" + str) == str) }

String.prototype.endsWith = function(str)
{ return (this.match(str + "$") == str) }

String.Format = function(text) {
    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there’s nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
    }

    return text;
}

function LoadCssFile(cssFileUrl) {

    $("head").append("<link>");
    css = $("head").children(":last");
    css.attr({
        rel: "stylesheet",
        type: "text/css",
        href: cssFileUrl
    });
}