// Global Variables
var id = 0, region = "", type = "", ingredients, requirements, ing_rates;

//emtpy array to hold the plans
var plans;

//*****************************************
// Date Functions
//*****************************************

function doubleDigit(n) {
  n = '' + n;
  if (n.length == 1) {
    n = '0' + n;
  }
  return n;
}

//*****************************************
//    STAGE 1 functions
//*****************************************

function LoadStage1(currstage) {
    
    //the validation function when submitting the form
    $('#form_step1').submit(function(){
        return ValidateStage1();
    });
        
    //the event to trigger the form submission
    $('#submit_button').bind('click',function(){
        $('#form_step1').submit();
    });
    
    //whenever there are errors, remove the highlight when the input gets focus
    $('#form_step1').find('input').each(function(){
        $(this).bind("focus",function(){
            $(this).removeClass("highlight_error");
        });
    });
    
    //the ajx request that retrieves the details regarding the requested postcode
    $('#region_search').bind('click',function() {
        //Reset the form every time you run a new postcode search
        $('#form_step1').resetForm();
        
        //hack to restore the styled drop down boxes to zero
        $("#selectadults").html("0");$("#selectchild").html("0");
        $(".add_adult_div").hide();$(".add_child_div").hide();
        
        $('#errorbox').html("").hide(); $('#coveredform').hide(); $('#loading').fadeIn();
        var pc_val = $('#postcode').val();
        if (pc_val != '') {
            $.getJSON("/booking/ajax.php",{request: "postcode", postcode: pc_val},handleRegion);
        } else {
            var error = {"Error":1,"Notes":"Postcode is not recognised"};
            handleRegion(error);
        }
    });
    
    //Trigger region search when ENTER is pressed on the postcode box
    $("#postcode").bind("keyup", function(e){
        if (e.keyCode==13) {$('#region_search').trigger("click");}
    });
    
    // If this stage has already been done, load the details
    if (currstage>1) {
        $('#form_step1').resetForm();
        
        $('#errorbox').html("").hide(); $('#coveredform').hide(); $('#loading').fadeIn();
        var pc_val = $('#input_group').val();
        if (pc_val != '') {
            $.getJSON("/booking/ajax.php",{request: "group", group_id: pc_val},handleRegion);
        } else {
            var error = {"Error":1,"Notes":"Region was not recognised"};
            handleRegion(error);
        }
        
    }
    
    
    //validation rules for the ingredients, no more than 5 allowed, or it removes the bottom selected    
    $(".ingredients_select").bind("change",function(e){
         var ing = $(this);
         var ing_count = (ing.val() === null) ? 0 : ing.val().length;
         if (ing_count > 5) {
             alert("You can only choose a maximum of 5 ingredients with this order\n\nIf you require more, Please contact us to discuss an a la carte price");
             e.target.selected = false;
             
             var setcount = 0;
             //hack to resolve issue with drag selecting
             $(this).find("option").each(function(){
                 if (this.selected) {
                    if (setcount < 5) {
                        setcount++;
                    } else {
                        this.selected = false;
                    }
                }
             });
             return false;
         }
    });
    
    //when the number of additional adults is changed, reveal that number of additional fields
    $('#adults').bind("change", function(){
        var count = $(this).val();
        //hide all the fields by default
        $(".add_adult_div").hide();
        //loop through the select number to show
        for(var i=1;i<=count;i++) {
            $("#add_adult_div_"+i).show();
        }
    });
    
    //when the number of additional children is changed, reveal that number of additional fields
    $('#child').bind("change", function(){
        var count = $(this).val();
        //hide all the fields by default
        $(".add_child_div").hide();
        //loop through the select number to show
        for(var i=1;i<=count;i++) {
            $("#add_child_div_"+i).show();
        }
    });


    //whenever any field changes, update the total
    $('#form_step1 :input').bind("change",calculateTotal);
    
    $('#if_your_out_choice').bind("change", function(){
        if($('#if_your_out_choice').selected().val() == 'other') {
          $('#if_your_out_other').css('display', '');
          $('#if_your_out').val('');
        } else {
          $('#if_your_out_other').css('display', 'none');
          $('#if_your_out').val($('#if_your_out_choice').selected().val());
        }
    });
    
    $('#coveredform').hide();
    $('#finaltotaldiv').hide();
    $('#loading').hide();
    $('#errorbox').hide();
    
    //Load the custom styling on the boxes
    Custom.init();
    
}


function handleRegion(data) {
    if (data.Error == 0) {
        
        id                  = parseFloat(data.group_id);
        region              = (data.group_name);
        type                = (data.group_condition_label);
        
        $('#input_group').val       (id);
        $('#input_type').val        (type);
        $('#region_span').html      (region);
        $('#plan_type_span').html   (type);
        
        $('#loading').fadeOut("fast",function(){
            $('#coveredform').fadeIn();
            $('#finaltotaldiv').fadeIn();
        });
        
        //store the object locally
        plans = data.plans;
        
        $("#plans_container").html("");
        //create fields for each plan type
        for (var i=0; i < plans.length; i++) {
            //create html for plan
            $("#plans_container").append(" \
            <div class=\"rc_item\"> \
                <div class=\"pp_checkbox_div\"><input " + ((plans[i].chosen==1 || i==0) ? "checked=\"checked\"" : "") + " class=\"input_radio\" type=\"radio\" name=\"plan_id\" id=\"plan_id_"+plans[i].plan_id+"\" value=\""+plans[i].plan_id+"\" /></div> \
                <div class=\"pp_desc_div\">"+plans[i].plan_name+"&nbsp;&nbsp;<a title=\"View more information about the "+plans[i].plan_name+"\" href=\"javascript:void(0);\" onclick=\"$('#plan_length_info"+plans[i].plan_id+"').toggle()\">&larr; More Info</a></div> \
            </div> \
            <div class=\"rc_item\" id=\"plan_length_info"+plans[i].plan_id+"\" style=\"display:none\"> \
                <div class=\"pp_desc_div\" style=\"border:1px solid #02A8DF; padding:5px;margin:5px 0px;width:340px;\"> \
                    <p>"+plans[i].plan_desc+"</p> \
                    <p> \
                        <strong>&pound;"+parseFloat(plans[i].single).toFixed(2) + "</strong> a day for the first adult for a "+plans[i].perweek+" day week<br/> \
                        <strong>&pound;"+parseFloat(plans[i].adult).toFixed(2) + "</strong> a day for any additional adult for a "+plans[i].perweek+" day week<br/> \
                        <strong>&pound;"+parseFloat(plans[i].child).toFixed(2) + "</strong> a day for any additional children for a "+plans[i].perweek+" day week<br/> \
                        <br /> \
                        "+plans[i].plan_more_info+" \
                    </p> \
                </div> \
            </div> \
            ");
            
            //create click event if the number of days equals zero
            if (parseInt(plans[i].days)==0) { 
                $("#plan_id_"+plans[i].plan_id).bind("click",function(e){ $('.under30fields').show();calculateTotal();});
            } else {
                $("#plan_id_"+plans[i].plan_id).bind("click",function(e){ $('.under30fields').hide();calculateTotal();});
            }
            
        };
        
        $('#adults').trigger("change");
        $('#child').trigger("change");
        
        calculateTotal();
        
        //frozen / chilled specifics
        if (type == 'Frozen') {
          //set terms and conditions link to frozen terms
          $('#termsLink').attr('href', '/terms_frozen.php');
          //hide the 'if your out' div
          $('#if_your_out_div').css('display', 'none');
        } else {
          $('#termsLink').attr('href', '/terms_chilled.php');
          //show the 'if your out' div
          $('#if_your_out_div').css('display', 'block');
        }
        
        //create the datepicker for the start date, or radio buttons if it's frozen
        if (type == 'Frozen') {
          fri = new Date();
          fri.setDate(fri.getDate() + 8);
          while (fri.getDay() != 5) {
            fri.setDate(fri.getDate() + 1);
          }
          sat = new Date(fri);
          sat.setDate(sat.getDate() + 1);
          fridd = doubleDigit(fri.getDate());
          satdd = doubleDigit(sat.getDate());
          frimm = doubleDigit(fri.getMonth() + 1);
          satmm = doubleDigit(sat.getMonth() + 1);
          friyyyy = fri.getFullYear();
          satyyyy = sat.getFullYear();
          fristartdate = fridd + '/' + frimm + '/' + friyyyy;
          satstartdate = satdd + '/' + satmm + '/' + satyyyy;
          
          var radio_el = '<div class="rc_item">\n' + 
                        '<div class="pp_checkbox_div"><input checked="checked" class="input_radio" type="radio" onclick="this.blur()" name="start_date" value="' + fristartdate + '" /></div>\n' + 
                        '<div class="pp_desc_div">Friday <br/>(' + fristartdate + ')</div>\n' + 
                    '</div>\n' + 
                    '<div class="rc_item">\n' + 
                        '<div class="pp_checkbox_div"><input class="input_radio" type="radio" onclick="this.blur()" name="start_date" value="' + satstartdate + '" /></div>\n' + 
                        '<div class="pp_desc_div">Saturday <br/>(' + satstartdate + ')</div>\n' + 
                        '<div class="pp_desc_div"><span style="font-size: 10px;">A Saturday delivery costs an additional &pound;6 per week (inc. VAT)</span></div>\n' + 
                        '<div class="pp_desc_div"><span style="font-size: 10px;">The options above show the next available start dates. If you wish to start at a later date, then please call us on 0845 366 9900 (local call rate).</span></div>\n' + 
                    '</div>\n';
          $('#start_date_div').html('');
          $('#start_date_div').append(radio_el);

        } else {
          d = new Date();
          dd = doubleDigit(d.getDate() + 3);
          mm = doubleDigit(d.getMonth() + 1);
          yyyy = d.getFullYear();
          startdate = dd + '/' + mm + '/' + yyyy;
          //<?=date("d/m/Y",(($booking->start_date>0) ? $booking->start_date : time() + (3*24*60*60))) ?>
          $('#start_date_div').html('');
          $('#start_date_div').append('<input type="text" name="start_date" value="' + startdate + '" id="start_date" style="float:right;margin-left:5px;"/>');
          $("#start_date").datepicker({minDate: 3, showOptions: {direction: 'down'}, dateFormat: 'dd/mm/yy', showOn: 'both', buttonImage: '/booking/img/book.calendar.jpg', buttonImageOnly: true}).addClass('input_text input_small_text');
        }
        $('[name=start_date]').bind("change",calculateTotal);
        
    } else {
        $('#errorbox').html('<p class="mp_error">'+data.Notes+'</p>');
        $('#loading').fadeOut("fast",function(){
            $('#errorbox').fadeIn();
        });
    }
}

function calculateTotal() {
    $('#finaltotal').fadeOut("fast",function(){
        $.post("/booking/ajax.php", $("#form_step1").serialize(), function(data) {
            var finaltotal = parseFloat(data);
            $('#finaltotal').html("&pound;" + finaltotal.toFixed(2));
            $('#input_finaltotal').val(finaltotal.toFixed(2));
            $('#finaltotal').fadeIn("fast");
        });
    });
}


//*****************************************
//    STAGE 2A functions
//*****************************************

function LoadStage2A(curr_stage) {
    
    // $('#form_step2').submit(function(){
    //     return ValidateStage2A();
    // });
        
    $('#submit_button').bind('click',function(){
        // Wait a minute! They could have entered a different postcode at the start to get a cheaper deal!
        // check em!
        var pc_val = $("input[name='postcode']").val();
        $.getJSON("/booking/ajax.php",{request: "delivery", postcode: pc_val},function(data){
            var issubmit = false;
            var dc = (data.Response == "EPIC FAIL") ? false : true;
            issubmit = ValidateStage2A(dc);
            if (issubmit){
                $('#form_step2').submit();
            }
        });
    });
    
    $('#form_step2').find('input').each(function(){
        $(this).bind("focus",function(){
            $(this).removeClass("highlight_error");
        });
    });

}

//*****************************************
//    STAGE 2B functions
//*****************************************

function LoadStage2B(curr_stage) {
    
    $('#form_step2').submit(function(){
        return ValidateStage2B();
    });
        
    $('#submit_button').bind('click',function(){
        $('#form_step2').submit();
    });
    
    $('#form_step2').find('input').each(function(){
        $(this).bind("focus",function(){
            $(this).removeClass("highlight_error");
        });
    });

}

//*****************************************
//    STAGE 2C functions
//*****************************************

function LoadStage2C(curr_stage) {
    
    $('#submit_button').bind('click',function(){
        // Wait a minute! They could have entered a different postcode at the start to get a cheaper deal!
        // check em!
        var pc_val = $("input[name='postcode']").val();
        $.getJSON("/booking/ajax.php",{request: "delivery", postcode: pc_val},function(data){
            var issubmit = false;
            var dc = (data.Response == "EPIC FAIL") ? false : true;
            issubmit = ValidateStage2C(dc);
            if (issubmit){
                $('#form_step2').submit();
            }
        });
    });
    
    
    $('#form_step2').submit(function(){
        return ValidateStage2C();
    });
        
    $('#submit_button').bind('click',function(){
        $('#form_step2').submit();
    });
    
    $('#form_step2').find('input').each(function(){
        $(this).bind("focus",function(){
            $(this).removeClass("highlight_error");
        });
    });

}

//*****************************************
//    STAGE 2B functions
//*****************************************

function LoadStage3(curr_stage) {
    
    $('#submit_button').bind('click',function(){
        $('#form_step3').submit();
        return false;
    });

}


