"use strict";
var radikoSl = function (_searchPage) {
    (function (window, $, Backbone, _, moment, undefined) {
        var contentsTemplate;
        if (_searchPage === Radiko.CONST.SEARCH_TYPE.TF) {
            contentsTemplate = '/apps/templates/search_timeshift/index.html';
        }
        else if (_searchPage === Radiko.CONST.SEARCH_TYPE.LV) {
            contentsTemplate = '/apps/templates/search_live/index.html';
        }
        else {
            contentsTemplate = '/apps/templates/search/history/index.html';
        }
        loadTemplate({
            '#contents': contentsTemplate,
            '#footer': '/apps/templates/common/footer.html'
        }, function () {
            (function (Radiko) {
                var Search = (function () {
                    function Search() {
                    }
                    Search.prototype.initialize = function () {
                        this.createModels();
                        this.createViews();
                        this.fetchAll([
                            {
                                model: this.searchedCollection,
                                options: {
                                    data: this.searchConfigModel.toJSON()
                                }
                            }
                        ]);
                        this.subscribeAll();
                    };
                    Search.prototype.createModels = function () {
                        this.searchConfigModel = new SearcheConfigModel(window.Radiko.URL.parseQueryString(location.search));
                        this.searchedCollection = new SearchedCollection();
                    };
                    Search.prototype.createViews = function () {
                        $.Radiko.views.push(new SearchFormView({
                            el: document.getElementById('search-form'),
                            model: this.searchConfigModel
                        }));
                        $.Radiko.views.push(new SearchedListView({
                            el: document.getElementById('search-result'),
                            collection: this.searchedCollection
                        }));
                    };
                    Search.prototype.fetchAll = function (obj) {
                        return $.when.apply($, _.map(obj, function (queue) {
                            return queue.model.fetch(queue.options || {});
                        }));
                    };
                    Search.prototype.subscribeAll = function () {
                        var _this = this;
                        $.Radiko.EventEmitter.off('request:search');
                        $.Radiko.EventEmitter.on('request:search', function () {
                            Path.routes.current = location.hash;
                            _this.searchConfigModel.set(window.Radiko.URL.parseQueryString(location.search));
                            return _this.searchedCollection.fetch({
                                data: _this.searchConfigModel.toJSON()
                            });
                        });
                    };
                    return Search;
                }());
                Radiko.Search = Search;
                var SearcheConfigModel = Backbone.Model.extend({
                    defaults: {
                        key: '',
                        filter: '',
                        start_day: '',
                        end_day: '',
                        area_id: '',
                        cul_area_id: '',
                        page_idx: '',
                        station_id: undefined
                    },
                    set: function (data) {
                        var validKeys = ['key', 'filter', 'start_day', 'end_day', 'area_id', 'region_id', 'cul_area_id', 'page_idx', 'action_id', 'station_id'];
                        return Backbone.Model.prototype.set.call(this, _.pick(data, validKeys));
                    }
                });
                var ProgramModel = Backbone.Model.extend({
                    defaults: {}
                });
                var SearchedCollection = Backbone.Collection.extend({
                    model: ProgramModel,
                    url: '/v3/api/program/search',
                    fetch: function (options) {
                        var _options = options;
                        if ($.Radiko.Suggest.action_id == 1 && $.Radiko.Suggest.suggestKeyWord != options.data.key) {
                            $.Radiko.Suggest.action_id = 0;
                        }
                        _.extend((_options.data || {}), {
                            uid: this.generateUid(),
                            row_limit: '12',
                            app_id: 'pc',
                            cur_area_id: _options.data.cul_area_id,
                            action_id: [0, 1, 2].indexOf($.Radiko.Suggest.action_id) == -1 ? 0 : $.Radiko.Suggest.action_id
                        });
                        if (!_.isUndefined($.Radiko.Suggest.action_rank) && $.Radiko.Suggest.action_id == 1) {
                            _.extend((_options.data || {}), {
                                action_rank: $.Radiko.Suggest.action_rank
                            });
                        }
                        if (!_.isUndefined(_options.data.station_id)) {
                            _.extend((_options.data || {}), {
                                station_id: _options.data.station_id
                            });
                        }
                        $.Radiko.Suggest.action_id = 0;
                        return Backbone.Collection.prototype.fetch.call(this, _options);
                    },
                    parse: function (resp) {
                        return resp;
                    }
                });
                _.extend(SearchedCollection.prototype, $.Radiko.Mixins.Utility);
                var SearchFormView = Backbone.View.extend({
                    initialize: function () {
                        this.currentDate = moment();
                        this.minDate = moment().add(-7, 'd');
                        this.maxDate = moment().add(6, 'd');
                        this.render();
                    },
                    render: function () {
                        this.$('[name="key"]').val(this.normalizeKeyword(this.model.get('key')));
                        this.setDateOption();
                        this.$('[name="region_id"]').html(this.buildRegionBox(this.model.get('region_id')));
                        var filter = this.model.get('filter');
                        if (filter.indexOf('past') != -1 || filter.indexOf('future') != -1)
                            this.$('option[value=' + filter + ']').attr('selected', true);
                        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 () {
                                    $('#search-form').find(".esb-displayer").append('<i class="icon icon--arrow-d"></i>');
                                }
                            });
                            $searchForm.find(".esb-displayer").append('<i class="icon icon--arrow-d"></i>');
                        }
                        $.Radiko.Suggest.currentKeyWord = $searchForm.find('input[name=key]').val();
                    },
                    buildRegionBox: function (regionId) {
                        var isAll = !!(regionId && regionId.indexOf('all') != -1);
                        var optionData = [
                            {
                                value: 'all',
                                text: '全国',
                                selected: isAll
                            },
                            {
                                value: '',
                                text: window.Radiko.Utility.areaId2Name($.cookie('default_area_id')),
                                selected: !isAll
                            }
                        ];
                        if ($.Radiko.login_status.premium) {
                            optionData.reverse();
                        }
                        return JST['common/options']({
                            data: optionData
                        });
                    },
                    setDateOption: function () {
                        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);
                        var counter;
                        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);
                        if (this.model.get('start_day') != '')
                            this.$('option[value=' + this.model.get('start_day') + ']').attr('selected', 'true');
                    },
                    events: {
                        'keyup input[name=key]': $.Radiko.Suggest.keyUpHandler,
                        'submit #search-form': 'submitHandler'
                    },
                    submitHandler: function (ev) {
                        ev.preventDefault();
                        var query = $('body').attr('class').indexOf('page-default') == -1 ? '/#!/search/timeshift?' : '/#!/search/live?';
                        var searchForm = $('#search-form');
                        var key = searchForm.find('[name="key"]').val();
                        if (key == '') {
                            alert('検索機能の利用には、検索キーワードの入力が必要です');
                            return false;
                        }
                        var filter = searchForm.find('[name="filter"]').val();
                        var date = searchForm.find('[name="date"]').val();
                        var regionId = searchForm.find('[name=region_id]').val();
                        var filterMap = {
                            future: 'live',
                            past: 'timefree'
                        };
                        dataLayer.push({
                            'event': 'FireTdEvent',
                            'eCategory': 'search_area',
                            'eAction': 'click',
                            'eLabel': 'search_button',
                            'eAreaId': regionId ? regionId : $.cookie('default_area_id'),
                            'eSearchWord': key,
                            'eStreamType': filter ? filterMap[filter] : 'all',
                            eSearchDate: date ? date : 'all'
                        });
                        query += 'key=' + encodeURIComponent(key);
                        query += '&filter=' + encodeURIComponent(filter);
                        query += '&start_day=' + encodeURIComponent(date);
                        query += '&end_day=' + encodeURIComponent(date);
                        query += '&region_id=' + encodeURIComponent(searchForm.find('[name="region_id"]').val());
                        query += '&area_id=' + $.cookie('default_area_id');
                        query += '&cul_area_id=' + $.cookie('default_area_id');
                        query += '&page_idx=0';
                        var searchResultBody = $('.search-result__body');
                        searchResultBody.html('<p class="search-result__count">検索結果<span class="num">-</span>件</p>'
                            + '<ul class="search-result__list img-list group"></ul>');
                        searchResultBody.removeClass('search-result__body--zero');
                        if (window.navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
                            var now = new Date();
                            query += '&t=' + now.getTime();
                            location.href = query;
                        }
                        else {
                            history.pushState('', '', query);
                            $.Radiko.EventEmitter.trigger('request:search');
                        }
                    },
                    normalizeKeyword: function (keyword) {
                        if (keyword === '%') {
                            return keyword;
                        }
                        return decodeURIComponent(keyword);
                    }
                });
                var SearchedListView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.collection, 'sync', this.onSync);
                        this.pageNationLimit = 5;
                    },
                    onSync: function (models) {
                        this.render(models);
                    },
                    render: function (models) {
                        var json = models.toJSON();
                        var data = json[0]['data'];
                        var meta = json[0]['meta'];
                        this.$('ul').empty();
                        this.append(data);
                        this.setPageNation(meta, data);
                        if ($('.search-result__list li').length == 0) {
                            var searchResultBody = $('#search-result');
                            searchResultBody.append('<p>検索条件に合う番組はありませんでした。<br>別の条件で再検索してください。</p>');
                            searchResultBody.find('.search-result__count').remove();
                            searchResultBody.find('.search-result__list').remove();
                            searchResultBody.addClass('search-result__body--zero');
                        }
                        else {
                            var keywords = void 0, length_1, i = void 0;
                            if (!_.isUndefined(meta['kakuchou']) && !_.isEmpty(meta['kakuchou'])) {
                                length_1 = meta['kakuchou'].length;
                                keywords = '「' + meta['kakuchou'][0] + '」';
                                for (i = 1; i < length_1; i++) {
                                    keywords += '「' + meta['kakuchou'][i] + '」';
                                }
                            }
                            else {
                                length_1 = meta['key'].length;
                                keywords = '「' + meta['key'][0] + '」';
                                for (i = 1; i < length_1; i++) {
                                    keywords += '「' + meta['key'][i] + '」';
                                }
                            }
                            $('.img-list__item').heightLine();
                            $('.search-result__count').text(keywords + 'の検索結果').append('<span class="num">' + meta['result_count'] + '</span>件');
                            this.divLazyLoad();
                        }
                        if (!_.isUndefined(meta['suisengo']) && meta['suisengo'] != '') {
                            this.setDidYouMean(meta);
                        }
                        else {
                            $('.search-did-you-mean').html('');
                        }
                        return this;
                    },
                    append: function (models) {
                        var _this = this;
                        var programs = _.map(models, function (model) {
                            return _this.getViewModel(model);
                        });
                        this.$('ul').empty().html(JST['common/program-card-list']({
                            programs: programs
                        }));
                        $('.img-list__item a').on('click', this.programClickHandler);
                    },
                    programClickHandler: 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;
                        }
                    },
                    divLazyLoad: function () {
                        var programs = $('.img-list__item');
                        programs.hide();
                        programs.addClass('hide-list__item');
                        var lazyLoad = setInterval(function () {
                            var hideItems = $('.hide-list__item');
                            var hideItemNum = hideItems.length;
                            if (hideItemNum == 0) {
                                clearInterval(lazyLoad);
                            }
                            else {
                                hideItems.first().fadeIn(500);
                                hideItems.first().removeClass('hide-list__item');
                            }
                        }, 100);
                    },
                    getViewModel: function (model) {
                        var description = model.description || '';
                        if (description)
                            description = description.replace(/(<([^>]+)>)/ig, "");
                        if (model.info != '')
                            model.info = model.info.replace(/(<([^>]+)>)/ig, "");
                        description += model.info;
                        var thumbnail;
                        if (model.img == null) {
                            thumbnail = model.status == 'past' ? window.Radiko.CONST.NO_IMAGE.TF : window.Radiko.CONST.NO_IMAGE.LIVE;
                        }
                        else {
                            thumbnail = model.img;
                        }
                        var stationId = model.station_id;
                        return {
                            station_id: stationId,
                            station_name: stationId,
                            link: "/#!/ts/" + stationId + "/" + moment(model.start_time).format('YYYYMMDDHHmmss'),
                            thumbnail: thumbnail,
                            date: this.getShortScheduleString(model['start_time']),
                            title: model.title,
                            performer: model.performer,
                            start: moment(model.ft, 'YYYYMMDDHHmmss'),
                            schedule: this.getScheduleString(model['start_time'], model['end_time']),
                            description: description.length > 100 ? description.slice(0, 100) + '…' : description,
                            status: model.status,
                            is_premium: !window.Radiko.User.canPlayStation(stationId),
                            show_label: true
                        };
                    },
                    getScheduleString: function (ft, to) {
                        var ftMoment = moment(ft, 'YYYYMMDDHHmmss');
                        var toMoment = moment(to, 'YYYYMMDDHHmmss');
                        var ftStr = ftMoment.format('M月D日（ddd） HH:mm');
                        var toStr = toMoment.format('HH:mm');
                        var ftHour = ftMoment.format('H');
                        var toHour = toMoment.format('H');
                        if (ftHour >= 0 && ftHour < 5) {
                            ftMoment.subtract(1, 'days');
                            ftStr = ftMoment.format('M月D日（ddd） ') + (24 + parseInt(ftMoment.format('HH'))) + ':' + ftMoment.format('mm');
                        }
                        if (toHour >= 0 && toHour <= 5 && (ftHour != 5)) {
                            toStr = (24 + parseInt(toMoment.format('HH'))) + ':' + toMoment.format('mm');
                        }
                        return ftStr + '-' + toStr;
                    },
                    getShortScheduleString: function (ft) {
                        var ftMoment = moment(ft, 'YYYYMMDDHHmmss');
                        if (ftMoment.format('H') < 5) {
                            ftMoment.subtract(1, 'days');
                        }
                        return ftMoment.format('M月D日');
                    },
                    setPageNation: function (meta, data) {
                        var query = window.Radiko.URL.parseQueryString();
                        meta.page_num = Math.ceil(meta.result_count / meta.row_limit);
                        var $pageNation = $('#page-nation');
                        if (meta.page_num <= 1) {
                            $pageNation.html('');
                            return;
                        }
                        meta.page_nation_num = [];
                        meta.search_result = data.length;
                        var queryPageIdx = query.page_idx;
                        meta.page_idx = !queryPageIdx && +meta.page_idx === 1 ? 0 : +meta.page_idx;
                        var pageNationLimit = !(meta.page_num > this.pageNationLimit) ? meta.page_num : this.pageNationLimit;
                        var startPosition = this.getStartPosition(meta.page_idx, meta.page_num, pageNationLimit);
                        for (var i = 0; i < pageNationLimit; i++) {
                            meta.page_nation_num[i] = ++startPosition;
                        }
                        meta['search_page'] = _searchPage;
                        var queryParams = {
                            key: query.key,
                            filter: query.filter,
                            start_day: query.start_day,
                            end_day: query.end_day,
                            area_id: $.cookie('default_area_id'),
                            region_id: query.region_id,
                            cul_area_id: $.cookie('default_area_id')
                        };
                        if (query.station_id) {
                            queryParams = _.extend(queryParams, {
                                station_id: query.station_id
                            });
                        }
                        meta.query = window.Radiko.URL.buildSearchQuery(queryParams);
                        $pageNation.html(JST['search/page-nation'](meta));
                    },
                    setDidYouMean: function (meta) {
                        var query = window.Radiko.URL.parseQueryString(meta['searched_url']);
                        var nextQuery = 'key=' + encodeURIComponent(meta['suisengo']);
                        nextQuery += '&filter=' + encodeURIComponent(query['filter']);
                        nextQuery += '&start_day=' + encodeURIComponent(query['start_day']);
                        nextQuery += '&end_day=' + encodeURIComponent(query['end_day']);
                        nextQuery += '&area_id=' + encodeURIComponent($.cookie('default_area_id'));
                        nextQuery += '&region_id=' + encodeURIComponent(query['region_id']);
                        nextQuery += '&cul_area_id=' + encodeURIComponent($.cookie('default_area_id'));
                        meta['query'] = nextQuery;
                        $('.search-did-you-mean').html('<div class="did-you-mean">もしかして: <a class="result" href="' + '/#!/search/' + _searchPage + '?' + nextQuery + '">' + meta['suisengo'] + '</a></div>');
                        $('.did-you-mean .result').on('click', function (e) {
                            e.preventDefault();
                            $.Radiko.Suggest.action_id = 2;
                            location.href = $(this).attr('href');
                        });
                    },
                    getStartPosition: function (currentPage, totalPageNum, pageNationLimit) {
                        if (totalPageNum <= pageNationLimit) {
                            return 0;
                        }
                        var startPosition = currentPage - Math.floor(pageNationLimit / 2);
                        if (startPosition <= 0) {
                            return 0;
                        }
                        if ((startPosition + pageNationLimit) <= totalPageNum) {
                            return startPosition;
                        }
                        var delta = (totalPageNum - currentPage);
                        return currentPage - (pageNationLimit - delta);
                    }
                });
                _.extend(SearchedListView.prototype, $.Radiko.Mixins.Utility);
            })($.Radiko || ($.Radiko = {}));
            if ($('body').hasClass('page-timeshift')) {
                $('#header').html(JST['common/header']({ logo: '/apps/images/img_logo_red_01.png' }));
            }
            else {
                $('#header').html(JST['common/header']({ logo: '/apps/images/img_logo_blue_01.png' }));
            }
            var search = new $.Radiko.Search();
            $.Radiko.EventEmitter.once('radikoSearchLive', function () {
                search.initialize();
                makeHeader();
                $('input[type="text"]').placeholder();
            });
            if (_.isString($.Radiko.area.id)) {
                $.Radiko.EventEmitter.trigger('radikoSearchLive');
            }
            if (window.area != undefined) {
                $('span.area').text(window.area);
            }
        });
    })(window, jQuery, Backbone, _, moment, undefined);
};
