﻿$(document).ready(function () {


    /*-------------------------------------------------------------------------*/
    /* Centre the DIV                                                          */
    /*-------------------------------------------------------------------------*/
    function deadCenterDiv(divid) {
        var scrolledX = 0, scrolledY = 0;
        if (self.pageYOffset) {
            scrolledX = self.pageXOffset;
            scrolledY = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrolltop) {
            scrolledX = document.documentElement.scrollLeft;
            scrolledY = document.documentElement.scrolltop;
        } else if (document.body) {
            scrolledX = document.body.scrollLeft;
            scrolledY = document.body.scrollTop;
        }

        // Next, determine the coordinates of the center of browser's window

        var centerX, centerY;
        if (self.innerHeight) {
            centerX = self.innerWidth;
            centerY = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) {
            centerX = document.documentElement.clientWidth;
            centerY = document.documentElement.clientHeight;
        } else if (document.body) {
            centerX = document.body.clientWidth;
            centerY = document.body.clientHeight;
        }

        // The initial width and height of the div can be set in the
        // style sheet with display:none; divid is passed as an argument to // the function
        var obj = document.getElementById(divid);
        // Xwidth is the width of the div, Yheight is the height of the
        // div passed as arguments to the function:
        var leftoffset = scrolledX + (centerX - obj.offsetWidth) / 2;
        var topOffset = scrolledY + (centerY - obj.offsetHeight) / 2;
        var r = obj.style;
        r.position = 'absolute';
        r.top = topOffset + 'px';
        r.left = leftoffset + 'px';
        r.visibility = "visible";
    }


    /*-----------------------------------------------------------------*/
    /*    Determine if there are any Popups on the page that needs to  */
    /*    be centered, then calls deadCenterDiv to center them         */
    /*-----------------------------------------------------------------*/

    if ($('.centeredPopup').length) {

        $('.centeredPopup').each(function (index) {
            var thisId = $(this).attr('id');
            deadCenterDiv(thisId);
        });
    }

    /*----------------------------------------------------------------*/
    /*      Limits amount of characters that can be entered in        */
    /*      Shipping instructions and Notes textboxes (viewcart.aspx) */
    /*----------------------------------------------------------------*/

    var limit = 70;

    $('textarea[id$=notes]').keydown(function (e) {
        var len = $(this).val().length;

        //disable Enter key for Additional Notes textarea
        if (e.which == 13) {
            return false;
        }

        if (len > limit) {
            this.value = this.value.substring(0, limit);
        }

        $('#notesLeft').text(limit - len + " characters left");
    });

    $('textarea[id$=shippingInstructions]').keydown(function (e) {
        var len = $(this).val().length;

        //disable Enter key for Shipping Instructions textarea
        if (e.which == 13) {
            return false;
        }

        if (len > limit) {
            this.value = this.value.substring(0, limit);
        }
        $('#instLeft').text(limit - len + " characters left");
    });



    /*---------------------------------------------------------------------*/
    /*    set correct delivery days and available time (viewcart.aspx)     */
    /*---------------------------------------------------------------------*/

    var today = $('[id$=todayDay]').val();

    function loadAvailableDeliveryTimes(day, currentHour, currentMinute, open, close, withinAnHour, nextDayOnly) {
        var openHour = parseInt(open);
        var closeHour = parseInt(close);
        var thisHour = parseInt(currentHour);
        var thisMinute = parseInt(currentMinute);
        var hoursLeft;
        var startHour;
        var endHour;
        var i;
        var outputString;

        $('#availableTimes').empty();

        if (day == today) {

            if (withinAnHour == 'True') {
                $('#withinTheHourDisplay').css({ 'display': 'block' });
            }
            if (withinAnHour == 'False') {
                $('#withinTheHourDisplay').css({ 'display': 'none' });
            }

            hoursLeft = parseInt(closeHour - thisHour);
            var processedDelivery = false;

            if (hoursLeft >= 0 && nextDayOnly == 'False') {

                //                for (i = 1; i <= hoursLeft; i++)
                //                 {

                i = 1;

                hoursLeft = closeHour - openHour;

                for (i = 1; i <= hoursLeft; i++) {

                    if (thisMinute < 30 && (thisHour + i) < closeHour) {
                        processedDelivery = true;
                        if (thisHour >= openHour) {
                            startHour = thisHour + i;
                            endHour = startHour + 1;
                        }
                        if (thisHour < openHour) {
                            $('#withinTheHourDisplay').css({ 'display': 'none' });
                            startHour = openHour + i - 1;
                            endHour = startHour + 1;
                        }
                        outputString = '<span><input type="radio" name="deliveryTime" value="' + startHour + 'h00-' + endHour + 'h00">' + startHour + 'h00-' + endHour + 'h00</input></span><br/>';
                        $('#availableTimes').append(outputString);
                    }
                }

                //hoursLeft = closeHour - openHour;

                for (i = 1; i <= hoursLeft; i++) {
                    if (thisMinute > 30 && (thisHour + i + 1) < closeHour) {
                        processedDelivery = true;

                        if (thisHour >= openHour) {
                            startHour = thisHour + i + 1;
                            endHour = startHour + 1;
                        }
                        if (thisHour < openHour) {
                            $('#withinTheHourDisplay').css({ 'display': 'none' });
                            startHour = openHour + i - 1;
                            endHour = startHour + 1;
                        }
                        outputString = '<span><input type="radio" name="deliveryTime" value="' + startHour + 'h00-' + endHour + 'h00">' + startHour + 'h00-' + endHour + 'h00</input></span><br/>';
                        $('#availableTimes').append(outputString);
                    }
                }

                if (processedDelivery == false && withinAnHour == 'False' && thisHour >= openHour) {
                    if (thisHour + i + 2 >= closeHour) {
                        //processedDelivery = true;
                        $('input[value^="' + day + '"]').attr('disabled', 'disabled').attr('checked', false);
                        $('input[value^="' + day + '"]').next().removeAttr('disabled').attr('checked', true);
                        outputString = '<span class="sorry">Unfortunately we can no longer deliver to your area today. Please select a delivery time for tomorrow or another day</span><br/>';
                        $('#withinTheHourDisplay').css({ 'display': 'none' });
                        $('#availableTimes').append(outputString);
                        //break;
                    }
                }
                if (processedDelivery == false && withinAnHour == 'True' && thisHour >= openHour) {
                    if (thisHour >= closeHour) {
                        //processedDelivery = true;
                        $('input[value^="' + day + '"]').attr('disabled', 'disabled').attr('checked', false);
                        $('input[value^="' + day + '"]').next().removeAttr('disabled').attr('checked', true);
                        outputString = '<span class="sorry">Unfortunately we can no longer deliver to your area today. Please select a delivery time for tomorrow or another day</span><br/>';
                        $('#withinTheHourDisplay').css({ 'display': 'none' });
                        $('#availableTimes').append(outputString);
                        //break;
                    }
                    else {
                        $('#withinTheHourDisplay').css({ 'display': 'block', 'padding-top': '20px' });
                        $('#or').hide();
                        outputString = '<span class="yay">You caught us just in time for our last delivery of the day, we can deliver your order within an hour.</span><br/>';
                        $('#ctl00_cphDetail_chkWithinTheHour').removeAttr('disabled').attr('checked', 'checked').parent().removeAttr('disabled');
                        $('#availableTimes').append(outputString);
                    }

                }


                //                }
            }
            if (hoursLeft <= 0 || nextDayOnly == 'True') {
                $('input[value^="' + day + '"]').attr('disabled', 'disabled').attr('checked', false);

                //$(':input:enabled:first').attr('checked', true).change();
                $('#withinTheHourDisplay').css({ 'display': 'none' });
                $('input[name$=dayOfWeek]:enabled:first').attr('checked', true).trigger('change');
                reloadDeliveryTimes();
                $('#nextDayNote').html('*Unfortunately we can no longer deliver to your area today and the delivery date has automatically been set to the first available delivery time for tomorrow');
                /*$('input[value^="' + day + '"]').nextAll('input[id*=radioDayOfWeek]:first').attr('checked', true);
                outputString = '<span class="sorry">Unfortunately we can no longer deliver to this area today. Please select a delivery time for tomorrow or another day</span><br/>';
                
                $('#availableTimes').append(outputString);*/
            }
        }

        else {

            $('#withinTheHourDisplay').css({ 'display': 'none' });
            hoursLeft = closeHour - openHour;

            for (i = 0; i < hoursLeft; i++) {
                startHour = openHour + i;
                endHour = openHour + i + 1;

                $('#availableTimes').append('<span><input type="radio" name="deliveryTime" value="' + startHour + 'h00-' + endHour + 'h00">' + startHour + 'h00-' + endHour + 'h00</input></span><br/>');
            }
        }

        $('[name=deliveryTime]:first').attr('checked', 'checked');
    }


    //Load times
    var dateCounter = 1;
    $('input[name$=dayOfWeek]:radio').each(function (index) {
        var dayValue = $(this).next().text();


        dayName = dayValue.split(' -');
        dayName = dayName[0];
        var thisHour = $('[id$=currentHour]').val();
        var thisMinute = $('[id$=currentMinute]').val();
        var nextDayOnly = $('[id$=hdnDeliveryNextDay]').val();
        var withinAnHour = $('[id$=hdnDeliveryHour]').val();

        $(this).attr('name', 'dayOfWeek');
        $(this).attr('value', dayValue);

        if (dayName == today) {
            var openHour = $(this).nextAll('[name=openTime]:first').val();
            var closingHour = $(this).nextAll('[name=closeTime]:first').val();

            $(this).attr('checked', true);

            loadAvailableDeliveryTimes(today, thisHour, thisMinute, openHour, closingHour, withinAnHour, nextDayOnly);
        }
    });



    //Update delivery times if selected day changes

    function reloadDeliveryTimes() {
        $('#nextDayNote').empty();
        var openHour = $('input[name*=dayOfWeek]:checked').nextAll('[name=openTime]:first').val();
        var closingHour = $('input[name*=dayOfWeek]:checked').nextAll('[name=closeTime]:first').val();
        var dayValue = $('input[name*=dayOfWeek]:checked').next().text();

        dayName = dayValue.split(' -');
        dayName = dayName[0];
        var thisHour = $('[id$=currentHour]').val();
        var thisMinute = $('[id$=currentMinute]').val();
        var nextDayOnly = $('[id$=hdnDeliveryNextDay]').val();
        var withinAnHour = $('[id$=hdnDeliveryHour]').val();

        loadAvailableDeliveryTimes(dayName, thisHour, thisMinute, openHour, closingHour, withinAnHour, nextDayOnly);
    }


    $('[name$=dayOfWeek]').change(function () {
        reloadDeliveryTimes();
        /*var openHour = $('input[name=dayOfWeek]:checked').nextAll('[name=openTime]:first').val();
        var closingHour = $('input[name=dayOfWeek]:checked').nextAll('[name=closeTime]:first').val();
        var dayValue = $('input[name=dayOfWeek]:checked').next().text();

        dayName = dayValue.split(' -');
        dayName = dayName[0];
        var thisHour = $('[id$=currentHour]').val();
        var thisMinute = $('[id$=currentMinute]').val();
        var nextDayOnly = $('[id$=hdnDeliveryNextDay]').val();
        var withinAnHour = $('[id$=hdnDeliveryHour]').val();

        loadAvailableDeliveryTimes(dayName, thisHour, thisMinute, openHour, closingHour, withinAnHour, nextDayOnly);*/

    });

    $('input[name*=deliveryTime]').change(function () {
        $('#nextDayNote').empty();
    });


    //Checks if there are any items in minicart to show productlist
    if ($('.minicartContents').find('[id$=LoggedInGridView]').length) {
        $('.minicartEmpty').addClass('minicart').removeClass('minicartEmpty');
        $('.minicartControls').css({ 'display': 'block' });
    }


    //Enables/Disables Same Day checkboxes on DeliveryAreaInformation.aspx
    if ($('[id$=gridSuburbsMain]').length) {

        $('[id$=gridSuburbsMain] tr').each(function (index) {
            var sameDay;
            var nextDay;
            var withInAnHour;
            var sameDayId;
            var nextDayId;


            $(this).find('td').each(function (index) {
                var thisID = $(this).find('input[id*=chDeliveryHourFlag]').attr('id');
                var thisSameDayID = $(this).find('input[id*=chSameDay]').attr('id');
                var thisNextDayID = $(this).find('input[id*=chDeliveryNextDayFlag]').attr('id');


                if (thisID != null) {
                    withInAnHour = $('#' + thisID).attr('checked');
                }

                if (thisSameDayID != null) {
                    sameDayId = thisSameDayID;
                }

                if (thisNextDayID != null) {
                    nextDayId = thisNextDayID;
                    nextDay = $('#' + nextDayId).attr('checked');
                }
            });

            if (withInAnHour == true) {
                $('#' + sameDayId).attr('checked', 'checked');
                $('#' + nextDayId).attr('checked', 'checked');
            }

            if (withInAnHour == false && nextDay == false) {
                $('#' + sameDayId).attr('checked', 'checked');
                $('#' + nextDayId).attr('checked', 'checked');
            }

            if (withInAnHour == false && nextDay == true) {
                $('#' + sameDayId).attr('checked', false);
                $('#' + nextDayId).attr('checked', 'checked');
            }

        });
        //Styles DeliveryArea checkboxes
        if ($('input[name*=gridSuburbsMain]:radio').length) {

            $('input[name*=gridSuburbsMain]:radio').each(function (index) {
                $(this).hide();
                if ($(this).is(':checked')) {
                    $(this).parents('.areaCheck').addClass('areaCheckActive');
                }
                else {
                    $(this).parents('.areaCheck').addClass('areaCheckDisabled');
                }
            });
        }

    }

});
