var Wick = Wick || {};
Wick.DateSelection = function () {

    var componentDateSelection = $('.component-date-selection'),
        $deliveryTypes = $('.delivery-types'),
        deliveryTypesFixed = 'delivery-types-fixed-height',
        calendarCellClassName = '.calendar__cell',
        calendarCell = $(calendarCellClassName),
        calendarCellSelected = 'calendar__cell_selected',
        calendarRowExtended = '.calendar__row_extended',
        deliverySelection = $('.delivery-selection'),
        deliverySelectionMobile = $('.delivery-selection-mobile'),
        inputField = '.delivery-types__slot label',
        confirmButton = '.delivery-types__confirm',
        changeDateLinks = '.delivery-time__show-calendar-link, .delivery-selection__show-calendar-link',
        validationError = $('.delivery-types__error'),
        validationErrorShow = 'delivery-types__error-show',
        deliverySelectionShow = 'delivery-selection-show',
        deliveryTypesHide = 'delivery-types-hide',
        deliveryTypesSlotLabel = $(inputField),
        closeIcon = $('.delivery-types__accordion'),
        deliveryTypesInnerStr = '.delivery-types__inner',
        dateSelection = '.date-selection',
        dateSelectionTimeVisible = 'date-selection_time-visible',
        deliveryTypesWrap = $('.delivery-types-wrap'),
        deliveryTypesBtn = 'button.btn',
        deliveryTypeBtnClassSecondary = 'btn-secondary',
        deliveryTypeBtnClass = 'delivery-type__action-btn-primary';

    function init() {
        var count = 0;
        var failed;

        function displayScrollbar (context) {
            setTimeout(function() {

                var deliveryListEl = $(this).closest(dateSelection).find('.delivery-types:visible').find($(deliveryTypesInnerStr)),
                    deliveryListElHeight = deliveryListEl.height(),
                    deliveryTypeDateHeight = deliveryListEl.find(".delivery-types__date").height(),
                    deliveryTypeHeight = deliveryListEl.find(".delivery-type").innerHeight(),
                    simplebarContentHeight = deliveryTypeDateHeight + deliveryTypeHeight;

                deliveryListEl.find($('.simplebar-track.vertical')).removeClass('d-none');

                if (deliveryListElHeight > simplebarContentHeight) {
                    deliveryListEl.find($('.simplebar-track.vertical')).addClass('d-none');
                }

            }.bind(context), 0);
        }

        componentDateSelection.on('click', deliveryTypesBtn, function () {
            $(this).parent(deliveryTypesWrap).find(deliveryTypesBtn).removeClass(deliveryTypeBtnClass);
            $(this).parent(deliveryTypesWrap).find(deliveryTypesBtn).addClass(deliveryTypeBtnClassSecondary);
            $(this).addClass(deliveryTypeBtnClass);
            $(this).removeClass(deliveryTypeBtnClassSecondary);
        });

        //delegation for checking inputs
        componentDateSelection.on('click', inputField, function () {
            $(this).find('input').attr('checked', 'checked');
            deliveryTypesSlotLabel.not($(this)).find('input').removeAttr('checked');
        });

        //delegation for checking validation
        componentDateSelection.on('click', confirmButton, function () {
            var slot = $(this).prev(deliveryTypesInnerStr).find(inputField).find('input');
            failed = 0;
            slot.each(function () {
                if (!$(this).attr('checked')) {
                    failed++;
                }
            });

            if (failed !== slot.length) {
                validationError.removeClass(validationErrorShow);
                calendarCell.removeClass(calendarCellSelected);

                if ($(window).width() < 767) {
                    var rowExtendedBlock = $(this).closest(calendarRowExtended);
                    rowExtendedBlock.slideUp();
                    deliverySelectionMobile.show();
                } else {
                    deliverySelection.addClass(deliverySelectionShow);
                    $deliveryTypes.addClass(deliveryTypesHide);
                }
            } else {
                validationError.addClass(validationErrorShow);
            }

            displayScrollbar(this);
        });

        //angel icon for mobile
        closeIcon.on("click", function () {
            var rowExtendedBlock = $(this).closest(calendarRowExtended);
            $(this).toggleClass('collapsed');
            rowExtendedBlock.slideToggle();
        });

        // counter for radiobutton's
        deliveryTypesSlotLabel.each(function () {
            var id = $(this).attr('for');
            $(this).attr('for', id + count);
            $(this).children('input').attr('id', id + count);
            count++;
        });

        componentDateSelection.on('click', calendarCellClassName, function () {
            displayScrollbar(this);
        });

        calendarCell.on("click", function () {
            $deliveryTypes.removeClass(deliveryTypesHide);
            deliverySelection.removeClass(deliverySelectionShow);

            $(deliveryTypesInnerStr).find('input').each(function () {
                if ($(this).attr('checked')) {
                    $(this).prop('checked', false).removeAttr('checked');
                }
            });

            if ($(window).width() > 767 && $(window).width() <= 1024) {
                $(this).closest(dateSelection).addClass(dateSelectionTimeVisible);
            } else if ($(window).width() < 767) {

                var isCellSelected = $(this).hasClass(calendarCellSelected),
                    rowExtendedBlock = $(this).parent().next(calendarRowExtended),
                    isBlockHidden = rowExtendedBlock.is(':hidden'),
                    currentDeliveryInner = rowExtendedBlock.find(deliveryTypesInnerStr);

                rowExtendedBlock.find(validationError).removeClass(validationErrorShow);

                //check height of deliveryInner
                (_.debounce(function () {
                    if (currentDeliveryInner.height() > 165) {
                        $deliveryTypes.addClass(deliveryTypesFixed);
                    }
                }, 200))();

                if (isCellSelected) {
                    rowExtendedBlock.slideToggle();
                    closeIcon.toggleClass('collapsed');
                } else if (isBlockHidden) {
                    $(calendarRowExtended).slideUp();
                    $(this).parent().next().slideDown();
                    closeIcon.toggleClass('collapsed');
                }
            }
        });

        $(changeDateLinks).on("click", function () {
            $(this).closest(dateSelection).removeClass(dateSelectionTimeVisible);
            deliverySelection.removeClass(deliverySelectionShow);
            calendarCell.removeClass(calendarCellSelected);
        });
    }

    if (!componentDateSelection.length) {
        return;
    }

    init();

    function unbind() {
        closeIcon.unbind('click');
        componentDateSelection.unbind('click');
        calendarCell.unbind('click');
        $(changeDateLinks).unbind('click');
        deliveryTypesWrap.unbind('click');
    }

    $(window).on('resize', _.debounce(function () {
        $deliveryTypes.removeClass(deliveryTypesFixed);

        unbind();
        init();
    }, 250));
}();

