$(document).ready(function() {



    function submitBuyForm() {
        $('#buyOnlineForm').submit();
    }


    $('#step2, #step1').attr("checked", true);

    var roof_group = 1;
    var roof_group_name = "22&deg; felt roof";

    var item_data = '';
    var carriage_house = null;
    var carriage_house_data = null;

    var discount = 0.00;

    var zones = null;
    var zone = null;

    var garage = null;
    var workshop = null;
    var cart_lodge = null;
    var log_store = null;

    var total = 0.00;
    var erectionCharge = 0.00;
    var delivery = 0.00;
    var gross = 0.00;

    var zone_dir = null;
    var log_store_dir = null;
    var garage_dir = null;
    var group_id = null;

    var vat = 0.00;
    var cart_lodge_dir = null;
    var workshop_dir = null;


    var step_one = false; 
    var step_two = false;
    
    function reset(){ //Resets the righthand basket (visually)
        total = 0.00;
        erectionCharge = 0.00;
        vat = 0.00;
        delivery = 0.00;
        gross = 0.00;

        $('#step2Text').html("");
        $('#step2Price').html("");

        $('#step3Text').html("");
        $('#step3Price').html("");

        $('#step4Text').html("");
        $('#step4Price').html("");

        $('#step5Text').html("");
        $('#step5Price').html("");

        $('#step6Text').html("");
        $('#step6Price').html("");

        $('#erectionCharge').html("&pound;0.00");
        $('#deliveryCharge').html("&pound;0.00");
        $('#subTotal').html("&pound;0.00");
        $('#vatAmount').html("&pound;0.00");
        $('#grossTotal').html("&pound;0.00");

        $('#discount').html("&pound;0.00");
        $('#discountTotalDetails').html("&pound;0.00");
        $('#deposit').html("&pound;0.00");

        $('#deliveryPostCode').val("&pound;0.00");
        $('#deliveryChargeDetails').val("&pound;0.00");
        $('#subTotalDetails').val("&pound;0.00");
        $('#vatAmountDetails').val("&pound;0.00");
        $('#grossTotalDetails').val("&pound;0.00");
        $('#buildingTotalCharge').html("&pound;0.00");

    }




    //Toggle left right cart lodge selection
    $('input[name="step5"]').change(function(){
        if($('input[name="step5"]:checked').val() === 'R'){
            $('input#step6a').attr('checked', false);
            $('input#step6a').attr('disabled', true);
            $('input#step6').attr('disabled', false);
            $('input#step6').attr('checked', true);

        }else{
            $('input#step6a').attr('checked', true);
            $('input#step6a').removeAttr('disabled');
            $('input#step6').attr('disabled', true);
            $('input#step6').attr('checked', false);
        }
    })


    //Resets the in memory values (used when the user changes the carrige house set.
    $('input[name="step1"], input[name="step2"], #step2Size').click(function(){ 

        if($(this).attr('name') == "step1"){
            if(step_one == true){
                item_data = null;
                carriage_house = null;
                garage = null;
                workshop = null;
                cart_lodge = null;
                log_store = null;
                step_two = false;

                //$('input#step1').attr('checked', true);

                $('#step3Body, #step4Body, #step5Body, #step6Body').css("display", "none");
                $('.toggle').val('Please Select');
                $('#erectChange').val('Please Select');
                
                $('#step7PostCodes').val("");
            }
            $('#step2Size, #step3Size, #step4Size').val('Please Select');
            step_one = true;

        }else if($(this).attr('name') == "step2"){
            msg = "Do you wish to change your design? - please start again from Step 1";
            if(step_two == true){
                if(confirm(msg)){
                    item_data = null;
                    carriage_house = null;
                    garage = null;
                    workshop = null;
                    cart_lodge = null;
                    log_store = null;
                    $('input#step1').attr('checked', true);                    
                    $('input#step2').attr('checked', true);  

                    $('#step3Body, #step4Body, #step5Body, #step6Body').css("display", "none");
                    $('.toggle').val('Please Select');
                    $('#erectChange').val('Please Select');
                    $('#step7PostCodes').val("");
                }else{
                    //change radio button back.
                    if($(this).attr("id")[$(this).attr("id").length-1] == "a"){
                        $(this).attr('checked', false);
                        $($("input#"+$(this).attr("id").slice(0, -1))).attr('checked', true);
                    }else{
                        $(this).attr('checked', false);
                        $($("input#"+$(this).attr("id")+"a")).attr('checked', true);
                    }
                }
            }
            step_two = true;
        }


        reset();
    });


    //gets the defualt data (page load defaults to Single Carriage House
    $.getJSON('get_carriage.php', {'name':'Single Carriage House', 'roof_group':roof_group}, function(data) {
        if(data != null && data != undefined) {
            carriage_house_data = data;
            $('#step2Size').html('<option selected="selected" value="">Please Select</option>');
            $.each(data, function(i, item){
                $('#step2Size').append("<option value='" + item['id'] + "'>" + item['depth'] + " x " + item['width'] + "</option>");
            });
        }
        reset();
    });


    //Populates the post code zones step 7
    $.getJSON('get_zones.php',  function(data) {
        zones = data;
        $('#step7PostCodes').html('<option selected="selected" value="">Please Select</option>');
        $.each(data, function(i, item){
            $('#step7PostCodes').append("<option value='" + item['id'] + "'>" + item['post_code'] + "</option>");
        });
        reset();
    });


    //Toggle select options
    $('.toggle').change(function(){
        var next = $(this).parent().parent().parent().next();
        if($(this).val() == 1){
            next.css('display', '');
        }else{
            next.css('display', 'none');
        }
        reset();
        step_one = true;
        step_two = true;
    });


    // Change roof group
    $("input[name='step1']").click(function(){
        if($(this).val() == 'felt'){
            roof_group = 1;
            roof_group_name = "22&deg; felt roof";
            $('#step5toggle').attr('disabled', 'disabled');
        }else if($(this).val() == 'tiled'){
            roof_group = 2;
            roof_group_name = "35&deg; roof to suit tiles";
            $('#step5toggle').removeAttr('disabled');
        }
        reset();
    $.getJSON('get_carriage.php', {'name':'Single Carriage House', 'roof_group':roof_group}, function(data) {
        if(data != null && data != undefined) {
            carriage_house_data = data;
            $('#step2Size').html('<option selected="selected" value="">Please Select</option>');
            $.each(data, function(i, item){
                $('#step2Size').append("<option value='" + item['id'] + "'>" + item['depth'] + " x " + item['width'] + "</option>");
            });
        }
        reset();
    });

    });


    // Change carriage type populates select box options in step 2
    $("input[name='step2']").click(function(){
        if($(this).val() == 'Single'){
            $.getJSON('get_carriage.php', {'name':'Single Carriage House', 'roof_group':roof_group}, function(data) {
                $('#step2Size').html('<option selected>Please Select</option>');
                carriage_house_data = data;
                $.each(data, function(i, item){
                    $('#step2Size').append("<option value='" + item['id'] + "'>" + item['depth'] + " x " + item['width'] + "</option>");
                });
            });

        }else if($(this).val() == 'Double'){
            $.getJSON('get_carriage.php', {'name':'Double Carriage House', 'roof_group':roof_group}, function(data) {
                $('#step2Size').html('<option selected>Please Select</option>');
                carriage_house_data = data;
                $.each(data, function(i, item){
                    $('#step2Size').append("<option value='" + item['id'] + "'>" + item['depth'] + " x " + item['width'] + "</option>");
                });
            });
        }

		else if($(this).val() == 'Triple'){
            $.getJSON('get_carriage.php', {'name':'Three Bay Carriage House', 'roof_group':roof_group}, function(data) {
                $('#step2Size').html('<option selected>Please Select</option>');
                carriage_house_data = data;
                $.each(data, function(i, item){
                    $('#step2Size').append("<option value='" + item['id'] + "'>" + item['depth'] + " x " + item['width'] + "</option>");
                });
            });
        }
        reset();
    });


    //Gets the group id as well as popluates the dropdown boxes of step 3-5
    $('#step2Size').change(function(){
    
        item_data = null;
        carriage_house = null;
        garage = null;
        workshop = null;
        cart_lodge = null;
        log_store = null;
        $('input#step1').attr('checked', true);                    
        $('input#step2').attr('checked', true);  

        $('#step3Body, #step4Body, #step5Body, #step6Body').css("display", "none");
        $('.toggle').val('Please Select');
        $('#erectChange').val('Please Select');
        $('#step7PostCodes').val("");

        
        
        val = $(this).val();
        if(val){

            $.each(carriage_house_data, function(i, item){
                if(item['id'] == val){
                    carriage_house = item;
                }
            });

            group_id = carriage_house['group_id'];

            $.getJSON('get_extra_data.php', {'group_id':group_id, 'roof_group_id':roof_group}, function(data) {
                item_data = data;
                $('#step3Size').html('<option selected>Please Select</option>');
                $.each(data['garage'], function(i, item){
                    $('#step3Size').append("<option value='" + item['id'] + "'>" + item['depth'] + " x " + item['width'] + "</option>");
                });

                $('#step4Size').html('<option selected>Please Select</option>');
                $.each(data['workshop'], function(i, item){
                    $('#step4Size').append("<option value='" + item['id'] + "'>" + item['depth'] + " x " + item['width'] + "</option>");
                });

                $('#cart_lodge_size').html(item_data['cart_lodge'][0]['depth'] + " x " + item_data['cart_lodge'][0]['width']);
                $('#log_store_size').html(item_data['log_store'][0]['depth'] + " x " + item_data['log_store'][0]['width']);
            });
        }
        reset();
    });
    

    //Get garage data
    $('#step3Size').change(function(){
        val = $(this).val();
        $.each(item_data['garage'], function(i, item){
            if(item['id'] == val){  
                garage = item;
                garage_dir = $("input[name='step3']:checked").val();
            }
        });
        reset();
    });


    //Get workshop data
    $('#step4Size').change(function(){
        val = $(this).val();
        $.each(item_data['workshop'], function(i, item){
            if(item['id'] == val){
                workshop = item;
                workshop_dir = $("input[name='step4']:checked").val();
            }
        });
        reset();
    });

    //Gets cart lodge data
    $('input[name="step5"], #step5toggle').change(function(){
        if( $('#step5toggle').val() == "1"){
            cart_lodge = item_data['cart_lodge'][0];
            cart_lodge_dir = $("input[name='step5']:checked").val();
            $('#cart_lodge_size').html(item_data['cart_lodge'][0]['depth'] + " x " + item_data['cart_lodge'][0]['width']);
            $('input#step6').attr('disabled', true);
        }else{
            cart_lodge = null;
            cart_lodge_dir = null;
            $('input#step6').attr('disabled', false);
        }
        reset();
    });

    //Gets log store data
    $('input[name="step6"], #step6toggle').change(function(){
        if( $('#step6toggle').val() == "1"){
            log_store = item_data['log_store'][0];
            log_store_dir = $("input[name='step6']:checked").val();
            $('#log_store_size').html(item_data['log_store'][0]['depth'] + " x " + item_data['log_store'][0]['width']);
        }else{
            log_store = null;
            log_store_dir = null;
        }
        reset();
    });


    //Gets location data
    $('#step7PostCodes').change(function(){
        val = $(this).val();
        $.each(zones, function(i, item){
            if(item['id'] == val){
                zone = item;
                zone_dir = $("input[name='step7']:checked").val();
            }
        });
        reset();
    });


    //Rounds the number down to the nearest X
    function round(num, x){
        if ( x < 0 ) {
            num *= x;
            num = Math.round(num);
            num /= x;
        } else {
            num /= x;
            num = Math.round(num);
            num *= x;
        }
        return Math.ceil(num);  //Math.floor()=round down, Math.ceil()=round up
    }


    //Calculates Totals
    $('.calcSubmit').click(function(){
        reset();

        if(carriage_house == null){ //if the user hasnt picket a carriage house prompt them to
            alert("Please choose a carriage house size.");
            return;
        }
        if(zone == null){ //if the user hasnt selected a post code, prompt them to
            alert("Please choose a post code.");
            return;$("#video").makeFloat({x:"current",y:"current"});
        }

        //Start to display everything on the righthand basket
        $('#step2BasketDetails').css('display', '');
        $('#step2Price').html("&pound;" + parseFloat(carriage_house['price']).toFixed(2));
        $('#step2PriceDetails').val(parseFloat(carriage_house['price']).toFixed(2));
        $('#step2Text').html(carriage_house['depth'] + " long x " + carriage_house['width'] + " wide " + "" + carriage_house['name'] + " with " + roof_group_name);
        $('#step2Details').val(carriage_house['depth'] + " long x " + carriage_house['width'] + " wide " + "" + carriage_house['name'] + " with " + roof_group_name);

        total += parseFloat(carriage_house['price']);
        erectionCharge += parseFloat(carriage_house["zone_" + zone['zone']]);

        if(garage && $('#step3toggle').val()=="1"){
            total += parseFloat(garage['price']);
            erectionCharge += parseFloat(garage["zone_" + zone['zone']]);

            $('#step3BasketDetails').css('display', '');
            $('#step3Price').html("&pound;" + parseFloat(garage['price']).toFixed(2));
            $('#step3PriceDetails').val(parseFloat(garage['price']).toFixed(2));
            $('#step3Text').html(garage['depth'] + " long x " + garage['width'] + " wide " + "" + garage['name'] + " with " + roof_group_name + " " + garage_dir);
            $('#step3Details').val(garage['depth'] + " long x " + garage['width'] + " wide " + "" + garage['name'] + " with " + roof_group_name + " " + garage_dir);
        }
        if(workshop && $('#step4toggle').val()=="1"){
            total += parseFloat(workshop['price']);
            erectionCharge += parseFloat(workshop["zone_" + zone['zone']]);

            $('#step4BasketDetails').css('display', '');
            $('#step4Price').html("&pound;" + parseFloat(workshop['price']).toFixed(2));
            $('#step4PriceDetails').val(parseFloat(workshop['price']).toFixed(2));
            $('#step4Text').html(workshop['depth'] + " long x " + workshop['width'] + " wide " + "" + workshop['name'] + " with " + roof_group_name + " " + workshop_dir);
            $('#step4Details').val(workshop['depth'] + " long x " + workshop['width'] + " wide " + "" + workshop['name'] + " with " + roof_group_name + " " + workshop_dir);        
        }
        if(cart_lodge && $('#step5toggle').val()=="1"){
            if( $('#step5toggle').val() == "1"){
                cart_lodge = item_data['cart_lodge'][0];
                cart_lodge_dir = $("input[name='step5']:checked").val();
                $('#cart_lodge_size').html(item_data['cart_lodge'][0]['depth'] + " x " + item_data['cart_lodge'][0]['width']);
                $('input#step6').attr('disabled', true);
            }else{
                cart_lodge = null;
                cart_lodge_dir = null;
                $('input#step6').attr('disabled', false);
            }
            total += parseFloat(cart_lodge['price']);
            erectionCharge += parseFloat(cart_lodge["zone_" + zone['zone']]);

            $('#step5BasketDetails').css('display', '');
            $('#step5Price').html("&pound;" + parseFloat(cart_lodge['price']).toFixed(2));
            $('#step5PriceDetails').val(parseFloat(cart_lodge['price']).toFixed(2));
            $('#step5Text').html(cart_lodge['depth'] + " long x " + cart_lodge['width'] + " wide " + "" + cart_lodge['name'] + " with " + roof_group_name + " " + cart_lodge_dir);
            $('#step5Details').val(cart_lodge['depth'] + " long x " + cart_lodge['width'] + " wide " + "" + cart_lodge['name'] + " with " + roof_group_name + " " + cart_lodge_dir);        
        }

        if(log_store && $('#step6toggle').val()=="1"){
            if( $('#step6toggle').val() == "1"){
                log_store = item_data['log_store'][0];
                log_store_dir = $("input[name='step6']:checked").val();
                $('#log_store_size').html(item_data['log_store'][0]['depth'] + " x " + item_data['log_store'][0]['width']);
            }else{
                log_store = null;
                log_store_dir = null;
            }

            total += parseFloat(log_store['price']);
            erectionCharge += parseFloat(log_store["zone_" + zone['zone']]);

            $('#step6BasketDetails').css('display', '');
            $('#step6Price').html("&pound;" + parseFloat(log_store['price']).toFixed(2));
            $('#step6PriceDetails').val(parseFloat(log_store['price']).toFixed(2));
            $('#step6Text').html(log_store['depth'] + " long x " + log_store['width'] + " wide " + "" + log_store['name'] + " with " + roof_group_name + " " + log_store_dir);
            $('#step6Details').val(log_store['depth'] + " long x " + log_store['width'] + " wide " + "" + log_store['name'] + " with " + roof_group_name + " " + log_store_dir);
        }

    
        //Start calculations
        $('#buildingTotalCharge').html("&pound;" + total.toFixed(2));

        //Displays totals in the basket
        delivery = parseFloat(zone['delivery']);

        //Display the area code
        $('#area_code').html(zone['post_code']);

        //Total plus delivery
        total = total + delivery;

        //If the user want the building to be erection the add that code of erection to the total.
        if($('#erectChange').val() == "Yes"){
            if(erectionCharge){
                $('#erectionDetails').val(erectionCharge); // post code 
                total = total + parseFloat(erectionCharge);
            }
        }
        
        if(erectionCharge && $('#erectChange').val() == "Yes"){ //If the user wants the building to be erected and theres an erection charge stored add the erection charge value to the erection chage box in the righthand basket.
            $('#erectionCharge').html("&pound;" + erectionCharge.toFixed(2));
        }else if ($('#erectChange').val() == "No"){ //if they dont want it erected then set it back to 0.00
            $('#erectionCharge').html("&pound;0.00");
        }else{ //The building cannot be erected in that area code.
            $('#erectionCharge').html("N/A");
        }

        $('#deliveryCharge').html("&pound;" + delivery.toFixed(2));
        $('#subTotal').html("&pound;" + total.toFixed(2));

        //Workout the VAT
        vat = (total/100) * 20;  
  
        //Display the VAT
        $('#vatAmount').html("&pound;" + vat.toFixed(2));


        //Workout the gross
        gross = parseFloat(vat) + parseFloat(total);

        //Workout dicount.
        discount = (gross/100) * 7.5;
        discount = round(discount, 10);

        //Workout the total
        total = gross - discount;

        // Used in the basket / printout NOT PART OF THE HIDDEN FORM
        $('#discountTotalDetails').html("&pound;" + total.toFixed(2));
        $('#discount').html("&pound;" + discount); 
        $('#grossTotal').html("&pound;" + gross.toFixed(2));

        $('#deposit').html("&pound;" + (total * 0.25).toFixed(2));


        //Add the vales to the hidden form erectionDetails
        //Erection change gets added in ferther up the page
        $('#deliveryPostCode').val(zone['post_code']); // post code 
        $('#deliveryChargeDetails').val(delivery.toFixed(2)); //delivery amount
        $('#grossTotalDetails').val(gross.toFixed(2)); // befor discount
        $('#subTotalDetails').val(total.toFixed(2));  // after discount
        $('#vatAmountDetails').val(vat.toFixed(2)); // vat amount
        $('#discountDetails').val(discount); // disocunt amount
    });
});

