if (LookCorp == undefined) var LookCorp = {}; // Make sure the base namespace exists.

LookCorp.SwitchEnergyEngine = {

    setupBlockUI : function() {
        $.extend($.blockUI.defaults.css, { top: '15%', width:'50em', left:'50%', 'margin-left':'-25em'}); // setup the blockUI library
        $.blockUI.defaults.overlayCSS.opacity = '0.4';
    },

    /********************************************************************************
    * Step 1
    ********************************************************************************/
    nextButtonId : null,    // clientId of the next button
    postcodeFieldId : null, // clientId of the postcode field
    localityFieldId : null, // clientId of the locality hidden field
    localityListId : 'localityList', // id of the locality list div
    previousPostcode : null, // previously entered postcode (used to detect changed postcode)
    userControlId : '',     // unique id of the wizard control (for calling with anthem)
    callbackUrl : '',
    
    // This function can replace WebForm_RestoreScrollPosition with the only side effect being
    // that the page won't scroll. (ie. it wont error or stop further page load event from happening)
    dontRestoreScrollPosition : function() {
        if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
            return theForm.oldOnLoad();
        }
        return true;
    },
    
    // fired by the body load event
    step1_onload : function() { 
        var t = LookCorp.SwitchEnergyEngine;

        t.addLocalityClickHandlers(); // in case the localities are prepopulated by the page

        // Disable or enable the localities fieldset
        var h3Localities = $("#step1_h3Localities");
        var txtPostcode = $('#' + t.postcodeFieldId);
        var fsLocalities = $("#step1_fsLocalities");
        
        if ((h3Localities.length > 0) && (txtPostcode.length > 0) && (fsLocalities.length > 0)) {
            if (txtPostcode.val().length == 4) {
                h3Localities.removeClass("disabled");
                fsLocalities.removeClass("disabled");
            } else {
                h3Localities.addClass("disabled");
                fsLocalities.addClass("disabled");
            }
        }
    },
    
    // dynamically add onclick handlers to locality li's
    addLocalityClickHandlers : function() { 
        var selector = LookCorp.substitute('#{0} a', LookCorp.SwitchEnergyEngine.localityListId); // selects all locality links
        $(selector).each( function() {
            $(this).click(function(e) { LookCorp.SwitchEnergyEngine.changeLocality(e.target); e.preventDefault(); });
        });
        $('#btnBadPostcodeSubmit').click(LookCorp.SwitchEnergyEngine.step1_submitEmailAddress);
    },
    
    // called when the postcode changes
    // obj is the postcode element
    postcodeChanged : function(obj) {
        if (obj.value == this.previousPostcode) {
            return;
        }
        
        var h3Localities = $("#step1_h3Localities");
        var fsLocalities = $("#step1_fsLocalities");

        if (obj.value.length == 4) {
        	// Show loading div
	        $('#step1_loading').show();
            
            if (h3Localities.length > 0) {
                h3Localities.removeClass("disabled");
            }

            if (fsLocalities.length > 0) {
                fsLocalities.removeClass("disabled");
            }
	        
	        // Do callback to fetch localities
	        $.post(this.callbackUrl,
	            { action : 'GetSuburbsForPostcode', pc : obj.value },
	            function(value) {
			        var localityList = $('#' + LookCorp.SwitchEnergyEngine.localityListId);
			        if (value) {
			            localityList.html(value); // set the localityList div to whatever the server returned
			            LookCorp.SwitchEnergyEngine.addLocalityClickHandlers();
			        } else {
		                localityList.html('<span class="error">Sorry, there seems to be a problem. Please try again later.</span>');
			        }
			        
			        // Hide loading div
                    $('#step1_loading').hide();
		        }
		    );
        } else {
            $('#' + this.localityListId).html(""); // clear locality list
            $('#' + this.localityFieldId).val(""); // clear selected locality id
                        
            if (h3Localities.length > 0) {
                h3Localities.addClass("disabled");
            }

            if (fsLocalities.length > 0) {
                fsLocalities.addClass("disabled");
            }
            
            // Hide loading div
            $('#step1_loading').hide();
        }
        
        this.previousPostcode = obj.value;
    },
    
    // called when a locality link is clicked
    // elem is the clicked element
    changeLocality : function(elem) {
        // Clear previously selected
        var localityIdField = $('#' + LookCorp.SwitchEnergyEngine.localityFieldId);
        var currentItem = $("#locality_" + localityIdField.value);
        
        if (currentItem.length > 0) {
            currentItem.removeClass("selected");
        }
        
        // Select current one
        $(elem).addClass("selected");
        
        // Set hidden field
        var localityId = elem.id.replace("locality_", "");
        localityIdField.val(localityId);
        
        //trigger next button
        var nextButton = $('#' + LookCorp.SwitchEnergyEngine.nextButtonId);
        nextButton.click(); // programatically click the next button
            
        return false;
    },
    
    step1_submitEmailAddress : function(event) {
        var t = LookCorp.SwitchEnergyEngine;
        var emailAddress = $('#txtBadPostcodeEmail').val();
        var valid = true;
        if (emailAddress.length <= 6) {
            valid = false;
        } else if (emailAddress.indexOf('@') <= 0) {
            valid = false;
        }
        
        event.preventDefault();
        
        if (!valid) {
            alert("Please enter a valid email address");
            return false;
        }
        
        $.post(t.callbackUrl,
            { action : 'Launcher_SubmitEmail', address : emailAddress },
            function(value) {
                if (value == "OK") {
                	var localityList = $('#' + LookCorp.SwitchEnergyEngine.localityListId);
	                localityList.text('Thanks for your interest, your email address has been submitted.');
                } else {
                    alert("Sorry, email address could not be sumbitted. Please try again later.");
                }
            });
    },
    
    // Prevent the enter key from cause a form submission
    preventEnter : function(e) {
        var key;
        if(window.event)
            key = window.event.keyCode; //IE
        else
            key = e.which; //others

        if (key != 13) {
            return true; 
        } else {
            if (e.preventDefault) e.preventDefault();
            return false;
        }
    },
    
    /********************************************************************************
    * Step 2
    ********************************************************************************/
    /* paymentMethodsBySupplier : {},
    productsBySupplier : {}, */
    //highElecUsageAmount : 20000, /* Annual amounts */
    //lowElecUsageAmount : 1000,
    //highElecSpendingsAmount : 10000,
    //lowElecSpendingsAmount : 1000,
    //elecUsagePeriodId : '',
    //elecSpendingsPeriodId : '',
    //elecPeakId : '',
    //elecOffPeakId : '',
    //elecShoulderId : '',
    //elecHotWaterId : '',
    //elecSpendingsId : '',
    //elecClimateSaverId : '',
    elecWarningsId : 'elecWarnings',
    step2_divResidentialQ1Id : '',
    step2_seId : '',
    
    step2_onload : function() {
        // Show popup Meter Wizard
        // Remove the Meter Wizard until we finish it properly - PJM 15/10/07
        /* var popup1 = new LookCorp.PopupQuote('popupQuote1', 'Not sure? Try our <a href="#" onclick="return LookCorp.SwitchEnergyEngine.step2_showMeterWizard(this);">wizard</a>.',
            { width: 100, height: 57, pointerDirection: 'l', pointerPadding: 10 });
        popup1.positionAt($id(LookCorp.SwitchEnergyEngine.step2_divResidentialQ1Id));
        popup1.show(); */
        
        var t = LookCorp.SwitchEnergyEngine;
        
        /* No longer use a full blocking disclaimer
        $.post(t.callbackUrl,
            { action : 'Step2_ShowDisclaimer', id : t.step2_seId },
            function(value) { // deal with response
                if (value == "True") {
                    // the page has indicated we need to show the disclaimer
                    t.setupBlockUI();
                    $.blockUI({ message : $('#disclaimer')}); // show disclaimer
                }
            }
        );
        */
    },
    
    // Called when the user clicks 'Agree' or 'Disagree' in a disclaimer
    step2_acceptDisclaimer : function() {
        $.unblockUI(); // hides disclaimer
        
        // Notify the server
        $.post(this.callbackUrl,
            {action : 'Step2_AcceptButtonClicked', id : this.step2_seId }
        );

        return false;
    },
    
    step2_preCallback1 : function() {
        $('#step2_loading1').show();        // Show loading
    }, 
    
    step2_postCallback1 : function() {
        $('#step2_loading1').hide();        // Hide loading
    },
        
    step2_preCallback2 : function() {
        $('#step2_loading2').show();        // Show loading
    }, 
    
    step2_postCallback2 : function() {
        $('#step2_loading2').hide();        // Hide loading
    },
        
    step2_preCallback3 : function() {
        $('#step2_loading3').show();        // Show loading
    }, 
    
    step2_postCallback3 : function() {
        $('#step2_loading3').hide();        // Hide loading
    },
    
    step2_wizardResponses : [null, null, null, null], // store the meter wizard responses
    
    // displays the meter wizard (step 1)
    step2_showMeterWizard : function(element) {
        var popupQuote = LookCorp.PopupQuote.getInstance('popupQuote1');
        var text = "";
        
        // step 1 content
        text += '<div class="meterWizardPage">';
        text += '   What type of hot water system do you have? <br />';
        text += '   <input id="hotWaterTypeElec" name="hotWaterType" type="radio" value="Electric" /><label for="hotWaterTypeElec">Electric</label>';
        text += '   <input id="hotWaterTypeGas" name="hotWaterType" type="radio" value="Gas" /><label for="hotWaterTypeGas">Gas</label><br /><br />';
        text += '   Do you run out of hot water from time to time? <br />';
        text += '   <input id="hotWaterGoesColdY" name="hotWaterGoesCold" type="radio" value="Yes" /><label for="hotWaterGoesColdY">Yes</label>';
        text += '   <input id="hotWaterGoesColdN" name="hotWaterGoesCold" type="radio" value="No" /><label for="hotWaterGoesColdN">No</label><br /><br />';
        text += '</div>';
        text += '<input type="button" value="Next &gt;" onclick="LookCorp.SwitchEnergyEngine.step2_showMeterWizard2(this);" />';
        
        popupQuote.text = text;
        popupQuote.width = 210;
        popupQuote.height = 160;
        popupQuote.show();
        return false;
    },
    
    // validates step 1, stores step 1 values, shows step 2
    step2_showMeterWizard2 : function(element) {
        var popupQuote = LookCorp.PopupQuote.getInstance('popupQuote1');
        var hotWaterType = LookCorp.getRadioValue('hotWaterType');
        var hotWaterGoesCold = LookCorp.getRadioValue('hotWaterGoesCold');
        var text = "";
        
        // validation
        if (!hotWaterType) {
            alert("Hot Water Type is required");
            return false;
        }
        if (!hotWaterGoesCold) {
            alert("Do you run out of hot water is required");
            return false;
        }
        
        // store responses
        this.step2_wizardResponses[0] = hotWaterType;
        this.step2_wizardResponses[1] = hotWaterGoesCold;
        
        // step 2 content
        text += '<div class="meterWizardPage">';
        text += '   How many newer style meters do you have with an Electronic display? <br />';
        text += '   <input id="elecDisplay0" name="elecDisplay" type="radio" value="0" /><label for="elecDisplay0">0</label>';
        text += '   <input id="elecDisplay1" name="elecDisplay" type="radio" value="1" /><label for="elecDisplay1">1</label>';
        text += '   <input id="elecDisplay2" name="elecDisplay" type="radio" value="2" /><label for="elecDisplay2">2</label><br /><br />';
        text += '   How many older style meters do you have with a clock-face or dial display?<br />';
        text += '   <input id="oldStyleMeters0" name="oldStyleMeters" type="radio" value="0" /><label for="oldStyleMeters0">0</label>';
        text += '   <input id="oldStyleMeters1" name="oldStyleMeters" type="radio" value="1" /><label for="oldStyleMeters1">1</label>';
        text += '   <input id="oldStyleMeters2" name="oldStyleMeters" type="radio" value="2" /><label for="oldStyleMeters2">2</label>';
        text += '   <input id="oldStyleMeters3" name="oldStyleMeters" type="radio" value="3" /><label for="oldStyleMeters3">3</label>';
        text += '   <input id="oldStyleMeters4" name="oldStyleMeters" type="radio" value="4" /><label for="oldStyleMeters4">4</label><br /><br />';
        text += '</div>';
        text += '<input type="button" value="Next &gt;" onclick="LookCorp.SwitchEnergyEngine.step2_endMeterWizard(this);" />';
        
        popupQuote.text = text;
        popupQuote.height = 190;
        popupQuote.show();
        
        // This was a change event, but IE doesn't fire the change event till the radio loses focus
        $('#elecDisplay0, #elecDisplay1, #elecDisplay2').click(LookCorp.SwitchEnergyEngine.step2_onNewStyleMeterChange);
        
        return false;
    },
    
    // event handler for new style meter options change event
    step2_onNewStyleMeterChange : function(e) {
        var zeroNewMeters = $id('elecDisplay0').checked; // true if the zero option is selected
        var oldStyleMeters = '#oldStyleMeters0, #oldStyleMeters1, #oldStyleMeters2, #oldStyleMeters3, #oldStyleMeters4';
        
        if (zeroNewMeters) {
            $(oldStyleMeters).removeAttr('disabled'); // enable old style meter options
        } else {
            // disable old style meter options
            $('#oldStyleMeters0').attr('checked', 'checked');
            $(oldStyleMeters).attr('disabled', 'disabled');
        }
    },
    
    // validates step2, stores step 2 value, posts answers to server for processing
    step2_endMeterWizard : function(element) {
        var popupQuote = LookCorp.PopupQuote.getInstance('popupQuote1');
        var elecDisplay = LookCorp.getRadioValue('elecDisplay');
        var oldStyleMeters = LookCorp.getRadioValue('oldStyleMeters');
        
        // validation
        if (!elecDisplay) {
            alert('No of meters with electronic display is required');
            return false;
        }
        if (!oldStyleMeters) {
            alert('No of older style meters is required');
            return false;
        }
        
        // store responses
        this.step2_wizardResponses[2] = elecDisplay;
        this.step2_wizardResponses[3] = oldStyleMeters;
        
        // Done message
        popupQuote.text = 'The meter type questions have been answered for you.';
        popupQuote.width = 200;
        popupQuote.height = 57; // original height/width
        popupQuote.show();
        
        // server processing. Its a callback with viewstate included, the response will set the meter type values
        Anthem_InvokeControlMethod(
            this.userControlId,
            'Step2_EndMeterWizard',
            this.step2_wizardResponses,
            function (result) {}
        );
    },
    
    checkElecUsage : function() {
        // Warnings currently not needed. GH 1/5/07
        /* try {
            var usage = 0;
            var period = $(this.elecUsagePeriodId).value;
            var periodStr = 'Year'; 
            var factor = 1;
            var errorMsg = "";
            
            if (period == 'Q') {
                factor = 4;
                periodStr = 'Quarter';
            } else if (period == 'M') {
                factor = 12;
                periodStr = 'Month';
            }
            
            try {
                usage += parseInt($(this.elecPeakId).value, 10);
            } catch (e) {
                // Either the number wasn't an int, or the element isn't visible - Do nothing
            }
            try {
                usage += parseInt($(this.elecOffPeakId).value, 10);
            } catch (e) {
                // Either the number wasn't an int, or the element isn't visible - Do nothing
            }
            try {
                usage += parseInt($(this.elecShoulderId).value, 10);
            } catch (e) {
                // Either the number wasn't an int, or the element isn't visible - Do nothing
            }
            try {
                usage += parseInt($(this.elecHotWaterId).value, 10);
            } catch (e) {
                // Either the number wasn't an int, or the element isn't visible - Do nothing
            }
            try {
                usage += parseInt($(this.elecClimateSaverId).value, 10);
            } catch (e) {
                // Either the number wasn't an int, or the element isn't visible - Do nothing
            }
            
            if (usage * factor < this.lowElecUsageAmount) {
                // low spendings amount
                errorMsg = "A total of " + usage + "kWh seems low for a " + periodStr + " period. Please check the amounts and period.";
            } else if (usage * factor > this.highElecUsageAmount) {
                // high spending amount
                errorMsg = "A total of " + usage + "kWh seems high for a " + periodStr + " period. Please check the amounts and period.";
            }
            
            if (errorMsg) {
                LookCorp.show($(this.elecWarningsId));
                $(this.elecWarningsId).innerHTML = errorMsg;
            } else {
                LookCorp.hide($(this.elecWarningsId));
            }
        } catch (e) {
            // couldn't parse spendings or required element missing - do nothing
        } */
    },
    
    checkElecSpendings : function() {
        // Warnings currently not needed
        /*
        try {
            var spendings = parseInt($(this.elecSpendingsId).value, 10);
            var period = $(this.elecSpendingsPeriodId).value;
            var periodStr = 'Year'; 
            var factor = 1;
            var errorMsg = "";
            
            if (period == 'Q') {
                factor = 4;
                periodStr = 'Quarter';
            } else if (period == 'M') {
                factor = 12;
                periodStr = 'Month';
            }
            
            if (spendings * factor < this.lowElecSpendingsAmount) {
                // low spendings amount
                errorMsg = "$" + spendings + " seems low for a " + periodStr + " period. Please check the amount and period.";
            } else if (spendings * factor > this.highElecSpendingsAmount) {
                // high spending amount
                errorMsg = "$" + spendings + " seems high for a " + periodStr + " period. Please check the amount and period.";
            }
            
            if (errorMsg) {
                LookCorp.show($(this.elecWarningsId));
                $(this.elecWarningsId).innerHTML = errorMsg;
            } else {
                LookCorp.hide($(this.elecWarningsId));
            }
        } catch (e) {
            // couldn't parse spendings or required element missing - do nothing
        }
        */
    },
    
    clearElecWarnings : function(element) {
        var elecWarnings = $('#' + this.elecWarningsId);
        elecWarnings.hide();
        elecWarnings.html("");
    },
    
    // Figure out the range between start/end dates on the form
    // element: either a start date or end date element on the form. This is used to
    //          find the trio of start date, end date and display span
    calculateDateRange : function(ev) {
        var element;
        var targetId;
        var startDate, endDate, diff;
        var billConstraints, message;
        
        if (typeof(ev) == 'string') {
            element = $id(ev);
        } else if (ev.id) {
            element = ev;
        } else {
            element = LookCorp.getEventTarget(ev)
        }

        targetId = element.id;

        var regex = /(.*)step(\d)_dateBill(\d)(Start|End)/; // all about figuring out the prefix asp.net has added
        var matches = targetId.match(regex);
                
        if (matches.length <= 4) {
            // No match, its an unrecognised id type, nothing we can do
            return;
        }
        var prefix = matches[1]; // match[0] is the whole string, match[1] is first part in parenthesies
        var stepNo = matches[2];
        var billNo = matches[3];
        
        var infoElement = $(LookCorp.substitute('#{0}step{1}_pnlDateRangeInfoMsg', prefix, stepNo));
        var errorElement = $(LookCorp.substitute('#{0}step{1}_pnlDateRangeErrorMsg', prefix, stepNo));
        var singleBillInd = ($(LookCorp.substitute("#step{0}_dateBill2Span", stepNo)).length == 0);        
        
        if (!errorElement.length)
            return;
        
        infoElement.html("");
        errorElement.html("");

        if (singleBillInd) {
            billConstraints = [
                {billNo: 1}
            ];
        } else {
            billConstraints = [
                {billNo: 1, name: 'Summer', start: new Date(2007, 12-1, 1), end: new Date(2008, 3-1, 1)}, // Months are 0 indexed, but days are 1 indexed
                {billNo: 2, name: 'Autumn', start: new Date(2007, 3-1, 1), end: new Date(2007, 6-1, 1)},
                {billNo: 3, name: 'Winter', start: new Date(2007, 6-1, 1), end: new Date(2007, 9-1, 1)},
                {billNo: 4, name: 'Spring', start: new Date(2007, 9-1, 1), end: new Date(2007, 12-1, 1)}
            ];
        }
        
        for (var i = 0; i < billConstraints.length; i++) {
            var billConstraint = billConstraints[i];
            var startElement = $(LookCorp.substitute("#{0}step{1}_dateBill{2}Start", prefix, stepNo, billConstraint.billNo));
            var endElement = $(LookCorp.substitute("#{0}step{1}_dateBill{2}End", prefix, stepNo, billConstraint.billNo));
            var spanElement = $(LookCorp.substitute("#step{0}_dateBill{1}Span", stepNo, billConstraint.billNo));        
            if (!startElement.length || !endElement.length || !spanElement.length) {
                continue; // elements aren't present, ignore
            }
            
            startDate = LookCorp.parseDate(startElement.val());
            endDate = LookCorp.parseDate(endElement.val());
            if (!startDate || !endDate) {
                spanElement.html("&nbsp;");
                continue; // dates aren't valid, ignore
            }
            
            diff = endDate.getTime() - startDate.getTime();
            
            // Calculate the period length 
            if (diff >= 0) {
                // 86400000 milliseconds in a day
                var noDays = parseInt((diff + 21600000) / 86400000, 10);  // Add 6 hrs (21600000) to allow for a possible missing daylight saving hour
                spanElement.html("(" + noDays + " day" + ((noDays == 1) ? ")" : "s)"));     
                if ((noDays < 7) || (noDays > 180)) {
                    message = LookCorp.substitute("<p>{0} end date must be within 7 to 180 days of the start date.</p>", (billConstraint.name) ? billConstraint.name : "The");
                    errorElement.html(errorElement.html() + message); // append message
                    continue;
                }
            } else {
                spanElement.html("&nbsp;");
                if (billConstraint.name) {
                    message = LookCorp.substitute("<p>The end date you have entered for the {0} bill is prior to the start date.</p>", billConstraint.name);
                } else {
                    message = "<p>The end date you have entered is prior to the start date.</p>";
                }
                errorElement.html(errorElement.html() + message); // append message
                continue;
            }
            
            if (billConstraint.start && billConstraint.end)
            {
                var midPointDate = new Date();
                midPointDate.setTime(startDate.getTime() + (diff / 2));
                if (!this.dateIsBetweenIgnoreYear(midPointDate, billConstraint.start, billConstraint.end)) {
                    // Month is more than 50% outside the season bounds.
                    // Figure out which season the date is in
                    var suggestedSeason = null;
                    for (var j = 0; j < billConstraints.length; j++) {
                        suggestedSeason = billConstraints[j];
                        if (this.dateIsBetweenIgnoreYear(midPointDate, suggestedSeason.start, suggestedSeason.end)) {
                            break;
                        }
                    }
                    
                    message = LookCorp.substitute("<p>The dates you have entered for the {0} bill indicate a{3} {1} bill. Please enter this bill in the {2} row.</p>",
                        billConstraint.name, suggestedSeason.name, suggestedSeason.name,
                        (suggestedSeason.billNo == 2 ? "n" : "")); // so that "a Winter bill" becomes "an Autumn bill"
                    infoElement.html(infoElement.html() + message); // append message
                }
            }
        }
                
        if (infoElement.html() == "") {
            infoElement.hide();
        } else {
            infoElement.show();
        }
                
        if (errorElement.html() == "") {
            errorElement.hide();
        } else {
            errorElement.show();
        }
    },
    
    // Convert a valid date to our standard format.
    standardFormatDate : function(element) {
        date = LookCorp.parseDate(element.value);    
        if (date) {
            element.value = date.getDate() + "/" + (date.getMonth() + 1) + "/" + LookCorp.getDateYear(date);
        }
    },
    
    // Flimsy function to check if a date is within a range, ignoring the year (except for when the range is across a year boundary)
    dateIsBetweenIgnoreYear : function(value, start, end) {
        //var valueYear = LookCorp.getDateYear(value);
        // Note: the if statement is unecessary - the else case can cover everything
        // I'm leaving it as is, because it helps me get my head around it.
        // Feel free to change (ie. optimise) it at will
        if (start.getYear() == end.getYear()) {
            // easy case - start and end in same year, just get year to be same as value
            value.setYear(LookCorp.getDateYear(start));
            return (start.getTime() <= value.getTime() && value.getTime() <= end.getTime());
        } else {
            // difficult case, range crosses year boundary.
            // use month to figure out which year to check against
            if (value.getMonth() >= start.getMonth()) {
                // use start year
                value.setYear(LookCorp.getDateYear(start));
            } else {
                // use end year
                value.setYear(LookCorp.getDateYear(end));
            }
            return (start.getTime() <= value.getTime() && value.getTime() <= end.getTime());
        }
    },
    
    // Change the size of the consumption fields
    // We shrink the fields when there are 4 or 5 displayed
    step2_changeFieldSizes : function(noOfFields) {
        var styleBlock4Fields = $id('smallConsumptionFields4');
        var styleBlock5Fields = $id('smallConsumptionFields5');
        var newStyleBlock;
        var oldStyleBlock;
        var css;

        switch (noOfFields)
        {
        case 4:
            oldStyleBlock = styleBlock5Fields;
            newStyleBlock = styleBlock4Fields;
            css = '#wizardContent input.usageAmount { width: 70px; } #wizardContent .multiBillHeading { width: 77px; }';
            break;
            
        case 5:
            oldStyleBlock = styleBlock4Fields;
            newStyleBlock = styleBlock5Fields;
            css = '#wizardContent input.usageAmount { width: 60px; margin-right: 4px; } #wizardContent .multiBillHeading { width: 66px; }';
            break;
        }
        
        if (oldStyleBlock)
            oldStyleBlock.parentNode.removeChild(oldStyleBlock);

        if (css && !newStyleBlock) {
            // add style block to reduce field sizes
            var head = document.getElementsByTagName('head')[0];
            newStyleBlock = document.createElement('style');
            newStyleBlock.id = 'smallConsumptionFields' + noOfFields;
            newStyleBlock.setAttribute('type', 'text/css');
            head.appendChild(newStyleBlock);
            
            if (newStyleBlock.styleSheet) { // good ol' faithful IE
                newStyleBlock.styleSheet.cssText = css;
            } else {
                var text = document.createTextNode(css);
                newStyleBlock.appendChild(text);
            }
        }
    },
    
        
    /********************************************************************************
    * Step 3
    ********************************************************************************/
    step3_preCallback1 : function() {
        $('#step3_loading1').show();        // Show loading
    }, 
    
    step3_postCallback1 : function() {
        $('#step3_loading1').hide();        // Hide loading
    },
        
    step3_preCallback2 : function() {
        $('#step3_loading2').show();        // Show loading
    }, 
    
    step3_postCallback2 : function() {
        $('#step3_loading2').hide();        // Hide loading
    },
        
        
    /********************************************************************************
    * Step 4
    ********************************************************************************/
    searchAllId : null,
    
    step4_onload : function() {
        var t = LookCorp.SwitchEnergyEngine; // this != LookCorp.SwitchEnergyEngine, so use shortcut t
        
        // Attach click handlers to checkboxes
        $(".searchOptions input[type='checkbox'], #" + t.searchAllId).each(function() {
            $(this).click(function() { LookCorp.SwitchEnergyEngine.searchOptionsChanged(this); });
        });
        
        // Fix css :hover for sort buttons in IE
		if ($.browser.msie) {
		    $(".sortButtons a").hover(
		        function() { $(this).addClass("IEHover"); $(this).css("text-indent", ""); },
		        function() { $(this).removeClass("IEHover"); $(this).css("text-indent", "0"); }
		    );
		}
    },
    
    searchOptionsChanged : function(obj) {
        if (obj.id == this.searchAllId && obj.checked) {
            // clear the other checks
            $(".searchOptions input[type='checkbox']").each(function() {
                this.checked = false;
            });
        }
        
        var atLeastOneChecked = false;
        $(".searchOptions input[type='checkbox']").each(function() {
            atLeastOneChecked |= this.checked;
        });
        $id(this.searchAllId).checked = !atLeastOneChecked;
    },
    
    /********************************************************************************
     * Step 5
     *******************************************************************************/
    step5_hfEmailAddressId : null,
    step5_txtEmailAddressId : null,
    step5_eventTarget : '',
    
    step5_launchCalculator : function(linkElement) {
        return LookCorp.popHelp(linkElement, 800); // leave out height so it gets set automatically
    },
    
    // Set the hidden fields to the values given and do a postback
    step5_applyPrice : function() {        
        window.focus();
        
        __doPostBack(this.step5_eventTarget, '');
    },
    
    // Toggles the details summary above the search results
    step5_showHideDetails : function(element, div) {
        element = $(element);
        var text = element.html();
        if (text.substring(0, 4) == "Hide") {
            $('#' + div).slideUp('fast');
            element.html(element.html().replace("Hide", "Show"));
        } else {
            $('#' + div).slideDown('normal');
            element.html(element.html().replace("Show", "Hide"));
        }
        
        return false;
    }, 
    
    // Stores supplier data
    step5_supplierDetails : null,
    
    step5_load : function() {
        var t = LookCorp.SwitchEnergyEngine; // a different 'this'
        
        // Scroll page
        var pageHeading = $('.pageHeading').get(0);
        if (pageHeading) pageHeading.scrollIntoView();

        // Do callback to get supplier details
        /* Now done inline. 
        Anthem_InvokeControlMethod(
		        t.userControlId,
		        'Step5_GetSupplierInfos', // function name
		        [], // params
		        function(result) {
		            if (result.value) {
		                t.step5_supplierDetails = eval('(' + result.value + ')');
		            }
		        }); */
		t.step5_resultsTableLoad();
    },
    
    step5_resultsTableLoad : function() {
        $('table.results tr td:first-child img').hover(
            function(ev) {
                // Mouse enter
                //var span = $('span:first-child', this).get(0);
                var supplierId = this.parentNode.className.replace("supplier", "");
                
                // Go 1 parent up in case there's link there
                if (!supplierId) supplierId = this.parentNode.parentNode.className.replace("supplier", "");
                
                // Init the popup quote
                var popupQuote = LookCorp.PopupQuote.getInstance('popupQuote');
                if (!popupQuote) {
                    // Create popup quote
                    popupQuote = new LookCorp.PopupQuote('popupQuote', '',
                                {width: 400, height: 160, pointerDirection: 'l', pointerPadding: 15, showClose: false, cssClass: 'supplierQuote'});
                }
                
                // show a nice div here
                if (LookCorp.SwitchEnergyEngine.step5_supplierDetails && LookCorp.SwitchEnergyEngine.step5_supplierDetails['s' + supplierId]) {
                    var supplierDetails = LookCorp.SwitchEnergyEngine.step5_supplierDetails['s' + supplierId];
                    popupQuote.height = (supplierDetails.length > 400) ? parseInt(supplierDetails.length / 2.4) : 160;   // This is very rough and may need improvement
                    popupQuote.width = 400;
                    popupQuote.text = supplierDetails;
                    popupQuote.positionAt(this);
                    popupQuote.show();
                } else {
                    popupQuote.text = '<p>Supplier information not available</p>';
                    popupQuote.height = 50;
                    popupQuote.width = 300;
                    popupQuote.positionAt(this);
                    popupQuote.show();
                }
            },
            function(ev) {
                // Mouse exit
                
                // hide nice div
                var popupQuote = LookCorp.PopupQuote.getInstance('popupQuote');
                if (popupQuote) {
                    popupQuote.hide();
                }
            });
    },
    
    step5_saveSearch : function(elem) {
        this.setupBlockUI();
        
        try {
            $.blockUI({message : $('#saveResults')}); // show disclaimer
        } catch (e) {
            // IE sometimes errors when blockUI tries to focus on an element that is hidden
            // eg. after the search has already been saved
            // Note: this try/catch doesn't seem to save it. Not sure it is catchable at all.
        }
        return false;
    },
    
    step5_saveSearchNow : function(elem) {
        // Validate entry
        var emailAddress = $id('step5_txtEmailAddress').value;
        emailAddress = LookCorp.trimString(emailAddress);
        
        if (emailAddress.length == 0) {
            alert("Please correct the following:\n   * Email address is required");
            return false;
        }
        if (!/^\w[\w._%-+]*@([\w-]+\.)+\w{2,6}$/.test(emailAddress)) {
            alert("Please correct the following:\n   * Email address must be valid");
            return false;
        }
        
        LookCorp.setElementText(elem, "Saving...");
        
        Anthem_InvokeControlMethod(
            this.userControlId,
	        'Step5_SaveResults', // function name
	        [emailAddress], // params
	        function(result) { // process result
	            if (result.value) {
	                var jsonResult = eval('(' + result.value + ')');
	                
	                if (jsonResult.error) {
	                    // show error
	                    $('#step5_preSave').hide();
	                    $('#step5_saveError').show();
	                    return false;
	                }
	                
	                $('#step5_searchReference').text(jsonResult.uniqueId);
	                $('#step5_emailAddress').text(jsonResult.emailAddress + " "); // IE loses the space after the span
	                if (jsonResult.filterWarning) {
	                    $('#step5_filteredEmailAddress').text(jsonResult.filterWarning);
	                } else {
	                    $('#step5_filteredEmailAddress').hide();
	                }
	                
                    $('#step5_preSave').hide();
                    $('#step5_postSave').show();
	            } else {
	                // Show error
	                $('#step5_preSave').hide();
	                $('#step5_saveError').show();
	            }
	        }
	    );
	    
	    return false;
    },
    
    step5_submitSavePopup : function() {
        var t = LookCorp.SwitchEnergyEngine;
        $id(t.step5_hfEmailAddressId).value = $id(t.step5_txtEmailAddressId).value;
    },
    
    step5_postSubmitSave : function() {
        
    },
    
    step5_closeSavePopup : function() {
        $.unblockUI(); // hides popup
        return false;
    },
    
    /********************************************************************************
    * Step 5b - Product Info
    ********************************************************************************/
    step5b_analyticsPrefix : null,
    step5b_initialTab : null,
    step5b_load : function() {
        var t = LookCorp.SwitchEnergyEngine;
        
        // Hide all panels except first (to make sure)
        $('div.productInfoContent > div:not(:first-child)').hide();
        
        // Scroll page
        var pageHeading = $('.pageHeading').get(0);
        if (pageHeading) pageHeading.scrollIntoView();
    
        $('ul.resultTabs a').click(
            function(ev) {
                // Tab link clicked
                ev.preventDefault();
                
                // set 'active' class on this tab
                $('ul.resultTabs li').removeClass('active');
                var jThis = $(this);
                this.parentNode.className = 'active';
                
                // show the right tab
                var tabId = this.href.substring(this.href.indexOf('#') + 1); // id is the anchor name
                $('div.productInfoContent > div').not('#' + tabId).hide();
                $('#' + tabId).show();
                
                if (t.step5b_analyticsPrefix && typeof(pageTracker) != "undefined") {
                    pageTracker._trackPageview(t.step5b_analyticsPrefix + tabId);
                }
            }
        );
        
        if (t.step5b_initialTab) {
            $("ul.resultTabs a[href$='#" + t.step5b_initialTab + "']").click(); // $= means ends with
        }
    },
    
    /********************************************************************************
    * Step 6
    ********************************************************************************/
    userControlId : null,
    step6_timeout : null,
    addressDivId : 'addressMessage',
    step6_txtAddress1Id : null,
    step6_selectedSupplierId : '',
    
    step6_load : function() {
        t = LookCorp.SwitchEnergyEngine;

        // Scroll page
        var pageHeading = $('.pageHeading').get(0);
        if (pageHeading) pageHeading.scrollIntoView();

        t.step6_showHideOtherTitle(0);
        t.step6_showHideOtherTitle(1);
        t.step6_attachSkipEvents();
        /* Turn off address lookup bec. DataTools no longer operational
        t.step6_addAddressFieldHandlers();
        
        var address1Element = $id(t.step6_txtAddress1Id);
        if (address1Element) {
            if (address1Element.value != '') {
                LookCorp.SwitchEnergyEngine.step6_checkAddressNow(address1Element);
            } else {
                var popup1 = new LookCorp.PopupQuote('addressPopupQuote', 'When you start typing, address suggestions will appear here.',
                    { width: 200, height: 60, pointerDirection: 'l', pointerPadding: 15 });
                popup1.positionAt(address1Element);
                popup1.show();
            }
        }
        */
        
        // Business phone no area code disabling
        var phoneNoType = $('.phoneNoType');
        if (phoneNoType.length > 0) {
            t.step6_ddlBusinessPhoneNoType_change(phoneNoType[0]);
        }
    },
    
    step6_preCallback1 : function() {
        $('#step6_loading1').show();        // Show loading
    }, 
    
    step6_postCallback1 : function() {
        $('#step6_loading1').hide();        // Hide loading
    },
        
    step6_preCallback2 : function() {
        $('#step6_loading2').show();        // Show loading
    }, 
    
    step6_postCallback2 : function() {
        $('#step6_loading2').hide();        // Hide loading
    },
        
    step6_preCallback3 : function() {
        $('#step6_loading3').show();        // Show loading
    }, 
    
    step6_postCallback3 : function() {
        $('#step6_loading3').hide();        // Hide loading
    },
        
    step6_preCallback4 : function() {
        $('#step6_loading4').show();        // Show loading
    }, 
    
    step6_postCallback4 : function() {
        $('#step6_loading4').hide();        // Hide loading
    },
            
    step6_preCallback5 : function() {
        $('#step6_loading5').show();        // Show loading
    }, 
    
    step6_postCallback5 : function() {
        $('#step6_loading5').hide();        // Hide loading
    },
                
    step6_preCallback6 : function() {
        $('#step6_loading6').show();        // Show loading
    }, 
    
    step6_postCallback6 : function() {
        $('#step6_loading6').hide();        // Hide loading
    },
    
    /* Gets called when a key is pressed in an address field */
    step6_checkAddress : function(element) {
        // Cancel previous timer (if any)
        if (this.step6_timeout) {
            clearTimeout(this.step6_timeout);
        }
        
        // Set a timer to do step6_checkAddressNow
        this.step6_timeout = setTimeout(function() { LookCorp.SwitchEnergyEngine.step6_checkAddressNow(element); }, 500);
        
        var verifiedElem = (element.id.indexOf("Previous") > 0) ? $('#previousAddressVerified') : $('#addressVerified');
        verifiedElem.html(''); // Clear 'address verified' text
    },
    
    /* Gets called when there's been a gap in the user's typing */
    step6_checkAddressNow : function(element) {
        var address1Elem, address2Elem, localityElem, postcodeElem, stateElem;
        var matches, elementPrefix, verifiedElem;
        
        this.step6_timeout = null;
        
        // figure out element ids
        matches = /.+_txt(?:Previous)?/.exec(element.id);
        if (matches && matches.length > 0) {
            elementPrefix = matches[0];
        } else {
            matches = /.+_ddl(?:Previous)?/.exec(element.id);
            if (matches && matches.length != 0) {
                elementPrefix = matches[0].replace('ddl', 'txt');
            } else {
                // Element id isn't what we expected
                return;
            }
        }
        
        address1Elem = $id(elementPrefix + 'Address1');
        address2Elem = $id(elementPrefix + 'Address2');
        localityElem = $id(elementPrefix + 'Suburb');
        postcodeElem = $id(elementPrefix + 'Postcode');
        stateElem = $id(elementPrefix.replace('txt', 'ddl') + 'State');
        verifiedElem = (elementPrefix.indexOf("Previous") > 0) ? $id('previousAddressVerified') : $id('addressVerified');
        
        if (!address1Elem || !address2Elem || !localityElem || !postcodeElem || !stateElem || !this.callbackUrl) {
            // at least one element we need is missing
            return;
        }
        
        if (!address1Elem.value || !localityElem.value || !postcodeElem.value) {
            // We need at least these three to get address suggestions (its a datatools quirk)
            return;
        }
        
        // Find popup quotes
        var initialPopupQuote = LookCorp.PopupQuote.getInstance('addressPopupQuote');
        var addressPopupQuote = LookCorp.PopupQuote.getInstance(t.addressDivId);
        
        // Show loading... in initial popup (if visible)
        if (initialPopupQuote && initialPopupQuote.visible) {
            initialPopupQuote.replaceText("Loading...");
        }
        
        $('#addressListLoading').show();
        
        // Do callback to get address suggestions
        $.post(this.callbackUrl,
            { action : 'Step6_GetAddressCheck', al1 : address1Elem.value, al2 : address2Elem.value, 
              lc : localityElem.value, pc : postcodeElem.value, st : stateElem.value },
            function(value) { // process result
			        //var addressList = $id(LookCorp.SwitchEnergyEngine.addressDivId);
			        var t = LookCorp.SwitchEnergyEngine;
			        
			        // hide quote that says 'Address suggestions will appear here'
                    if (initialPopupQuote) initialPopupQuote.hide();

                    // If the popup quote is visible, make sure it points at the right place
                    if (addressPopupQuote && addressPopupQuote.targetElement != address1Elem) {
                        addressPopupQuote.hide();
                    }

                    // Find the popup quote that shows address suggestions
                    if (!addressPopupQuote) { // create it if necessary
                        addressPopupQuote = new LookCorp.PopupQuote(t.addressDivId, value,
                                {width: 425, height: 200, pointerDirection: 'l', pointerPadding: 15});
                    }
                    
                    if (value) {
                        if ((value.length > 9) && (value.substr(0, 9) == 'VERIFIED:')) {
                            var addressValueList = value.substr(9).split('|');
                            if (addressValueList.length == 4) {
                                // Don't set address1Elem and address2Elem as the user may be confused to see their text change
                                localityElem.value = addressValueList[1];
                                postcodeElem.value = addressValueList[3];
                                stateElem.value = addressValueList[2];
                            }
                            LookCorp.setElementText(verifiedElem, 'Address Verified');
                            addressPopupQuote.hide();
                        } else {
                            if (addressPopupQuote.visible) {
                                addressPopupQuote.replaceText(value);
                            } else {
                                addressPopupQuote.text = value;
                                addressPopupQuote.positionAt(address1Elem);
                                addressPopupQuote.show();
                            }
                            LookCorp.SwitchEnergyEngine.step6_addAddressClickHandlers($id(addressPopupQuote.id), elementPrefix);
                            // stop the extra callback due to blurring the input field when the close image is clicked
                            $('.close', $id(t.addressDivId)).click(function() { var to = LookCorp.SwitchEnergyEngine.step6_timeout; if (to != null) clearTimeout(to); });
                        }
                    } else {
                        addressPopupQuote.hide();
                    }
		        }
		    );  
        
        /* 
        Anthem_InvokeControlMethodStateless(
		        this.userControlId,
		        'Step6_GetAddressCheck', // function name
		        [address1Elem.value, address2Elem.value, localityElem.value, postcodeElem.value, stateElem.value], // params
		        function(result) { // process result
			        //var addressList = $id(LookCorp.SwitchEnergyEngine.addressDivId);
			        var t = LookCorp.SwitchEnergyEngine;
			        
			        // hide quote that says 'Address suggestions will appear here'
                    if (initialPopupQuote) initialPopupQuote.hide();

                    // If the popup quote is visible, make sure it points at the right place
                    if (addressPopupQuote && addressPopupQuote.targetElement != address1Elem) {
                        addressPopupQuote.hide();
                    }

                    // Find the popup quote that shows address suggestions
                    if (!addressPopupQuote) { // create it if necessary
                        addressPopupQuote = new LookCorp.PopupQuote(t.addressDivId, result.value,
                                {width: 425, height: 200, pointerDirection: 'l', pointerPadding: 15});
                    }
                    
                    if (result.value) {
                        if ((result.value.length > 9) && (result.value.substr(0, 9) == 'VERIFIED:')) {
                            var addressValueList = result.value.substr(9).split('|');
                            if (addressValueList.length == 4) {
                                // Don't set address1Elem and address2Elem as the user may be confused to see their text change
                                localityElem.value = addressValueList[1];
                                postcodeElem.value = addressValueList[3];
                                stateElem.value = addressValueList[2];
                            }
                            LookCorp.setElementText(verifiedElem, 'Address Verified');
                            addressPopupQuote.hide();
                        } else {
                            if (addressPopupQuote.visible) {
                                addressPopupQuote.replaceText(result.value);
                            } else {
                                addressPopupQuote.text = result.value;
                                addressPopupQuote.positionAt(address1Elem);
                                addressPopupQuote.show();
                            }
                            LookCorp.SwitchEnergyEngine.step6_addAddressClickHandlers($id(addressPopupQuote.id), elementPrefix);
                            // stop the extra callback due to blurring the input field when the close image is clicked
                            $('.close', $id(t.addressDivId)).click(function() { var to = LookCorp.SwitchEnergyEngine.step6_timeout; if (to != null) clearTimeout(to); });
                        }
                    } else {
                        addressPopupQuote.hide();
                    }
		        }
	        ); */
    },
    
    /* add click handlers to the address links returned by the callback */
    step6_addAddressClickHandlers : function(addressList, elementPrefix) {
        $("ul a", addressList).each(function() {
            $(this).click(function(e) { LookCorp.SwitchEnergyEngine.step6_changeAddress(e.target, elementPrefix); e.preventDefault(); });
        });
    },
    
    /* Called when a suggested address is clicked */
    step6_changeAddress : function(element, elementPrefix) {
        var address1Elem, address2Elem, localityElem, postcodeElem, stateElem, newAddressElem, verifiedElem;
        var addressValueList = element.getAttribute('href');
        
        // clear timer to make sure another callback doesn't happen
        if (this.step6_timeout != null)
            clearTimeout(this.step6_timeout);
        
        // Get address values, which are stored in the anchor part of the link
        addressValueList = decodeURIComponent(addressValueList.substring(addressValueList.indexOf("#") + 1)); //some browsers prepend the page url, this gives us just the part after #
        
        address1Elem = $id(elementPrefix + 'Address1');
        address2Elem = $id(elementPrefix + 'Address2');
        localityElem = $id(elementPrefix + 'Suburb');
        postcodeElem = $id(elementPrefix + 'Postcode');
        stateElem = $id(elementPrefix.replace('txt', 'ddl') + 'State');
        //newAddressElem = $id(elementPrefix.replace('txt', 'chk') + 'NewAddress');
        verifiedElem = (elementPrefix.indexOf("Previous") > 0) ? $id('previousAddressVerified') : $id('addressVerified');
        
        if (addressValueList != "newAddress") {
            addressValueList = addressValueList.split('|');
            address1Elem.value = addressValueList[0];
            address2Elem.value = '';
            localityElem.value = addressValueList[1];
            postcodeElem.value = addressValueList[3];
            stateElem.value = addressValueList[2];
            LookCorp.setElementText(verifiedElem, 'Address Verified');
        }
        
        this.step6_closeAddressPopup();
    },
    
    /* add event handlers to the address fields */
    step6_addAddressFieldHandlers : function() {
        var replacements = ["txtAddress1", "txtAddress2", "txtSuburb", "txtPostcode", "ddlState",
                            "txtPreviousAddress1", "txtPreviousAddress2", "txtPreviousSuburb", "txtPreviousPostcode", "ddlPreviousState" ];
        var address1Id = LookCorp.SwitchEnergyEngine.step6_txtAddress1Id;
        
        // address1Id is the full id of the first field, ASP.net prefix & all.
        // we loop through each of the 'replacements' prepending the bit needed to get the full id
        for (var i = 0; i < replacements.length; i++) {
            var element = $id(address1Id.replace("txtAddress1", replacements[i]));
            if (element) {
                element.onchange = function() { LookCorp.SwitchEnergyEngine.step6_checkAddress(this); };
                if (element.id.indexOf("txt") >= 0) {
                    element.onkeyup = function() { LookCorp.SwitchEnergyEngine.step6_checkAddress(this); };
                    element.setAttribute("autocomplete", "off");
                }
            }
        }
        
        /* Used to have a checkbox that indicated a new address. Don't require this at the moment.
        var checks = ["chkNewAddress", "chkPreviousNewAddress"];
        for (var i = 0; i < checks.length; i++) {
            var element = $id(address1Id.replace("txtAddress1", checks[i]));
            if (element) {
                element.onchange = function() { LookCorp.SwitchEnergyEngine.step6_newAddressChange(this); };
            }
        }
        */
    },
    
    /* Called when the 'my address is new' checkbox is clicked
    step6_newAddressChange : function(element) {
        if (element.checked) {
            var verifiedElem = (element.id.indexOf("Previous") > 0) ? $('#previousAddressVerified') : $('#addressVerified');
            verifiedElem.html(''); // Clear 'address verified' text
        }
    },*/
    
    // Called when the close button in the address popup is clicked.
    step6_closeAddressPopup : function() {
        var addressPopupQuote = LookCorp.PopupQuote.getInstance(this.addressDivId);
        if (addressPopupQuote) addressPopupQuote.hide();
        
        if (this.step6_timeout != null) clearTimeout(this.step6_timeout);
        
//        var addressDiv = $('#' + this.addressDivId);
//        
//        if (this.step6_timeout != null)
//            clearTimeout(this.step6_timeout);
//        
//        if (addressDiv.length) {
//            addressDiv.remove();
//        }
        
        return false;
    },
    
    /* Banking details */
    step6_skipFields : [],
    step6_attachSkipEvents : function() {
        // add event handlers to credit card no fields / bsb fields so that the cursor goes to the next
        // field when the max length for each is reached
        var skipFields = LookCorp.SwitchEnergyEngine.step6_skipFields;
        for (var i = 0; i < skipFields.length; i++) {
            var elem = $id(skipFields[i]);
            if (elem) {
                LookCorp.attachEventListener(elem, 'keyup', LookCorp.SwitchEnergyEngine.step6_skipNext);
            }
        }
    },
    
    step6_skipNext : function(e) {
        // only continue if key was a number (48-57 are normal numbers, 96-105 are keypad numbers).
        // This stops problems with using the arrow/tab keys
        if (!(e.keyCode >= 48 && e.keyCode <= 57) && !(e.keyCode >= 96 && e.keyCode <= 105)) return;
        var element = LookCorp.getEventTarget(e);
        try {
            if (element.value.length == element.maxLength) {
                // focus the next element, found by incrementing the no at the end of the element's id
                var no = parseInt(element.id.charAt(element.id.length - 1));
                $id(element.id.substring(0, element.id.length - 1) + (no + 1)).focus();
            }
        } catch (e) {
            // either id isn't there, isn't the right format, or the next element doesn't exist
            // nothing to do
        }
    },
    
    // Validate the move in date
    step6_validateMoveInDate : function(element) {
        var moveInElement, errorElement;

        if (typeof(element) == 'string') {
            moveInElement = $('#' + element);// + '_textbox');    // Add "_textbox" bec. Look:DatePicker adds this
        } else {
            moveInElement = $('#' + element.id);
        }

        if (!moveInElement.length)
            return;
            
        errorElement = $(moveInElement[0].id.replace(/^(.*)step6_dateMoveIn(.*)$/, '#$1step6_pnlDateRangeErrorMsg'));
        
        if (!errorElement.length)
            return;
            
        errorElement.html("");
        
        var dateStr = LookCorp.trimString(moveInElement.val());
        
        if (dateStr.length > 0) {
            var moveInDate = LookCorp.parseDate(dateStr);
            var stateElement = $id(this.step6_txtAddress1Id.replace('step6_txtAddress1', 'step6_ddlState'));
            var stateStr = stateElement.value;
            if (moveInDate) {
                // Use callback to validate date
                $.post(this.callbackUrl,
                    { action : 'Step6_MoveInDateIsValid', moveInDate : dateStr, 
                      state : stateStr, supplierId : this.step6_selectedSupplierId },
                    function(value) {
		                if (value) {
		                    errorElement.html("<p>" + value + "</p>");
		                    errorElement.show();
		                }
		            }
		        );
                
                /*
                Anthem_InvokeControlMethodStateless(
                    this.userControlId,
		            'Step6_MoveInDateIsValid',
		            [dateStr],
		            function(result) {
		                if (result.value) {
		                    errorElement.html("<p>" + result.value + "</p>");
		                    errorElement.show();
		                }
		            }
                ); */
            } else {
                errorElement.html("<p>Invalid move in date.</p>");
            }
        }
                
        if (errorElement.html() == "") {
            errorElement.hide();
        } else {
            errorElement.show();
        }
    },
    
    step6_ddlTitle : [],
    step6_showHideOtherTitle : function(titleIdx) {
        var ddlTitle = LookCorp.SwitchEnergyEngine.step6_ddlTitle;
        
        var ddlTitleSel = '#' + ddlTitle[titleIdx];
        var txtOtherTitle = $(ddlTitleSel.replace("_ddlTitle", "_txtOtherTitle"));
        
        if ($(ddlTitleSel).val() == "Other") {
            txtOtherTitle.show();
        } else {
            txtOtherTitle.hide();
        }
    },
        
    // Validate the credit card number
    step6_validateCC : function(source, args) {
        var elem1, elem2, elem3, elem4, ccNum;
        
        elem1 = source;
        elem2 = $id(source.id.substring(0, source.id.length - 1) + "2");
        elem3 = $id(source.id.substring(0, source.id.length - 1) + "3");
        elem4 = $id(source.id.substring(0, source.id.length - 1) + "4");
        
        ccNum = elem1.value + elem2.value + elem3.value + elem4.value;
        args.IsValid = LookCorp.validateCC(ccNum);
    },
        
    // Validate the ABN number
    step6_validateABN : function(source, args) {
        var elem1, elem2, elem3, elem4, abnNum, controlId;
        
        if (!source.controltovalidate) {
            args.IsValid = false;
            return;
        }
        
        controlId = source.controltovalidate.substring(0, source.controltovalidate.length - 1);
        elem1 = $id(controlId + "1");
        elem2 = $id(controlId + "2");
        elem3 = $id(controlId + "3");
        elem4 = $id(controlId + "4");
        
        abnNum = elem1.value + elem2.value + elem3.value + elem4.value;
        args.IsValid = LookCorp.validateABN(abnNum);
    },
        
    // Validate the phone numbers
    step6_validatePhoneNo : function(source, args) {
        var controlId;
        var elemAdditionalPhone;
        var elemMobilePhone;
        
        if (!source.controltovalidate) {
            args.IsValid = false;
            return;
        }
        
        elemAdditionalPhone = $id(source.controltovalidate);
        elemMobilePhone = $id(source.controltovalidate.replace("_txtPhoneNo", "_txtMobilePhoneNo"));
        
        args.IsValid = (elemAdditionalPhone && LookCorp.trimString(elemAdditionalPhone.value).length > 0) || 
                       (elemMobilePhone && LookCorp.trimString(elemMobilePhone.value).length > 0);
    },
    
    step6_ddlBusinessPhoneNoType_change : function(elem) {
        var areaCodeElem = $('select.areaCode', elem.parentNode).get(0);
        
        // Make sure we don't have the residential one
        if (!areaCodeElem || areaCodeElem.id.indexOf('BusinessPhoneNoArea') <= 0) return;
        
        var phoneNoType = $(elem).val();
        
        if (phoneNoType == "D") {
            // force area to 04
            for (var i = 0; i < areaCodeElem.options.length; i++) {
                var optionElement = areaCodeElem.options[i];
                optionElement.disabled = (optionElement.value != "04");
            }
            
            // The browser won't do this for us
            $(areaCodeElem).val("04");
        } else {
            // force area to non 04
            for (var i = 0; i < areaCodeElem.options.length; i++) {
                var optionElement = areaCodeElem.options[i];
                optionElement.disabled = (optionElement.value == "04");
            }
            
            // The browser won't do this for us
            if ($(areaCodeElem).val() == "04") {
                areaCodeElem.selectedIndex = 0;
            }
        }
    },
    
    step6_validateNMI : function(source, args) {
        var nmi; // Don't know why, but giving nmi a value on this line wasn't working in firefox. Argh!
        nmi = args.Value;
        
        if (nmi.length != 11)
        {
            args.IsValid = false; // NMIs must be 11 digits long
            return;
        }

        var checksum = 0;
        var rawNmi = nmi.substring(0, nmi.length - 1); // NMI without the check digit
        var v = 0;
        var multiply = true;

        // Calculate checksum
        for (var i = rawNmi.length; i > 0; i--)
        {
            var d = rawNmi.charCodeAt(i - 1);
            if (multiply)
            {
                d *= 2;
            }
            multiply = !multiply;
            while (d > 0)
            {
                v += d % 10;
                d = Math.floor(d / 10); // Integer division
            }
        }
        checksum = (10 - (v % 10)) % 10;

        args.IsValid = (nmi == rawNmi + checksum);
    },
    
    /********************************************************************************
    * Step 7
    ********************************************************************************/
    step7_load : function() {
        // Scroll page
        var pageHeading = $('.pageHeading').get(0);
        if (pageHeading) pageHeading.scrollIntoView();
    },

//    step7_nextButtonId : '',
//    step7_changeNextButton : function() {
//        var button = $id(LookCorp.SwitchEnergyEngine.step7_nextButtonId);
//        if (button) {
//            // Ideally, these values are stored somewhere else
//            button.value = 'SWITCH NOW';
//            button.className = 'WizardNavButtonFinal';
//        }
//    },
    
    /********************************************************************************
    * Step 9
    ********************************************************************************/
    step9_load : function() {
    },

    step9_txtName1Id : null,
    step9_preCallback : function() {
        // Show loading
        $('#step9_loading').show();
    }, 
    
    step9_postCallback : function() {
        // Hide loading
        if ($id('step9_loading')) {
            $('#step9_loading').hide();
        }
    },
    
    step9_emailCallback : function(data) {
        var prefix = this.step9_txtName1Id.replace(/Name1/, "");
        
        // Loop a max of 10 times
        for (var i = 0; i < data.length; i++) {
            var entry = data[i];
            var nameElement = $id(prefix + "Name" + (i + 1));
            var emailElement = $id(prefix + "Email" + (i + 1));
            
            if (nameElement && emailElement) {
                nameElement.value = entry[0];
                emailElement.value = entry[1];
            } else {
                break;
            }
        }
    }
};

// Plaxo callback
function onABCommComplete(data) {
    LookCorp.SwitchEnergyEngine.step9_emailCallback(data);
};








