"use strict";
var areaFree = function () {
    (function (window, $, Backbone, _, moment, undefined) {
        loadTemplate({
            '#contents': '/apps/templates/areafree/index.html',
            '#footer': '/apps/templates/common/footer.html'
        }, function () {
            (function (Radiko) {
                var areaFree = (function () {
                    function areaFree() {
                        this.areaFreeCollection = null;
                        this.nowOnAirCollection = null;
                        this.stationListCollection = null;
                    }
                    areaFree.prototype.initialize = function () {
                        this.createModels();
                        this.createViews();
                        this.fetchAll([
                            {
                                model: this.areaFreeCollection
                            }
                        ]);
                        this.subscribeAll();
                    };
                    areaFree.prototype.createModels = function () {
                        this.areaFreeCollection = new AreaFreeCollection();
                        this.stationListCollection = new StationListCollection(this.areaFreeCollection);
                        this.nowOnAirCollection = new NowOnAirCollection({
                            collection: this.stationListCollection
                        });
                    };
                    areaFree.prototype.createViews = function () {
                        $.Radiko.views.push(new AreaFreeView({
                            el: document.getElementById('now_on_air'),
                            collection: this.areaFreeCollection
                        }));
                        $.Radiko.views.push(new NowOnAirListView({
                            el: document.getElementById('now_on_air'),
                            collection: this.nowOnAirCollection
                        }));
                        $.Radiko.views.push(new StationsView({
                            collection: this.stationListCollection
                        }));
                    };
                    areaFree.prototype.fetchAll = function (models) {
                        return $.when.apply($, _.map(models, function (queue) {
                            return queue.model.fetch(queue.options || {});
                        }));
                    };
                    areaFree.prototype.subscribeAll = function () {
                        var _this = this;
                        $.Radiko.EventEmitter.off('change:area');
                        $.Radiko.EventEmitter.on('change:area', function (area_id) {
                            _this.stationListCollection.fetch({ area_id: area_id });
                        });
                    };
                    return areaFree;
                }());
                Radiko.areaFree = areaFree;
                var AreaFreeModel = Backbone.Model.extend({
                    'default': {
                        region_name: '',
                        station: []
                    }
                });
                var AreaFreeCollection = Backbone.Collection.extend({
                    model: AreaFreeModel,
                    url: '/v3/station/region/full.xml',
                    parse: function (data) {
                        $.each($.Radiko.areaListParRegion, function (regionName, areas) {
                            $.each(areas, function (index, area) {
                                if (area.id === getAreaId()) {
                                    $.cookie('user_region', regionName);
                                }
                            });
                        });
                        return _.map($('stations', data), function (stations) {
                            var $stations = $(stations);
                            return {
                                id: $stations.attr('region_id'),
                                name: $stations.attr('region_name'),
                                stations: _.map($stations.find('station'), function (station) {
                                    var $station = $(station);
                                    return {
                                        stationId: $station.find('id').text(),
                                        name: $station.find('name').text(),
                                        areafree: $station.find('areafree').text(),
                                        timefree: $station.find('timefree').text(),
                                        logo: $station.find('logo').first().text(),
                                        areaId: $station.find('area_id').text()
                                    };
                                })
                            };
                        }, this);
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = "xml";
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    },
                    initialize: function () {
                        this.areaId = getAreaId() || $.cookie('default_area_id');
                        this.listenTo(this.collection, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        this.render(models);
                    }
                });
                var AreaFreeView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.collection, "sync", this.onSync);
                    },
                    onSync: function (models) {
                        this.render(models);
                    },
                    render: function (models) {
                        this.renderRegionTab(models.toJSON());
                        this.renderAreaList($.cookie('user_region'));
                        return this;
                    },
                    tabClickHandler: function (e) {
                        e.preventDefault();
                        $('.tab-list .item__selected').removeClass('item__selected');
                        $(e.currentTarget).addClass('item__selected');
                        this.renderAreaList($(e.currentTarget).attr('href'));
                    },
                    listClickHandler: function (e) {
                        e.preventDefault();
                        $('.link-list .item__selected').removeClass('item__selected');
                        $(e.currentTarget).addClass('item__selected');
                        var target_area_id = $(e.currentTarget).attr('href');
                        if (!$.Radiko.login_status.areafree) {
                            $.cookie('areafree_id', target_area_id);
                        }
                        $.Radiko.EventEmitter.trigger('change:area', target_area_id);
                    },
                    renderRegionTab: function (data) {
                        var zenkokuIndex = _.findIndex(data, function (region) {
                            return region["id"] === "zenkoku";
                        });
                        if (zenkokuIndex !== -1) {
                            data.splice(zenkokuIndex, 1);
                        }
                        $('.tab-list').html(JST['areafree/region-list']({
                            regions: data,
                            user_region: $.cookie('user_region')
                        }));
                        $('.tab-list a').on('click', this.tabClickHandler.bind(this));
                    },
                    renderAreaList: function (regionId) {
                        var stations = _.map($.Radiko.areaListParRegion[regionId], function (station) {
                            return _.extend(station, {
                                is_selected_area: station.id === getAreaId()
                            });
                        });
                        var $linkList = $('.link-list');
                        var regionName = this.collection.findWhere({
                            id: regionId
                        }).get('name');
                        $linkList.html(JST['areafree/area-list']({
                            stations: stations,
                            tracking_region_name: regionName
                        }));
                        $linkList.find('a').on('click', this.listClickHandler);
                    }
                });
                var ProgramModel = Backbone.Model.extend({
                    idAttribute: 'station_id',
                    defaults: {
                        id: '',
                        name: '',
                        progTitle: '',
                        progPfm: '',
                        progSchedule: '',
                        progImage: ''
                    }
                });
                var NowOnAirCollection = Backbone.Collection.extend({
                    model: ProgramModel,
                    initialize: function (options) {
                        this.listenTo(options.collection, 'sync', this.onSync);
                    },
                    onSync: function (stationCollection) {
                        this.area_id = stationCollection.area_id;
                        this.collection = stationCollection;
                        this.fetch();
                    },
                    url: function () {
                        return "/v3/program/now/" + this.area_id + ".xml";
                    },
                    fetch: function (options) {
                        if (options && options.area_id) {
                            this.area_id = options.area_id;
                        }
                        return Backbone.Collection.prototype.fetch.call(this, _.extend({
                            dataType: 'xml',
                            cache: true,
                            expires: 60 * 3
                        }, options));
                    },
                    parse: function (resp) {
                        var _this = this;
                        return _.filter($('station', resp), function (station) {
                            var $station = $(station);
                            var stationId = $station.attr('id');
                            var info = _this.collection.get(stationId);
                            return info && +info.get('areafree') !== 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';
                            }
                            var stationId = $station.attr('id');
                            return {
                                station_id: stationId,
                                areaId: _this.area_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,
                                start: moment($prog.attr('ft'), 'YYYYMMDDHHmmss'),
                                is_premium: !window.Radiko.User.canPlayStation(stationId),
                                link: "/#!/live/" + stationId
                            };
                        });
                    }
                });
                _.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) {
                        this.$el.empty().html(JST['common/program-card-list']({
                            programs: models.toJSON()
                        }));
                        $(".img-list>.img-list__item").heightLine();
                        if (!$.Radiko.login_status.areafree) {
                            $("li[class='img-list__item'] a").on("click", this.noaClickHandler);
                        }
                        return this;
                    },
                    noaClickHandler: function (e) {
                        var station_id = $(e.currentTarget).data("station_id").toString();
                        if ($.Radiko.isUserAreaStation(station_id)) {
                            return true;
                        }
                        $.colorbox({
                            width: "60%",
                            inline: true,
                            href: "#colorbox--premium",
                            speed: 0,
                            open: true,
                            opacity: 0.5
                        });
                        return false;
                    }
                });
                var StationListModel = Backbone.Model.extend({
                    defaults: {}
                });
                var StationListCollection = Backbone.Collection.extend({
                    model: StationListModel,
                    initialize: function (models) {
                        this.listenTo(models, 'sync', this.onSync);
                    },
                    onSync: function () {
                        this.fetch({ area_id: getAreaId() });
                    },
                    parse: function (data) {
                        var _this = this;
                        return $(data).find('station')
                            .filter(function (i, station) { return +$(station).find('areafree').text() !== 0; })
                            .map(function (i, station) {
                            var stationId = $(station).find('id').text();
                            var stationName = $(station).find('name').text();
                            return {
                                id: stationId,
                                areaId: _this.area_id,
                                name: stationName
                            };
                        })
                            .toArray();
                    },
                    url: function () {
                        return "/v3/station/list/" + this.area_id + ".xml";
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = "xml";
                        this.area_id = options.area_id;
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    }
                });
                var StationsView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.collection, "sync", this.onSync);
                    },
                    onSync: function (models) {
                        if ($.Radiko.login_status.areafree) {
                            $.cookie('areafree_id', models.area_id, { path: '/' });
                        }
                        this.render(models);
                    },
                    render: function (models) {
                        $('#station-list').html(JST['common/station-list']({ models: models.toJSON() }));
                        window.Radiko.UI.fixedHeaderHeight();
                        return this;
                    }
                });
            })($.Radiko || ($.Radiko = {}));
            if ($.Radiko.login_status.premium) {
                $('.premium-area').hide();
            }
            $('#header').html(JST['common/header']({ logo: '/apps/images/img_logo_blue_01.png' }));
            var areaFree = new $.Radiko.areaFree();
            $.Radiko.EventEmitter.once('radikoareafree', function () {
                makeHeader();
                areaFree.initialize();
                setMetaText();
                $('input[type="text"]').placeholder();
            });
            if (_.isString($.Radiko.area.id)) {
                $.Radiko.EventEmitter.trigger('radikoareafree');
            }
            if (window.area != undefined) {
                $('span.area').text(window.area);
            }
        });
    })(window, $, Backbone, _, moment);
};
