frontend.Gastro = frontend.Gastro || {};
;
frontend.Gastro.OrdersAcceptation = {

    init: function () {
        this.cacheElements();
        this.bindEvents();
        this.screensCount = $('.box-for-display').length;
        this.currentScreen = 1;
        this.activeOrderId = '';

        this.setOrdersHeight();

        if (this.$ordersWrapper.length) {
            this.initOrdersListScreens();
            if (this.$newOrdersWrapper.length) {
                this.initLoadOrdersLoop();
            }
            this.initLoadNotificationsLoop();
        }
    },

    cacheElements: function () {
        this.$window = $(window);
        this.$document = $(document);

        this.$ordersWrapper = $('#orders-for-acceptation');
        this.$newOrdersWrapper = $('#new-orders');
        this.$finishedOrdersWrapper = $('#finished-orders');
        this.$cancelledOrdersWrapper = $('#cancelled-orders');
        this.$ordersListWrapper = $('#orders');
        this.$orderWrapper = $('#order-detail');
        this.$sendForgottenPwdBtn = $('#js-send-pwd');
    },

    bindEvents: function () {
        this.$window.on('resize', $.proxy(this.setOrdersHeight, this));
        this.$ordersWrapper.on('click', '.order', $.proxy(this.showOrderDetail, this));
        this.$orderWrapper.on('click', '.time', $.proxy(this.setDeliveryTime, this));
        this.$ordersListWrapper.on('swipe', $.proxy(this.ordersListSwipe, this));
        this.$ordersWrapper.on('click', '#prev-screen, #next-screen', $.proxy(this.changeScreen, this));
        this.$ordersWrapper.on('click', '#time-suggestion-btn', $.proxy(this.showTimeSuggestionTable, this));
        this.$ordersWrapper.on('click', '.js-open-map', $.proxy(this.showOnMap, this));
        this.$document.on('click', '#time-shifting .time-btn', $.proxy(this.suggestNewTime, this));
        this.$sendForgottenPwdBtn.on('click', $.proxy(this.sendForgottenPwd, this));
        this.$document.on('click', '.gastro-delivery-times-asap', $.proxy(this.showDeliveryTimeAsapControls, this));
        this.$document.on('click', '.gastro-delivery-times-asap__options a', $.proxy(this.changeDeliveryTimeAsap, this));
    },

    showTimeSuggestionTable: function(event) {
        event.preventDefault();

        $('#modal').modal();
    },

    showOnMap: function(event) {
        event.preventDefault();

        $('#map-modal').modal();
    },

    initOrdersListScreens: function() {
        var i = 0;
        $('.box-for-display').each(function(){
            $(this).css('left', i++ * 100 + '%')
        });
    },
    
    ordersListSwipe: function(event, Dx, Dy) {
        if (Dx < 0) {
            this.swipeRight();
        } else if (Dx > 0) {
            this.swipeLeft();
        }

        $('#current-page').text(this.currentScreen + " / " + this.screensCount);
    },

    changeScreen: function(event) {
        var $el = $(event.target).closest('a');

        event.preventDefault();

        if ($el.attr('id') == 'prev-screen') {
            this.swipeLeft()
        } else {
            this.swipeRight()
        }

        $('#current-page').text(this.currentScreen + " / " + this.screensCount);
    },

    swipeLeft: function() {
        if (this.currentScreen > 1) {
            $('.box-for-display').animate({'left': '+=100%'}, 250);
            this.currentScreen--;
        }
    },

    swipeRight: function() {
        if (this.currentScreen < this.screensCount) {
            $('.box-for-display').animate({'left': '-=100%'}, 250);
            this.currentScreen++;
        }
    },

    initLoadOrdersLoop: function() {
        var that = this;

        setInterval(
            function() {
                $.ajax({
                    type: 'GET',
                    url : '/gastro/orders-acceptation/load-new-orders',
                    success : function(data) {
                        $('#orders').replaceWith(data);

                        that.initOrdersListScreens();

                        that.cacheElements();
                        that.setOrdersHeight();

                        if (that.activeOrderId) {
                            $('.order').each(function() {
                                if ($(this).attr('data-id') == that.activeOrderId) {
                                    $(this).addClass('active');
                                }
                            });
                        }
                    }
                })
            }, 25000);
    },

    initLoadNotificationsLoop: function() {
        var that = this,
            state = 'new';

        if (this.$finishedOrdersWrapper.length) {
            state = 'finished';
        } else if (this.$cancelledOrdersWrapper.length) {
            state = 'cancelled';
        }

        setInterval(
            function() {
                $.ajax({
                    type: 'GET',
                    url : '/gastro/orders-acceptation/load-new-orders-count',
                    data: {state: state},
                    success : function(data) {
                        $('#buttons').replaceWith(data);

                        that.cacheElements();
                    }
                })
            }, 25000);
    },

    showOrderDetail: function(event) {
        event.preventDefault();

        var $el = $(event.target).closest('.order');

        $('.order').removeClass('active');
        $el.addClass('active');

        this.activeOrderId = $el.attr('data-id');

        $('#order-detail').html('<p class="hint">Načítám detail objednávky</p>');
        setSpinnerPosition($('.hint'), 'top');

        $.ajax({
            type: 'GET',
            url : '/gastro/orders-acceptation/load-order-detail',
            data: {order_id: this.activeOrderId},
            success : function(data) {
                $('#spinner').hide();
                $('#order-detail').html(data);

                //that.initNewTimeSuggestionBtn();

                $('#top-scrollable').height($(window).height() - $('#header').outerHeight(true) - $('.bottom-fixed').outerHeight(true) + 'px');
                $('#top-scrollable').slimScroll(
                    {
                        height: $('#order-detail-wrapper #top-scrollable').outerHeight(true)
                    }
                );

            }
        });
    },

    setDeliveryTime: function(event) {
        var $el = $(event.target).closest('.time');

        $('.time').removeClass('active');

        $el.addClass('active');
        $('#delivery-date').val($el.find('input').val());
    },

    suggestNewTime: function(event) {
        var $el = $(event.target).closest('a'),
            $elWrapper = $el.parents('.time-btn'),
            $form = $('#acceptation-form'),
            that = this;

        if ($elWrapper.hasClass('suggestion')) {
            $('.modal').modal('hide');

            var $order = $('#orders').find('.order[data-id = ' + this.activeOrderId + ']');
            setSpinnerPosition($order);
            this.activeOrderId = null;

            $('#order-detail').html('<p class="hint">Zde se po kliknutí na objednávku zobrazí její detail</p>');
            $.ajax({
                type: $form.attr('method'),
                url: $form.attr('action'),
                data: $form.serialize() + "&time_suggestion=" + $elWrapper.find('input').val() + "&submit=new_transportation_confirm",
                success: function (data) {
                    $('#spinner').hide();
                    $order.replaceWith(data);
                    that.setOrdersHeight();
                }
            });
        }
    },

    showDeliveryTimeAsapControls: function (event) {
        event.preventDefault();
        $('.gastro-delivery-times-asap__options').toggle();
    },

    changeDeliveryTimeAsap: function (event) {
        event.preventDefault();

        var $el = $(event.currentTarget);
        var url = $el.attr('href');
        var minutes = parseInt($el.data('minutes'));
        var $elMinutes = $('.delivery-time-asap__minutes');

        $.ajax({
            type: 'GET',
            url: url,
            data: {'minutes': minutes},
            success: function (data) {
                if (data.success) {
                    $elMinutes.text(data.data.minutes);

                    $('.gastro-delivery-times-asap__options a').each(function () {
                        var mins = data.data.minutes + $(this).data('minutes');

                        if (mins > data.data.max || mins < data.data.min) {
                            $(this).attr('disabled', true);
                        } else {
                            $(this).attr('disabled', false);
                        }
                    });
                }
            }
        });
    },

    setOrdersHeight: function() {
        var headerOuterHeight = $('#header').outerHeight(true),
            buttonsOuterHeight = $('#buttons').outerHeight(true);

        $('.order').each(function() {
            var margin = $(this).outerHeight(true) - $(this).outerHeight();
            $(this).outerHeight(($(window).height() -  headerOuterHeight - buttonsOuterHeight) / 4 - margin);
        });

        var padding = this.$orderWrapper.outerHeight(false) - this.$orderWrapper.height();
        this.$orderWrapper.height($(window).height() - headerOuterHeight - padding + 'px');
        this.$ordersListWrapper.height($(window).height() - headerOuterHeight - buttonsOuterHeight + 'px');

        $('#top-scrollable').height($(window).height() - headerOuterHeight - $('.bottom-fixed').outerHeight(true) + 'px');
        $('#top-scrollable').slimScroll(
            {
                height: $('#top-scrollable').outerHeight(true)
            }
        );
    },

    sendForgottenPwd: function(event) {
        event.preventDefault();
        grecaptcha.execute();
    }
};

;
$().ready(function() {
    frontend.Gastro.OrdersAcceptation.init();
});

;
