$(document).ready(function() {
    sam.calendarWidget.init();
});

sam.calendarWidget = new function() {
    var that = this;

    //Используемые классы
    var classes = {
        'league'    : 'js-calendar-widget-league-select',
        'tournament': 'js-calendar-widget-tournament-select',
        'child'     : 'js-calendar-widget-child-select',
        'round'     : 'js-calendar-widget-round-select',
        'data'      : 'js-calendar-widget-data',
        'header'    : 'js-calendar-widget-header',
        'cont'      : 'js-calendar-widget-cont',
        'widget'    : 'js-calendar-widget',
        'saveState' : 'js-calendar-widget-save-state',
        'filters'   : 'js-calendar-widget-selects',
        'notShow'   : 'js-calendar-widget-not-show',
        'popup'     : 'js-calendar-widget-popup',
        'game'      : 'js-calendar-widget-game',
        'gamePopup' : 'js-calendar-widget-game-popup-',
        'loader'    : 'loader'
    };

    //Используемые селекторы
    var selectors = {
        'league'    : '.' + classes.league,
        'tournament': '.' + classes.tournament,
        'child'     : '.' + classes.child,
        'round'     : '.' + classes.round,
        'data'      : '.' + classes.data,
        'header'    : '.' + classes.header,
        'cont'      : '#' + classes.cont,
        'widget'    : '#' + classes.widget,
        'saveState' : '.' + classes.saveState,
        'filters'   : '.' + classes.filters,
        'notShow'   : '.' + classes.notShow,
        'popup'     : '.' + classes.popup,
        'game'      : '.' + classes.game,
        'gamePopup' : '#' + classes.gamePopup,
        'loader'    : '.' + classes.loader
    };

    //Виджет
    var $widget = $(selectors.widget);

    //Связанные фильтры
    var visible = {
        'league'    : [selectors.tournament, selectors.child, selectors.round],
        'tournament': [selectors.child, selectors.round],
        'child'     : [selectors.round],
        'round'     : [selectors.data]
    };

    this.init = function() {
        //Получение данных виджета по выбору лиги
        $widget.on('click', selectors.league + ' li', function() {
            that.select.league(this);
        });

        //Получение данных виджета по выбору турнира
        $widget.on('click', selectors.tournament + ' li', function() {
            that.select.tournament(this);
        });

        //Получение данных виджета по выбору дочернего турнира
        $widget.on('click', selectors.child + ' li', function() {
            that.select.child(this);
        });

        //Получение данных виджета по выбору этапа
        $widget.on('click', selectors.round + ' li', function() {
            that.select.round(this);
        });

        //Поп-ап матча
        that.popup.init();
    };

    this.select = {
        //Выбор лиги
        league    : function(el) {
            that.filter.hide(visible.league);
            that.filter.toggle(el);

            var leagueId = $(el).data('value');
            that.filter.show(visible.league, '[data-league="' + leagueId + '"]');

            $(selectors.tournament + '[data-league="' + leagueId + '"] li.js-active').click();
        },

        //Выбор турнира
        tournament: function(el) {
            $(selectors.saveState).removeClass(classes.saveState).addClass('js-active');
            that.filter.hide(visible.tournament);
            that.filter.toggle(el);

            var parentId = $(el).data('value');
            that.filter.show(visible.tournament, '[data-parent="' + parentId + '"]');

            if ($(el).data('isParent')) {
                $(selectors.child + '[data-parent="' + parentId + '"] li.js-active').click();
            } else {
                $(selectors.round + '[data-parent="' + parentId + '"] li.js-active').click();
            }
        },

        //Выбор дочернего турнира
        child     : function(el) {
            that.filter.hide(visible.child);
            that.filter.toggle(el);

            var childId = $(el).data('value'), select = $(selectors.round + '[data-child="' + childId + '"] ul');
            if ($(select).find('li').length > 1) {
                that.filter.show(visible.child, '[data-child="' + childId + '"]');
            }

            $(select).find('li.js-active').click();
        },

        //Выбор этапа
        round     : function(el) {
            that.filter.hide(visible.round);
            that.filter.toggle(el);

            var leagueId = $(el).parents(selectors.round).data('league'),
                tournamentId = $(el).parents(selectors.round).data('tournament'),
                roundId = $(el).data('value'),
                roundDataClass =
                    selectors.data +
                    '[data-league="' + leagueId + '"]' +
                    '[data-tournament="' + tournamentId + '"]' +
                    '[data-round="' + roundId + '"]';
            that.cookie.saveFilters(leagueId, tournamentId, roundId);

            if (that.filter.exists(roundDataClass, selectors.cont)) {
                $(roundDataClass).show(0, function() {
                    that.state.open();
                });
            } else {
                $(selectors.cont).find(selectors.loader).show();

                var data = $('#calendarWidgetParams').data();
                data.leagueId = leagueId;
                data.tournamentId = tournamentId;
                data.roundId = roundId;
                $.ajax({
                    'url'     : $widget.data('url'),
                    'type'    : 'POST',
                    'dataType': 'json',
                    'data'    : {
                        '_csrf' : sam._csrf,
                        'params': data
                    },
                    'success' : function(data) {
                        $(selectors.cont).find(selectors.loader).hide();
                        $(selectors.cont).append(data.html);
                        $(selectors.cont).find('.js-slick:visible:not(.js-already-init)').each(function() {
                            sam.slick.build(this);
                        });

                        that.state.open();
                        that.popup.init();
                    }
                });
            }
        }
    };

    this.cookie = {
        //Сохранение пользовательских фильтров
        saveFilters: function(leagueId, tournamentId, roundId) {
            var data = that.cookie.get();

            data.open = $(selectors.header).hasClass('js-open') ? 1 : 0;
            data.leagueId = leagueId;
            data.tournamentId = tournamentId;
            data.roundId = roundId;

            that.cookie.save(data);
        },

        //Получение пользовательских фильтров
        get        : function() {
            var leagueId = $widget.data('leagueId');
            if ($.cookie('calendar')) {
                var data = JSON.parse($.cookie('calendar'));
                if (data[leagueId]) {
                    return data[leagueId];
                }
            }

            return {
                'params': {}
            };
        },

        //Сохранение cookie
        save       : function(obj) {
            var leagueId = $widget.data('leagueId'), saveObj = {};
            saveObj[leagueId] = obj;
            $.cookie('calendar', JSON.stringify(saveObj));
        }
    };

    this.filter = {
        //Скрытие фильтров
        hide  : function(elementsSelectors) {
            $.each(elementsSelectors, function(k, selector) {
                $(selector).hide();
            });
        },

        //Вскрытие фильтров
        show  : function(elementsSelectors, additional) {
            if (!additional) {
                additional = '';
            }
            $.each(elementsSelectors, function(k, selector) {
                selector += additional;
                if (that.filter.exists(selector) && !$(selector).hasClass(classes.notShow)) {
                    $(selector).show();
                }
            });
        },

        //Проверка на существование фильтра
        exists: function(selector, parent) {
            if (!parent) {
                parent = selectors.widget;
            }
            return $(parent).find(selector).length;
        },

        //Переключение состояния фильтра
        toggle: function(el) {
            $(el).parents('ul').find('li.js-active').removeClass('js-active');
            $(el).addClass('js-active');
        }
    };

    this.state = {
        //Сохранение состояния календаря
        save   : function() {
            var widgetParams = that.cookie.get();
            widgetParams.params.open = $(selectors.header).hasClass('js-open') ? 1 : 0;

            that.cookie.save(widgetParams);
        },

        //Открытие календаря
        open   : function() {
            var $header = $widget.find(selectors.header);
            if (!$header.hasClass('js-open')) {
                $header.click();
            }
        },

        //Колбек раскрытия календаря
        enable : function() {
            that.state.save();
            $(selectors.filters).show();
            $(selectors.cont).find('.js-slick:visible:not(.js-already-init)').each(function() {
                sam.slick.build(this);
            });
            $(selectors.saveState).removeClass(classes.saveState).addClass('js-active');
        },

        //Колбек закрытия календаря
        disable: function() {
            $(selectors.filters).hide();
            that.state.save();

            $(selectors.tournament).find('li.js-active').removeClass('js-active').addClass(classes.saveState);
        }
    };

    this.popup = {
        params    : {
            'animationSpeed': 200,
            'hoverDelay'    : 500,
            'waiting'       : {}
        },

        //Инициирует наведение мышки на матч
        init      : function() {
            $(selectors.game)
                .on('mouseenter', function() {
                    var el = this, popupId = that.popup.getPopupId(el);
                    that.popup.params.waiting[popupId] = true;
                    setTimeout(function() {
                        if (that.popup.params.waiting[popupId]) {
                            that.popup.open(el);
                        }
                    }, that.popup.params.hoverDelay);
                })
                .on('mouseleave', function() {
                    var popupId = that.popup.getPopupId(this);
                    that.popup.params.waiting[popupId] = false;
                    that.popup.close(this);
                });
        },

        //Раскрытие попапа
        open      : function(el) {
            var popupId = that.popup.getPopupId(el, true);
            if ($(popupId).length) {
                var popup = $(popupId);
                that.popup.setOffset(el, popup);
                $(popup).fadeIn(that.popup.params.animationSpeed);
            } else {
                that.popup.create(el);
            }
        },

        //Скрытие попапа
        close     : function(el) {
            var popupId = that.popup.getPopupId(el, true),
                popup = $(popupId);

            if (!$(popupId + ':hover').length) {
                $(popup).fadeOut(that.popup.params.animationSpeed)
            }
        },

        //Создание попапа
        create    : function(el) {
            var popup = $('<div>', {'id': that.popup.getPopupId(el), 'class': 'popup' + ' ' + classes.popup}).hide(),
                loader = $('<img>', {'src': '/img/loader.gif', 'class': 'loader'});
            $(popup).append(loader);
            that.popup.setOffset(el, popup);
            $widget.append(popup);
            that.popup.open(el);

            $(popup).on('mouseleave', function() {
                that.popup.close(el);
            });

            $.ajax({
                'url'     : $widget.data('gameUrl'),
                'type'    : 'POST',
                'dataType': 'json',
                'data'    : {
                    '_csrf'  : sam._csrf,
                    'gameId': $(el).data('gameId')
                },
                'success' : function(data) {
                    if (data.success) {
                        $(popup).html(data.html);
                    } else {
                        that.popup.close(el);
                    }
                }
            });
        },

        //Получение #id попапа
        getPopupId: function(el, octothorpe) {
            return (octothorpe ? '#' : '') + classes.gamePopup + $(el).data('gameId');
        },

        //Устанавливает позиционирование попапа
        setOffset : function(el, popup) {
            var offset = $(el).offset();
            popup.css({
                'bottom': -126,
                'left'  : offset.left - 273 / 2 + 5
            })
        }
    };
};

sam.collapse.callbacks.calendarEnable = function() {
    sam.calendarWidget.state.enable();
};

sam.collapse.callbacks.calendarDisable = function() {
    sam.calendarWidget.state.disable();
};
