CheckedPostcode = null;
GasOptionExists = null;
OkToShowFaq = true;

$(document).ready(function() {
    //show state selection box or inform user if product is not available
    ShowStateBox();

    // Activate mNI
    $('input.mni').makeNiceInput();

    //show the correct products
    if ($("#C_Supply_State").val() == 'SA') {
        $('#southAusResProducts').show();
    } else {
        $('#victorianResProducts').show();
    }

    // make the heights of the product boxes
    if ($('.product').length > 1) {
        var tallest = 0;
        $('.product').each(function() {
            var thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        $('.product').height(tallest);
    }

    //initialise some values for future use
    if ($("#DDA_PaymentType").val() == '') {
        $("#DDA_PaymentType").val("1");
    }
    if ($("#QET_ID").val() == '') {
        $("#QET_ID").val("DUAL");
    }
    if ($("#Qu_EnergySavingPackage").val() == '') {
        $("#Qu_EnergySavingPackage").val("True");
    }

    if ($("#Qu_EnergySavingPackage").val() == "False") {
        SwitchOptionOff($("#enSavPack"));
    }
    $("#enSavPack").click(function() {
        EnerSavPack();
    });
    if ($("#DDA_PaymentType").val() == "0") {
        SwitchOptionOff($("#ddTypeSpan"));
    }
    $("#ddTypeSpan").click(function() {
        SetDdType();
    });

    CheckedPostcode = 0 + $('#Qu_Post_Code').val();

    //new landing page code

    // Local Scroll
    function filterPath(string) {
        return string
			.replace(/^\//, '')
			.replace(/(index|default).[a-zA-Z]{3,4}$/, '')
			.replace(/\/$/, '');
    }
    $('a[href*=#]').each(function() {
        if (filterPath(location.pathname) == filterPath(this.pathname)
			&& location.hostname == this.hostname
			&& this.hash.replace(/#/, '')) {
            var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']');
            var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
            if ($target) {
                var targetOffset = $target.offset().top;
                $(this).click(function() {
                    $('html, body').animate({ scrollTop: targetOffset }, 400);
                    return false;
                });
            }
        }
    });

    //submit the form
    $("a.switchnowbutton").live("click", function() {
        $("#Qu_Product").val($(this).attr('prod'));
        $("#mainForm").submit();
        $("a.switchnowbutton").attr("disabled", "disabled");
    });

    //determine if we have a gas selection question
    GasOptionExists = $("#gascheckbox").length;

    //setup state
    var supplystate = $("#C_Supply_State").val().toString().toLowerCase();
    $("#productarea").removeClass("victoria southaustralia").addClass(supplystate == "sa" ? "southaustralia" : "victoria");
    $("a.rmsmart").attr('href', supplystate == 'sa' ? '#TB_inline?&amp;height=250&amp;width=450&amp;inlineId=sa_more_efficiency_package&amp;modal=false' : '#TB_inline?&amp;height=160&amp;width=400&amp;inlineId=vic_more_efficiency_package&amp;modal=false');
    $("a.rmgreen").attr('href', supplystate == 'sa' ? '#TB_inline?&amp;height=250&amp;width=450&amp;inlineId=sa_more_efficiency_package&amp;modal=false' : '#TB_inline?&amp;height=160&amp;width=400&amp;inlineId=vic_more_efficiency_package&amp;modal=false');
    $("a.rmverygreen").attr('href', supplystate == 'sa' ? '#TB_inline?&amp;height=250&amp;width=450&amp;inlineId=sa_more_efficiency_package&amp;modal=false' : '#TB_inline?&amp;height=160&amp;width=400&amp;inlineId=vic_more_efficiency_package&amp;modal=false');
    $("a.rmsmarta").attr('href', supplystate == 'sa' ? '#TB_inline?&amp;height=250&amp;width=450&amp;inlineId=sa_more_efficiency_package&amp;modal=false' : '#TB_inline?&amp;height=160&amp;width=400&amp;inlineId=vic_more_efficiency_package&amp;modal=false');
    $("a.potsmart").attr('href', supplystate == 'sa' ? '#TB_inline?&amp;height=250&amp;width=450&amp;inlineId=sa_more_payontime&amp;modal=false' : '#TB_inline?&amp;height=240&amp;width=400&amp;inlineId=vic_more_payontime&amp;modal=false');
    $("a.potgreen").attr('href', supplystate == 'sa' ? '#TB_inline?&amp;height=250&amp;width=450&amp;inlineId=sa_more_payontime&amp;modal=false' : '#TB_inline?&amp;height=240&amp;width=400&amp;inlineId=vic_more_payontime&amp;modal=false');
    $("a.potverygreen").attr('href', supplystate == 'sa' ? '#TB_inline?&amp;height=250&amp;width=450&amp;inlineId=sa_more_payontime&amp;modal=false' : '#TB_inline?&amp;height=240&amp;width=400&amp;inlineId=vic_more_payontime&amp;modal=false');

    $("#h2Title").text(supplystate == 'sa' ? "Select a South Australian residential offer" : "Select a Victorian residential offer");

    $("#offerFaq").keyup(function() {
        GetFaq();
    });
    $("#faqActions").hide();

    //disable Enter key in FAQ
    $("#offerFaq").noEnter();

    //show Postcode box if there is a reference from CMS
    RefToViewRates();
});

function EnerSavPack() {
    var c = $("#enSavPack").parent().attr("class");
    $("#Qu_EnergySavingPackage").val(c == "checked" ? "True" : "False");
}

function SetDdType() {
    var c = $("#ddTypeSpan").parent().attr("class");
    if (c == "checked") {
        if ($("#DDA_PaymentType").val() == "" || $("#DDA_PaymentType").val() == "0") {
            $("#DDA_PaymentType").val("1");
        }
    } else {
        $("#DDA_PaymentType").val("0");
    }
}

function CheckPostcode() {
    var pcOk = $("#_Qu_Post_Code").valid();
    if (!pcOk) {
        return;
    }
    
    $('#Qu_Post_Code').attr('value', $('#_Qu_Post_Code').val());
    $('#Qu_Peak_And_OffPeak').attr('value', $('#_Qu_Peak_And_OffPeak').attr('checked'));
    
    var pc = 0 + $('#Qu_Post_Code').val();
    var gas = null;
    if (GasOptionExists) {
        gas = $('#QET_ID').val();
    } else {
        gas = "DUAL";   //we'll check if gas is supplied for this postcode
    }
    var hw = $('#Qu_Peak_And_OffPeak').attr('checked');
    var prod = $('#Qu_Product').val();
    var quote = $('#Qu_Reference_No').val();
    if (CheckedPostcode != pc)  //postcode is changed, so NMI values have become outdated
    {
        $('#Qu_NMI_Prefix').val('');
        $('#Qu_MIRN_Prefix').val('');
        $('#Qu_NMI_DontKnow').val('');
    }
    var nmi = $('#Qu_NMI_Prefix').val();
    var mirn = $('#Qu_MIRN_Prefix').val();
    var nmiDontKnow = $('#Qu_NMI_DontKnow').val();

    $.getJSON(SiteRoot() + 'Rates/CheckPostcode',
            { postcode: pc, gas: gas, hotwater: hw, product: prod, quote: quote, nmi: nmi, mirn: mirn, nmiDontKnow: nmiDontKnow },
            AfterPostcodeCheck);
            
    CheckedPostcode = pc;   //remember which postcode is already checked
}

function AfterPostcodeCheck(jsonData) {
    pc = $("#_Qu_Post_Code");
    HideLoadingImage();

    if (!GasOptionExists && jsonData.isGasAvailable) {
        $("#QET_ID").val("DUAL");
    }
    if (!jsonData.isElecAvailable) {
        pc.rules("add", { postcodeNoElec: true });
        pc.valid();
        pc.rules("remove", "postcodeNoElec");
    } else if (!jsonData.isGasAvailable) {
        if (GasOptionExists) {
            pc.rules("add", { postcodeNoGas: true });
            pc.valid();
            pc.rules("remove", "postcodeNoGas");
        } else {
            $("#QET_ID").val("ELEC");
            ShowRatesBox();
        }
    } else if (jsonData.isElecMultiSuppliers || jsonData.isGasMultiSuppliers) {
        ShowMultiSuppliersBox(jsonData.isElecMultiSuppliers, jsonData.isGasMultiSuppliers);
    } else {
        ShowRatesBox();
    }
}

function ShowMultiSuppliersBox(elec, gas) {
    var url = SiteRoot() + "Rates/ShowMultiSuppliersBox?KeepThis=true&width=400&height=265&elec=" + elec + "&gas=" + gas;
    tb_show("", url);
}

function CheckNmiPrefix() {
    if ($("#_Qu_MIRN_Prefix").length) {
        var cOk = $("#_Qu_MIRN_Prefix").valid();
        if (!cOk) {
            return;
        }
        $('#Qu_MIRN_Prefix').val($('#_Qu_MIRN_Prefix').val());
    }
    if ($("#_Qu_NMI_Prefix").length) {
        var cOk = $("#_Qu_NMI_Prefix").valid();
        if (!cOk) {
            return;
        }
        $('#Qu_NMI_Prefix').val($('#_Qu_NMI_Prefix').val());
    }
    $('#Qu_NMI_DontKnow').attr('value', false);

    var pc = 0 + $('#Qu_Post_Code').val();
    var gas = $('#QET_ID').val();
    var hw = $('#Qu_Peak_And_OffPeak').val();
    var prod = $('#Qu_Product').val();
    var nmi = $('#Qu_NMI_Prefix').val();
    var mirn = $('#Qu_MIRN_Prefix').val();

    $.getJSON(SiteRoot() + 'Rates/CheckNmiPrefix', 
        { postcode: pc, gas: gas, hotwater: hw, product: prod, nmi: nmi, mirn: mirn }, AfterCheckNmi);
}

function CheckNmiPrefixNoNmi() {
    $('#Qu_MIRN_Prefix').attr('value', '');
    $('#Qu_NMI_Prefix').attr('value', '');
    $('#Qu_NMI_DontKnow').attr('value', true);

    var pc = 0 + $('#Qu_Post_Code').val();
    var gas = $('#QET_ID').val();
    var hw = $('#Qu_Peak_And_OffPeak').val();
    var prod = $('#Qu_Product').val();

    $.getJSON(SiteRoot() + 'Rates/CheckNmiPrefix',
        { postcode: pc, gas: gas, hotwater: hw, product: prod, dontKnow: true }, AfterCheckNmi);
}

function AfterCheckNmi(jsonData) {
    nmi = $("#_Qu_NMI_Prefix");
    mirn = $("#_Qu_MIRN_Prefix");
    HideLoadingImage();
    if (!jsonData.isElecAvailable && nmi.length) {
        nmi.rules("add", { nmiNoElec: true });
        nmi.valid();
        nmi.rules("remove", "nmiNoElec");
    } else if (!jsonData.isGasAvailable && mirn.length) {
        mirn.rules("add", { mirnNoGas: true });
        mirn.valid();
        mirn.rules("remove", "mirnNoGas");
    } else {
        ShowRatesBox();
    }
}

function ShowRatesBox() {
    var pc = 0 + $('#Qu_Post_Code').val();
    var gas = $('#QET_ID').val();
    var hw = $('#Qu_Peak_And_OffPeak').val();
    var prod = $('#Qu_Product').val();
    var nmi = $('#Qu_NMI_Prefix').val();
    var mirn = $('#Qu_MIRN_Prefix').val();
    var dontKnow = $('#Qu_NMI_DontKnow').val();

    var url = SiteRoot() + "Rates/ShowRates?KeepThis=true&width=700&height=535&postcode=" + pc + 
        "&gas=" + gas + "&hotwater=" + hw + "&product=" + prod + "&nmi=" + nmi + "&mirn=" + mirn + "&dontKnow=" + dontKnow;
    tb_show("", url);
}

function ShowStateBox() {
    if ($("#noStream").length && ($("#noStream").val() == "1"/*power*/) || $("#noStream").val() == "2"/*mates*/) {
        //show No Product message
        var url = SiteRoot() + "Home/ShowStateBox?KeepThis=true" +
        "&prod=" + $("#Qu_Product").val() +
        "&state=" + $("#C_Supply_State").val() +
        "&noStream=" + $("#noStream").val() +
        "&width=250&height=120&modal=true";
        tb_show("", url);
    }else if ($("#C_Supply_State").val() == '') {
        //show Select state message
        var url = SiteRoot() + "Home/ShowStateBox?KeepThis=true&prod=" +
        $("#Qu_Product").val() +
        "&width=250&height=90&modal=true";
        tb_show("", url);
    } else if ($("#askForPower").val() == "True") {
        //show Would you like Power Offer message
        var url = SiteRoot() + "Home/ShowPowerOfferBox?KeepThis=true&prod=" +
            $("#Qu_Product").val() +
            "&width=320&height=118&modal=true";
        tb_show("", url);
    }
}

function RefToViewRates() {
    if ($("#getRates").length && $("#getRates").val() == "True") {
        $("#aRates").click();
    }
}

function GetFaq() {
    if (OkToShowFaq) {
        $.getJSON(SiteRoot() + 'Home/GetFaq', { query: $("#offerFaq").val() }, AfterGetFaq);
    }
}

function AfterGetFaq(json) {
    $("#faqItems").html("").show().append("#faqTmpl", json); ;
    if (json.length) {
        $("#faqActions").show();
    } else {
        $("#faqActions").hide();
    }
}

function GetFaqText(node) {
    $("#faqItems span.ansFull").hide();
    $("#faqItems span.ansPlain").show();
    $("#faqItems li[name=" + node + "] span.ansPlain").hide();

    var el = $("#faqItems li[name=" + node + "] span.ansFull");
    var text = el.html();
    if (text.toString().length == 0) {
        $.getJSON(SiteRoot() + 'Home/GetFaqText', { nodeId: node }, AfterGetFaqText);
    }
    el.show();
}

function AfterGetFaqText(json) {
    $("#faqItems li[name=" + json.NodeID + "] span.ansFull").html(json.Answer).show();
}

function FaqClose() {
    $("#faqActions").hide();
    $("#faqItems").fadeOut(300);
}

function FaqNo() {
    FaqClose();
    OkToShowFaq = false;
}
