"use strict";
var radikoTop = function () {
    (function (window, $, Backbone, _, moment, undefined) {
        loadTemplate({
            '#contents': '/apps/templates/top/index.html',
            '#footer': '/apps/templates/common/footer.html'
        }, function () {
            (function (Radiko) {
                var Top = (function () {
                    function Top() {
                        this.superBannerCollection = null;
                        this.nowOnAirCollection = null;
                        this.prImageCollection = null;
                        this.infoCollection = null;
                    }
                    Top.prototype.initialize = function () {
                        var _this = this;
                        var intervalId = setInterval(function () {
                            if (Object.keys($.Radiko.user_station_list).length) {
                                _this.createModels();
                                _this.createViews();
                                _this.fetchAll([
                                    {
                                        model: _this.superBannerCollection
                                    }, {
                                        model: _this.nowOnAirCollection
                                    }, {
                                        model: _this.prImageCollection
                                    }, {
                                        model: _this.infoCollection
                                    }, {
                                        model: _this.recommendProgramModel
                                    }
                                ]);
                                _this.subscribeAll();
                                clearInterval(intervalId);
                            }
                        }, 100);
                    };
                    Top.prototype.createModels = function () {
                        this.superBannerCollection = new SuperBannerCollection();
                        this.nowOnAirCollection = new NowOnAirCollection();
                        this.prImageCollection = new PrImageCollection();
                        this.infoCollection = new InfoCollection();
                        this.recommendProgramModel = window.Radiko.Recommend.RecommendProgramModel;
                    };
                    Top.prototype.createViews = function () {
                        $.Radiko.views.push(new SuperBannerView({
                            el: document.getElementById('super_banner'),
                            collection: this.superBannerCollection
                        }));
                        $.Radiko.views.push(new PrImageListView({
                            el: document.getElementById('pr-image-slider'),
                            collection: this.prImageCollection
                        }));
                        $.Radiko.views.push(new SearchFormView({
                            el: document.getElementById('to-search')
                        }));
                        $.Radiko.views.push(new NowOnAirListView({
                            el: document.getElementById('now_on_air'),
                            collection: this.nowOnAirCollection
                        }));
                        $.Radiko.views.push(new InfoListView({
                            el: document.getElementById('top-info'),
                            collection: this.infoCollection
                        }));
                        $.Radiko.views.push(new HistoryProgramView({
                            el: document.getElementById('history'),
                            model: window.Radiko.History.collection
                        }));
                        $.Radiko.views.push(new PopularProgramView({
                            el: document.getElementById('popular'),
                            model: window.Radiko.Popular.PopularProgramModel
                        }));
                        $.Radiko.views.push(new RecommendProgramView({
                            el: document.getElementById('recommend'),
                            model: this.recommendProgramModel
                        }));
                    };
                    Top.prototype.fetchAll = function (models) {
                        return $.when.apply($, _.map(models, function (queue) {
                            return queue.model.fetch(queue.options || {});
                        }));
                    };
                    Top.prototype.subscribeAll = function () {
                        $.Radiko.EventEmitter.once(window.Radiko.Event.KEY.COMPLETE_STATION_FETCH, function () {
                            window.Radiko.Popular.PopularProgramModel.fetch();
                        });
                    };
                    return Top;
                }());
                Radiko.Top = Top;
                var PrImageModel = Backbone.Model.extend({
                    defaults: {
                        id: '',
                        name: '',
                        banner: ''
                    }
                });
                var PrImageCollection = Backbone.Collection.extend({
                    model: PrImageModel,
                    initialize: function () {
                        this.areaId = $.cookie('default_area_id');
                    },
                    url: function () {
                        return '/v3/station/list/' + this.areaId + '.xml';
                    },
                    fetch: function (options) {
                        return Backbone.Collection.prototype.fetch.call(this, _.extend({
                            dataType: 'xml'
                        }, options));
                    },
                    parse: function (resp) {
                        return _.map($('station', resp), function (station) {
                            var $station = $(station);
                            return {
                                id: $station.find('id').first().text(),
                                name: $station.find('name').first().text(),
                                banner: $station.find('banner').first().text()
                            };
                        }, this);
                    }
                });
                var HistoryProgramView = Backbone.View.extend({
                    initialize: function () {
                        var _this = this;
                        var checkUntilUSTrue = setInterval(function () {
                            if ($.Radiko.user_station_list) {
                                clearInterval(checkUntilUSTrue);
                                _this.render(_this.model);
                            }
                        }, 1000);
                    },
                    onSync: function (collection) {
                        this.render(collection);
                    },
                    render: function (collection) {
                        this.renderList(collection.slice(0, 10));
                        this.afterRender();
                    },
                    renderList: function (model) {
                        var _this = this;
                        if (!model.length) {
                            this.$el.hide();
                            return;
                        }
                        var programs = _.map(model, function (model) {
                            var program = model.toJSON();
                            return _.extend(model.toJSON(), {
                                schedule: _this.createScheduleString(program.start, program.end),
                                status: window.Radiko.CONST.BROADCAST.STATUS.TF,
                                is_premium: !_this.canPlayStation(model.get('station_id')),
                                tracking: {
                                    station_id: program.station_id,
                                    program_title: program.title,
                                    start_time: program.start.format('YYYY-MM-DD hh:mm'),
                                    action: 'click',
                                    category: 'top',
                                    label: 'program_history'
                                }
                            });
                        });
                        this.$el.html(JST['top/program-carousel']({
                            label_name: '聴取履歴',
                            link: {
                                href: '/#!/history',
                                name: '聴取履歴一覧'
                            },
                            programs: programs,
                            tracking: {
                                label: 'list_history'
                            }
                        }));
                    },
                    afterRender: function () {
                        var prevArrow = JST['top/previous-red-arrow']({
                            label: 'previous_history'
                        });
                        var nextArrow = JST['top/next-red-arrow']({
                            label: 'next_history'
                        });
                        this.$el.find('.img-list__carousel').slick({
                            infinite: true,
                            slidesToShow: 4,
                            autoplay: false,
                            prevArrow: prevArrow,
                            nextArrow: nextArrow
                        });
                        this.$el.find('.img-list__item').heightLine();
                    }
                });
                _.extend(HistoryProgramView.prototype, $.Radiko.Mixins.Utility, window.Radiko.User);
                var RecommendProgramView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.model, 'sync', this.onSync);
                        this.effectedSlick = false;
                    },
                    onSync: function (model) {
                        this.render(model);
                    },
                    render: function (model) {
                        var recommend;
                        if (model.get('is_ranking')) {
                            recommend = model.get('recommend');
                        }
                        else {
                            recommend = model.get('recommend').slice(0, 10);
                        }
                        this.renderList(recommend);
                        this.afterRender(model);
                    },
                    renderList: function (collection) {
                        var _this = this;
                        this.$el.html();
                        if (this.effectedSlick) {
                            this.$el.slick('unslick');
                        }
                        var programs = collection.map(function (model) {
                            return _this.processModelData(model);
                        });
                        this.$el.html(JST['top/program-carousel']({
                            label_name: 'あなたへ',
                            link: {
                                href: '/#!/recommend',
                                name: 'あなたへ一覧'
                            },
                            programs: programs,
                            tracking: {
                                label: 'list_recommend'
                            }
                        }));
                    },
                    noaClickHandler: function (e) {
                        var $program = $(e.currentTarget);
                        var stationId = $program.data('station_id').toString();
                        if (!window.Radiko.User.canPlayStation(stationId)) {
                            $.colorbox({
                                width: '60%',
                                inline: true,
                                href: '#colorbox--premium',
                                speed: 0,
                                open: true,
                                opacity: 0.5
                            });
                            return false;
                        }
                        window.Radiko.Logger.Recommend.referrerType = window.Radiko.Logger.Recommend.TYPE.USER;
                        window.Radiko.Logger.Recommend.toURL = $program.attr('href');
                    },
                    processModelData: function (model) {
                        var program = model.get('program').toJSON();
                        return _.extend(program, {
                            station_id: model.get('station_id'),
                            station_name: model.get('station_name'),
                            schedule: this.createScheduleString(program.start, program.end),
                            status: window.Radiko.CONST.BROADCAST.STATUS.TF,
                            tracking: {
                                station_id: model.get('station_id'),
                                program_title: program.title,
                                start_time: program.start.format('YYYY-MM-DD hh:mm'),
                                action: 'click',
                                category: 'top',
                                label: 'program_recommend'
                            }
                        });
                    },
                    afterRender: function (model) {
                        var prevArrow = JST['top/previous-red-arrow']({
                            label: 'previous_recommend'
                        });
                        var nextArrow = JST['top/next-red-arrow']({
                            label: 'next_recommend'
                        });
                        this.$el.find('.img-list__carousel').slick({
                            infinite: true,
                            slidesToShow: 4,
                            autoplay: false,
                            prevArrow: prevArrow,
                            nextArrow: nextArrow
                        });
                        this.effectedSlick = true;
                        var timeTillExpire = window.Radiko.Date.getMsTillExpire(model.get('expires_at'));
                        if (timeTillExpire) {
                            setTimeout(function () {
                                return model.fetch();
                            }, timeTillExpire);
                        }
                        this.$el.find('.img-list__item').heightLine();
                        this.$el.on('click', '.img-list__link', this.noaClickHandler);
                    }
                });
                _.extend(RecommendProgramView.prototype, $.Radiko.Mixins.Utility, window.Radiko.User);
                var PopularProgramView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.model, 'sync', this.onSync);
                        if (this.model.get('recommend')) {
                            this.render(this.model);
                        }
                    },
                    onSync: function (model) {
                        this.render(model);
                    },
                    render: function (model) {
                        this.effectedSlick = false;
                        var recommend = model.get('recommend');
                        this.renderList(recommend);
                        this.afterRender(model);
                    },
                    renderList: function (collection) {
                        var _this = this;
                        this.$el.html();
                        if (this.effectedSlick) {
                            this.$el.slick('unslick');
                        }
                        var programs = collection.map(function (model) {
                            return _this.processModelData(model);
                        });
                        this.$el.html(JST['top/program-carousel']({
                            label_name: '人気番組',
                            link: {
                                href: '/#!/popular',
                                name: '人気番組一覧'
                            },
                            programs: programs,
                            tracking: {
                                label: 'list_popular'
                            }
                        }));
                    },
                    noaClickHandler: function (e) {
                        var $program = $(e.currentTarget);
                        var stationId = $program.data('station_id').toString();
                        if (!window.Radiko.User.canPlayStation(stationId)) {
                            $.colorbox({
                                width: '60%',
                                inline: true,
                                href: '#colorbox--premium',
                                speed: 0,
                                open: true,
                                opacity: 0.5
                            });
                            return false;
                        }
                        window.Radiko.Logger.Recommend.referrerType = window.Radiko.Logger.Recommend.TYPE.POPULAR;
                        window.Radiko.Logger.Recommend.toURL = $program.attr('href');
                    },
                    processModelData: function (model) {
                        var program = model.get('program').toJSON();
                        return _.extend(program, {
                            station_id: model.get('station_id'),
                            station_name: model.get('station_name'),
                            schedule: this.createScheduleString(program.start, program.end),
                            status: window.Radiko.CONST.BROADCAST.STATUS.TF,
                            tracking: {
                                station_id: model.get('station_id'),
                                program_title: program.title,
                                start_time: program.start.format('YYYY-MM-DD hh:mm'),
                                action: 'click',
                                category: 'top',
                                label: 'program_popular'
                            }
                        });
                    },
                    afterRender: function (model) {
                        var prevArrow = JST['top/previous-red-arrow']({
                            label: 'previous_popular'
                        });
                        var nextArrow = JST['top/next-red-arrow']({
                            label: 'next_popular'
                        });
                        this.$el.find('.img-list__carousel').slick({
                            infinite: true,
                            slidesToShow: 4,
                            autoplay: false,
                            prevArrow: prevArrow,
                            nextArrow: nextArrow
                        });
                        this.effectedSlick = true;
                        var timeTillExpire = window.Radiko.Date.getMsTillExpire(model.get('expires_at'));
                        if (timeTillExpire) {
                            setTimeout(function () {
                                return model.fetch();
                            }, timeTillExpire);
                        }
                        this.$el.find('.img-list__item').heightLine();
                        this.$el.on('click', '.img-list__link', this.noaClickHandler);
                    }
                });
                _.extend(PopularProgramView.prototype, $.Radiko.Mixins.Utility, window.Radiko.User);
                var PrImageListView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.collection, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        this.render(models);
                    },
                    render: function (models) {
                        this.$el
                            .empty()
                            .html(JST['top/pr-image-slider']({ 'list': models.toJSON() }));
                        this.defineUi();
                        return this;
                    },
                    defineUi: function () {
                        var prevArrow = JST['top/previous-arrow']();
                        var nextArrow = JST['top/next-arrow']();
                        this.$('.js-slider').slick({
                            infinite: true,
                            slidesToShow: 4,
                            autoplay: true,
                            autoplaySpeed: 5000,
                            prevArrow: prevArrow,
                            nextArrow: nextArrow
                        });
                    }
                });
                var SearchFormView = Backbone.View.extend({
                    initialize: function () {
                        this.currentDate = moment();
                        this.minDate = moment().add(-7, 'd');
                        this.maxDate = moment().add(6, 'd');
                        this.areaId = $.Radiko.area.id;
                        this.render();
                    },
                    render: function () {
                        this.setDateOption();
                        var all = $('<option></option>', {
                            value: 'all',
                            text: '全国'
                        });
                        var area = $('<option></option>', {
                            value: '',
                            text: $.Radiko.areaList[parseInt(($.cookie('default_area_id').replace('JP', '')), 10) - 1]
                        });
                        if ($.Radiko.login_status.premium) {
                            this.$('[name="region_id"]').html(all[0].outerHTML + area[0].outerHTML);
                        }
                        else {
                            this.$('[name="region_id"]').html(area[0].outerHTML + all[0].outerHTML);
                        }
                        var $searchForm = $('#search-form');
                        var searchText = $searchForm.find('.form__text');
                        searchText.focus(function () {
                            $(this).animate({
                                backgroundColor: "#fff"
                            }, 500);
                        });
                        searchText.blur(function () {
                            $(this).animate({
                                backgroundColor: "#f2f2f2"
                            }, 500);
                        });
                        if ($('.easy-select-box').length == 0) {
                            $searchForm.find("select").easySelectBox({
                                onClick: function () {
                                    $searchForm.find(".esb-displayer").append('<i class="icon icon--arrow-d"></i>');
                                }
                            });
                        }
                        $searchForm.on('submit', function () {
                            var key = $('#search-form').find('[name="key"]').val();
                            if (key == '') {
                                alert('検索機能の利用には、検索キーワードの入力が必要です');
                                return false;
                            }
                            var searchDate = $searchForm.find('[name=date]').val();
                            var regionId = $searchForm.find('[name=region_id]').val();
                            dataLayer.push({
                                'event': 'FireTdEvent',
                                'eCategory': 'top',
                                'eAction': 'click',
                                'eLabel': 'search_button',
                                'eAreaId': regionId ? regionId : $.cookie('default_area_id'),
                                'eSearchWord': $searchForm.find('[name=key]').val(),
                                'eSearchDate': searchDate ? searchDate : 'all',
                                'eStreamType': 'all'
                            });
                            var query = window.Radiko.URL.buildQuery({
                                key: key,
                                filter: '',
                                start_day: searchDate,
                                end_day: searchDate,
                                region_id: regionId,
                                area_id: $.cookie('default_area_id'),
                                cul_area_id: $.cookie('default_area_id'),
                                page_idx: 0
                            });
                            location.href = '/#!/search/live?' + query;
                            return false;
                        });
                        $searchForm.find(".esb-displayer").append('<i class="icon icon--arrow-d"></i>');
                        $.Radiko.Suggest.currentKeyWord = $searchForm.find('input[name=key]').val();
                    },
                    setDateOption: function () {
                        var counter;
                        var select = this.$('select[name=date]');
                        var all = $('<option></option>', {
                            value: '',
                            text: 'すべて'
                        });
                        select.append(all[0].outerHTML);
                        var minDate = $('<option></option>', {
                            value: this.minDate.format('YYYY-MM-DD'),
                            text: this.minDate.format('YYYY年MM月DD日(ddd)')
                        });
                        select.append(minDate[0].outerHTML);
                        for (counter = -6; counter <= -1; counter++) {
                            var bd = moment();
                            bd.add(counter, 'days');
                            var beforeDate = $('<option></option>', {
                                value: bd.format('YYYY-MM-DD'),
                                text: bd.format('YYYY年MM月DD日(ddd)')
                            });
                            select.append(beforeDate[0].outerHTML);
                        }
                        var today = $('<option></option>', {
                            value: moment().format('YYYY-MM-DD'),
                            text: '本日'
                        });
                        select.append(today[0].outerHTML);
                        for (counter = 1; counter <= 5; counter++) {
                            var ad = moment();
                            ad.add(counter, 'days');
                            var afterDate = $('<option></option>', {
                                value: ad.format('YYYY-MM-DD'),
                                text: ad.format('YYYY年MM月DD日(ddd)')
                            });
                            select.append(afterDate[0].outerHTML);
                        }
                        var maxDate = $('<option></option>', {
                            value: this.maxDate.format('YYYY-MM-DD'),
                            text: this.maxDate.format('YYYY年MM月DD日(ddd)')
                        });
                        select.append(maxDate[0].outerHTML);
                    },
                    events: {
                        'keyup input[name=key]': $.Radiko.Suggest.keyUpHandler,
                        'change': 'changeHandler'
                    },
                    changeHandler: function (ev) {
                        var target = ev.target;
                        var name = target.name;
                        var val = target.value;
                        if (name === 'date') {
                            var startDay = '';
                            var endDay = '';
                            switch (val) {
                                case 'all':
                                    break;
                                case 'last':
                                    startDay = this.minDate.format('YYYY-MM-DD');
                                    endDay = this.minDate.format('YYYY-MM-DD');
                                    break;
                                case 'today':
                                    startDay = this.currentDate.format('YYYY-MM-DD');
                                    endDay = this.currentDate.format('YYYY-MM-DD');
                                    break;
                                case 'next':
                                    startDay = this.maxDate.format('YYYY-MM-DD');
                                    endDay = this.maxDate.format('YYYY-MM-DD');
                                    break;
                                default:
                                    startDay = val;
                                    endDay = val;
                                    break;
                            }
                            this.$('[name="start_day"]').val(startDay);
                            this.$('[name="end_day"]').val(endDay);
                        }
                    },
                    onClose: function () {
                        if (this.collection != undefined) {
                            this.collection.remove();
                        }
                    }
                });
                var ProgramModel = Backbone.Model.extend({
                    idAttribute: 'station_id',
                    defaults: {
                        id: '',
                        name: '',
                        progTitle: '',
                        progPfm: '',
                        progSchedule: '',
                        progImage: ''
                    }
                });
                var NowOnAirCollection = Backbone.Collection.extend({
                    model: ProgramModel,
                    initialize: function () {
                        this.areaId = $.cookie('default_area_id');
                    },
                    url: function () {
                        return '/v3/program/now/' + this.areaId + '.xml';
                    },
                    fetch: function (options) {
                        return Backbone.Collection.prototype.fetch.call(this, _.extend({
                            dataType: 'xml',
                            cache: false
                        }, options));
                    },
                    parse: function (resp) {
                        var _this = this;
                        return _.filter($('station', resp), function (station) {
                            var $station = $(station);
                            return _.contains($.Radiko.user_station_list, $station.attr('id')) || +$(_this).find('areafree').text() !== 0;
                        })
                            .map(function (station) {
                            var $station = $(station);
                            var $prog = $station.find('prog').first();
                            var img = $prog.find('img').text();
                            if (img == '') {
                                img = '/images/radio-api-noimage_live.png';
                            }
                            return {
                                station_id: $station.attr('id'),
                                station_name: $station.find('name').first().text(),
                                title: $prog.find('title').first().text(),
                                performer: $prog.find('pfm').first().text(),
                                schedule: (_this.dateToFormatedString($prog.attr('ft'), 'M月D日（ddd） HH:mm')) + '-' + (_this.dateToFormatedString($prog.attr('to'), 'HH:mm')),
                                thumbnail: img,
                                link: "/#!/live/" + $station.attr('id'),
                                start: moment($prog.attr('ft'), ' YYYYMMDDHHmmss')
                            };
                        });
                    }
                });
                _.extend(NowOnAirCollection.prototype, $.Radiko.Mixins.Utility);
                var NowOnAirListView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.collection, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        this.render(models);
                    },
                    render: function (models) {
                        var programs = _.map(models.toJSON(), function (program) {
                            program.tracking = {
                                station_id: program.station_id,
                                program_title: program.title,
                                start_time: program.start.format('YYYY-MM-DD hh:mm'),
                                category: 'top',
                                action: 'click',
                                label: 'program_live'
                            };
                            return program;
                        });
                        this.$el.empty().html(JST['common/program-card-list']({ programs: _.shuffle(programs) }));
                        $(".img-list>.img-list__item").heightLine();
                        if (window.isScroll) {
                            window.isScroll = false;
                            var scrollTop = $('.content__top-onair').offset().top - $('#header-nav').height();
                            window.scrollTo(0, scrollTop);
                        }
                        return this;
                    },
                    onClose: function () {
                        if (this.collection != undefined) {
                            this.collection.remove();
                        }
                    }
                });
                var InfoModel = Backbone.Model.extend({
                    defaults: {}
                });
                var InfoCollection = Backbone.Collection.extend({
                    model: InfoModel,
                    initialize: function () {
                        this.areaId = $.cookie('default_area_id');
                    },
                    url: function () {
                        return '/v2/information2/' + this.areaId + '.xml';
                    },
                    fetch: function (options) {
                        options.cache = false;
                        return Backbone.Collection.prototype.fetch.call(this, _.extend({
                            dataType: 'xml'
                        }, options));
                    },
                    parse: function (resp) {
                        var informationList = [];
                        var maintenanceList = [];
                        _.map($('info', resp), function (info) {
                            var $info = $(info);
                            var infoData = {
                                id: $info.attr('id'),
                                categoryId: $info.attr('category_id'),
                                categoryName: $info.attr('category_name'),
                                stationId: $info.attr('station_id'),
                                stationName: $info.attr('station_name'),
                                date: $info.find('date').first().text(),
                                title: $info.find('title').first().text(),
                                body: $info.find('body').first().text()
                            };
                            if ($info.attr('category_id') === 'maitenance') {
                                maintenanceList.push(infoData);
                            }
                            else {
                                informationList.push(infoData);
                            }
                        }, this);
                        return {
                            informationList: informationList.slice(0, 3),
                            maintenanceList: maintenanceList.slice(0, 3)
                        };
                    }
                });
                var InfoListView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.collection, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        this.render(models);
                    },
                    render: function (models) {
                        var data = models.toJSON();
                        var $info = $('#info');
                        var $maintenance = $('#maintenance');
                        $info.html(JST['top/top-info']({ informationList: data[0].informationList }));
                        $maintenance.html(JST['top/top-maintenance']({ maintenanceList: data[0].maintenanceList }));
                        $('.top-info__list').height(Math.max($info.height(), $maintenance.height()));
                        return this;
                    },
                    onClose: function () {
                        if (this.collection != undefined) {
                            this.collection.remove();
                        }
                    }
                });
                var SuperBannerModel = Backbone.Model.extend({
                    defaults: {
                        models: []
                    }
                });
                var SuperBannerCollection = Backbone.Collection.extend({
                    model: SuperBannerModel,
                    url: '/v3/feed/pc/web_top_superbnr/web_top_superbnr.xml',
                    parse: function (resp) {
                        var bannerData = this.filterRandomBanner(resp);
                        return _.map(bannerData, function (item) {
                            var $item = $(item);
                            return {
                                desc: $item.attr('desc'),
                                href: $item.attr('href'),
                                img: $item.attr('img_468x60'),
                                evid: $item.attr('evid'),
                                target: $item.attr('target')
                            };
                        }, this);
                    },
                    filterRandomBanner: function (resp) {
                        var bannerData = $();
                        var uniqueArray = [];
                        _.map($('item', resp), function (item) {
                            var $item = $(item);
                            var random = $item.attr('random_group');
                            if (random !== "") {
                                uniqueArray[random] == undefined ? uniqueArray[random] = [] : null;
                                uniqueArray[random].push($item);
                            }
                            else {
                                bannerData = bannerData.add($item);
                            }
                        });
                        uniqueArray.forEach(function (value, index) {
                            var item = value[Math.floor(Math.random() * value.length)];
                            uniqueArray[index][0] = item;
                        });
                        uniqueArray.forEach(function (value) {
                            bannerData = bannerData.add(value[0]);
                        });
                        return bannerData;
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = 'xml';
                        options.cache = false;
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    }
                });
                var SuperBannerView = Backbone.View.extend({
                    events: {
                        'click a': 'onClick'
                    },
                    initialize: function () {
                        this.listenTo(this.collection, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        this.render(models);
                        this.adaptSlick();
                    },
                    onClick: function (e) {
                        $('.top-main-slider__list').find('a').on('click', function (e) {
                            var evid = $(this).data('evid');
                            if (evid) {
                                $.Radiko.logger.ad_log("click.gif?ad_id=" + evid);
                            }
                        });
                    },
                    render: function (models) {
                        $('#super_banner').html(JST['top/super-banner']({
                            models: models.toJSON()
                        }));
                        return this;
                    },
                    adaptSlick: function () {
                        var kvSlider = $('.kv-slider').slick({
                            infinite: true,
                            slidesToShow: 1,
                            autoplay: true,
                            autoplaySpeed: 5000,
                            initialSlide: 0,
                            prevArrow: '<ul class="top-slider__nav"><li class="item item--prev"><i class="icon icon--prev-02"></i><span>前へ</span></li></ul>',
                            nextArrow: '<ul class="top-slider__nav"><li class="item item--next"><i class="icon icon--next-02"></i><span>次へ</span></li></ul>'
                        });
                        var evid = $('.slick-slide[data-slick-index=' + kvSlider.slick('slickCurrentSlide') + ']').find('a').data('evid');
                        if (evid) {
                            $.Radiko.logger.ad_log("view.gif?ad_id=" + evid);
                        }
                        kvSlider.on('afterChange', function (slick, currentSlide) {
                            var evid = $('.slick-slide[data-slick-index=' + currentSlide.currentSlide + ']').find('a').data('evid');
                            if (evid) {
                                $.Radiko.logger.ad_log("view.gif?ad_id=" + evid);
                            }
                        });
                        $('.item__prev').on('click', function () {
                            kvSlider.slick('slickPrev');
                        });
                        $('.item__next').on('click', function () {
                            kvSlider.slick('slickNext');
                        });
                    }
                });
            })($.Radiko || ($.Radiko = {}));
            $('#header').html(JST['common/header']({ logo: '/apps/images/img_logo_blue_01.png', top: true }));
            var top = new $.Radiko.Top();
            $.Radiko.EventEmitter.once('radikoready', function () {
                top.initialize();
                makeHeader($.cookie('default_area_id'));
                setMetaText();
                $('input[type="text"]').placeholder();
                var $topInfoList = $('.top-info__list');
                $topInfoList.off('click', 'a:not([href^=http])');
                $topInfoList.on('click', 'a:not([href^=http])', function () {
                    $("html, body").animate({ scrollTop: 0 }, 10, "linear");
                    return true;
                });
            });
            if (_.isString($.Radiko.area.id)) {
                $.Radiko.EventEmitter.trigger('radikoready');
            }
            if (window.area != undefined) {
                $('span.area').text(window.area);
            }
        });
    })(window, $, Backbone, _, moment);
};
