jQuery(document).ready(function($){
    jQuery('input, select, textarea','.uniForm').focus(function(){
         jQuery('.uniForm', '#survey ').find('.focused').removeClass('focused');
         jQuery(this).parents().filter('.ctrlHolder:first').addClass('focused');            
    });
    
    $('#bill').focus();
    
    Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

    
    function checkRecommendation()
    {
        var recommendation = 0;
        var bill = parseInt($('#bill').val());
        var largehome = $('input[name="homearea"]:checked').val(); //size
        var centralac = $('input[name="central-ac"]:checked').val(); //pump
        
        if(bill>= 175 && largehome == "yes" && centralac == "yes")
            recommendation = 1;
        if(bill>= 175 && largehome == "no" && centralac == "yes")
            recommendation = 2;
        if(bill>= 175 && largehome == "yes" && centralac == "no")
            recommendation = 3;
        if(bill<= 100 && largehome == "no" && centralac == "no")
            recommendation = 4;
        
        return recommendation;
    }
    
    function extraRecommendation()
    {
        var count = 0;
        var recommendation = 0;
        count = $('#secondQ input:checkbox:checked').length;
        
        if(count <= 1)
            recommendation = 5;
        if(count >= 2 && count <= 4)
            recommendation = 6;
        if(count >= 5 && count <= 7)
            recommendation = 7;
        if(count >= 8 && count <= 9)
            recommendation = 8;
        
        return recommendation;
    }
    
    function recommendationPercentage(index)
    {
        var r = new Array(.15, .12, .12, .05, .05, .07, .12, .15);
        return r[index-1];
    }
    
    function finalCalculation()
    {
        var finalRecommendation = checkRecommendation();
        if(finalRecommendation == 0)
            finalRecommendation = extraRecommendation();
        
        var bill = parseInt($('#bill').val());
        var product_cost = 297.00;
        var discounted_product_cost = 247.00;
        var estimated_saving = recommendationPercentage(finalRecommendation);
        var saving_month = bill*estimated_saving;
        var roi_month = Math.ceil(product_cost/saving_month);
        var roi_month_discounted = Math.round(discounted_product_cost/saving_month);
        var roi_relevant = 0;
        var price_relevant = 0;
        var year7 = (saving_month*84).formatMoney(0, '.', ',');
        var year25 = (saving_month*300).formatMoney(0, '.', ',');
        var appliances_count = $('#secondQ input:radio[value="yes"]:checked').length;
        
        if(roi_month>12 && roi_month <= 18)
        {
            roi_relevant = roi_month_discounted;
            price_relevant = discounted_product_cost;
        }
        else
        {
            roi_relevant = roi_month;
            price_relevant = product_cost;
        }
        
        
        if(roi_month <= 6)
            $('#heading3').html("<h2>The Zap Box Is <strong>HIGHLY Recommended</strong>. You're Going To Love The Results!</h2>");
        if(roi_month > 6 && roi_month <= 12)
            $('#heading3').html("<h2>The Zap Box Is a <strong>VERY Worthwhile</strong> Investment.</h2>");
        if(roi_month > 12 && roi_month <= 18)
            $('#heading3').html("<h2>The Zap Box Will <strong>Work GREAT</strong> for you - But Only If We Give You a <strong>$50 Discount</strong>.</h2>");
        if(roi_month > 19)
            $('#heading3').html("<h2>Unfortunately The Zap Box Is <strong>NOT Recommended</strong> for You!</h2>");
        
        //Recommendations as paragraph 1 -- result-para1
        if(finalRecommendation == 1)
            $('#result-para1').html("<p>That's great news for you.  You're in a large property that uses appliances that are not going to be particularly efficient.</p><p><br/>Your electric bill is already significantly above-average and you should expect <strong>savings of at least 15%.</strong></p>");
        if(finalRecommendation == 2)
            $('#result-para1').html("<p>Wow, for a relatively small home your electric bill is very high. This is probably because your air condition or heat pumps are running inefficiently and The <strong>Zap Box can certainly help you save money<strong> here.</p><p><br/>It's likely that you'll see <strong>savings of at least 12%</strong>.</p>");
        if(finalRecommendation == 3)
            $('#result-para1').html("<p>It seems like you probably have quite energy-efficient appliances in your home already however your electric bill is still very high and the very size of your home means that you'll be suffering from losses in your wiring.</p><p>You probably won't make large savings on your air conditioning or heat pump but <strong>there's a lot of opportunity to save electricity on other appliances</strong> in your home that use motors such as fridges, freezers, washers, dryers, dishwashers etc.</p><p><br/>It's likely that you'll make <strong>savings of at least 12%</strong>.</p>");
        if(finalRecommendation == 4)
            $('#result-para1').html("<p>As much as I hate to lose a sale, based on the information you've given me <strong>I DO NOT recommend The Zap Box for your home</strong>.</p><p>Although you should expect The Zap Box to work for you for at least 7 years, <strong>it's going to take you a long time for you to save enough money</strong> from The Zap Box for it to pay for itself. </p><p><strong>Savings will only be about 5%</strong>.</p>");
        if(finalRecommendation == 5)
            $('#result-para1').html("<p><strong>You don't really have enough 'inductive' appliances in your home</strong> for The Zap Box to be effective. Although you'll certain gain good savings over many years <strong>buying a zap box is not a good short (or medium) term investment.</strong></p><p><strong>Savings will only be about 5%</strong>.</p>");
        if(finalRecommendation == 6)
            $('#result-para1').html("<p>Your electric bill is quite modest but <strong>you do have a number of appliances that The Zap Box will work with</strong>.</p><p><br/><strong>You're likely to see savings of around 7%</strong>.</p>");
        if(finalRecommendation == 7)
            $('#result-para1').html("<p>Although your electric bill is about average, <strong>you do have a lot of appliances in your home which The Zap Box will definitely save money on.</strong></p><p><strong>We estimate savings to be around 12%</strong>.</p>");
        if(finalRecommendation == 8)
            $('#result-para1').html("<p>Wow, <strong>you're one of the lucky few who has a house full of appliances that The Zap Box can help you with</strong>. The more of these appliances you have, the greater your chances of saving money.</p><p><br/>Based on this, <strong>we estimate savings to be around 15%</strong>.</p>");
        
        //Recommendations as paragraph 2 -- result-para2
        if(roi_month < 6)
            $('#result-para2').html("<p>Based on <strong>MINIMUM</strong> estimated savings of <strong>AT LEAST "+(estimated_saving*100).toFixed(2)+"% ($"+saving_month.toFixed(2)+")</strong> <span class='italic'>per month</span>.</p><ul class='wp100'><li>The Zap Box will pay for itself within just <strong>"+roi_relevant+"</strong> <span class='italic'>months</span>.</li><li>You should be saving <strong>$"+year7+"</strong> over <strong>7</strong> years.</li><li>And, as the expected life of The Zap Box is <strong>25</strong> years you'll see a lifetimes saving of over <strong>$"+year25+"</strong>.</li><li class='cblue'>...that's not bad for a single <strong>$"+price_relevant.toFixed(0)+" purchase</strong>, is it?</li></ul>");
        if(roi_month > 6 && roi_month <= 12)
            $('#result-para2').html("<p>Based on <strong>MINIMUM</strong> estimated savings of <strong>AT LEAST "+(estimated_saving*100).toFixed(2)+"% ($"+saving_month.toFixed(2)+")</strong> <span class='italic'>per month</span>.</p><ul class='wp100'><li>The Zap Box will pay for itself within just <strong>"+roi_relevant+"</strong> <span class='italic'>months</span>.</li><li>You should be saving <strong>$"+year7+"</strong> over <strong>7</strong> years.</li><li>And, as the expected life of The Zap Box is <strong>25</strong> years you'll see a lifetimes saving of over <strong>$"+year25+"</strong>.</li><li class='cblue'>...that's not bad for a single <strong>$"+price_relevant.toFixed(0)+" purchase</strong>, is it?</li></ul>");
        if(roi_month > 12 && roi_month <= 18)
            $('#result-para2').html("<p>At our standard price of <strong>$297</strong> The <strong>Zap Box</strong> may take too long to pay for itself. To give you the best possible value we offer a <strong>$50</strong> discount which will reduce the time it will take for The Zap Box to pay for itsel.</p><p class='cblue'>Just enter <strong class='big'>\"modestuser\"</strong> as a coupon<br/>to get an immediate <strong>$50</strong> discount<br/><br/>This discount does NOT work with our payment plan option.</p><br/><p>The following calculations assume you are paying the discounted price of <strong>$247</strong>...</p><p>Based on <strong>MINIMUM</strong> estimated savings of <strong>AT LEAST "+(estimated_saving*100).toFixed(2)+"% ($"+saving_month.toFixed(2)+")</strong> <span class='italic'>per month</span>.</p><ul class='wp100'><li>The Zap Box will pay for itself within just <strong>"+roi_relevant+"</strong> <span class='italic'>months</span>.</li><li>You should be saving <strong>$"+year7+"</strong> over <strong>7</strong> years.</li><li>And, as the expected life of The Zap Box is <strong>25</strong> years you'll see a lifetimes saving of over <strong>$"+year25+"</strong>.</li><li class='cblue'>...that's not bad for a single <strong>$"+price_relevant.toFixed(0)+" purchase</strong>, is it?</li></ul>");
        if(roi_month > 18)
            $('#result-para2').html("<p>Based on <strong>MINIMUM</strong> estimated savings of <strong>AT LEAST "+(estimated_saving*100).toFixed(2)+"% ($"+saving_month.toFixed(2)+")</strong> <span class='italic'>per month</span>.</p><ul class='wp100'><li>The Zap Box will pay for itself in about <strong>"+roi_relevant+"</strong> <span class='italic'>months</span>.</li></ul><p>This is a long time to wait for savings and there are probably better ways you can save money on your electric bill.</p>");

        //Recommendations as paragraph 3 -- result-para3
        var dcharge = $('input[name="d-charge"]:checked').val(); //q3
        
        if(dcharge == "yes")
            $('#result-para3').html("<div class='rpara heading'>EVEN MORE SAVINGS!</div><p>The <strong>Zap Box will also provide ADDITIONAL savings</strong> on your electric bill by reducing or eliminating your <strong>demand charge</strong>. The dollar amount for this may vary but the savings will be significant if you regularly pay these charges.</p>");
        if(dcharge == "no")
            $('#result-para3').html("<p></p>");
        if(dcharge == "dno")
            $('#result-para3').html("<div class='rpara heading'>POSSIBLY MORE SAVINGS!</div><p><strong>You might save even more money with The Zap Box</strong> if you learn that your electric company bills you with a <strong>demand charge</strong>. We recommend contacting your electric company to ask them if they bill residential customers for this.</p><p>Many electric companies are starting to introduce this charge so it's worth finding our.</p>");
            
        //Recommendations as paragraph 4 -- result-para4   
        if(saving_month >= 25)
        {
            $('#result-para4').html("<div class='rpara heading'>YOU'LL ACTUALLY BE SAVING MORE THAN YOU'RE PAYING ...</div><p>Just look at this ...</p><ul class='wp100'><li>Our monthly payment plan costs you less than you'll be saving each month!</li><li>After paying the <strong>$97</strong> 1-time payment, you'll actually be profiting every month from then onwards!!</li><li>You'll be making monthly savings of about <strong>"+(saving_month).toFixed(2)+"</strong> yet with our payment plan you'll be paying just <strong>$25</strong> ...</li><li class='cblue'>It's as if we're GIVING you <strong>$"+(saving_month-25).toFixed(2)+"</strong> a month from now onwards!</li></ul><div class='clear'></div>");
        }
        
        if(finalRecommendation == 4 || finalRecommendation == 5 || roi_relevant>18)
        {
            $('#pays').hide();
            $('#result-para3').hide();
        }
        
        return finalRecommendation;
    }
    
    $("#firstForm").validate({
        errorLabelContainer: $("#firstForm div.error-con"),
        messages : {
            bill: {
                required:'Please enter your monthly electric bill.',
                number: 'Enter numbers only.'
            },
            homearea: 'Please answer about your home size.',
            'central-ac': 'Please answer about your air conditioner or heat pump.',
            'd-charge': 'Please answer about your demand charge.'
        }
    });
    $("#secondForm").validate({
        errorLabelContainer: $("#secondForm div.error-con"),
        messages : {
            fullname: 'Enter your name.',
            emailaddress: {
                required: 'Email address is required.',
                email: 'Enter a valid email address.'
            }
        }
    });
    
    $('.primaryAction, .stepAction').click(function(event){
        event.preventDefault();
        
        if($(this).attr('rel') == 'firstQ')
        {
            $('#survey-result').hide();
            $('#appliances').hide();
            if($(this).hasClass('reset'))
            {
                $('#secondQ').show();
                
                $(':input','#secondForm')
                .removeAttr('checked')
                .removeAttr('selected')
                .not(':button, :submit, :reset, :hidden, :checkbox, :radio')
                .val('');
                
                $('#firstQ').show();
                $('#secondQ').hide();
                                
                $(':input','#firstForm')
                .removeAttr('checked')
                .removeAttr('selected')
                .not(':button, :submit, :reset, :hidden, :checkbox, :radio')
                .val('');
                
                $('#appliances').hide();
            }
            else
            {
                $('#firstQ').show();
                $('#secondQ').hide();
            }
        }
        
        if($(this).attr('rel') == 'secondQ')
        {
            if($("#firstForm").valid())
            {
                $('#firstQ').hide();
                $('#appliances').hide();
                $('#secondQ').show();
                $('#survey-result').hide();
                var r = checkRecommendation();
                //alert(r);
                if(r == 0)
                    $('#appliances').show();
                else
                    $('#appliances').hide();
            }
            else
            {
                $("#firstForm div.error-con").show();
            }
        }
        
        if($(this).attr('rel') == 'survey-result')
        {
            if($("#secondForm").valid())
            {
                $('#secondQ').hide();
                $('#survey-result').show();
                r = finalCalculation();
                var count = $('#secondQ input:checkbox:checked').length;
                doPost('http://thezapbox.com/scripts/Residential-Wizard/surveyProcessor.php', $('#firstForm').serialize()+"&count="+count+"&r="+r+"&"+$('#secondForm').serialize());
            }
             else
            {
                $("#secondForm div.error-con").show();
            }
        }
        return false;
    });
    
    $('#firstForm, #secondForm').submit(function(event){
        event.preventDefault();
        return false;
    });
    
    function doPost($url, $data)
    {
        $.ajax({
          type: 'POST',
          url: $url,
          data: $data,
          dataType: 'json',
          success: function(data)
          {
            $('#json-result').html(data);
          }
        });
    }
});
