'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
;
function reqStation(ymd, stationId) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            return [2, $.ajax({
                    type: 'GET',
                    url: "./v4/program/station/date/" + ymd + "/" + stationId + ".json",
                    dataType: 'json'
                })];
        });
    });
}
function findProgram(programList, ft) {
    for (var idx = 0; idx < programList.length; idx++) {
        if (programList[idx].ft === ft) {
            return programList[idx];
        }
    }
    return undefined;
}
function getActorIdList(program) {
    if (program === undefined)
        return [];
    return program.person.reduce(function (acc, cur) {
        var mat = cur.id.match(/[^/]+$/);
        if (mat !== null) {
            acc.push(mat[0]);
        }
        return acc;
    }, []);
}
function getEventId(program) {
    if (program === undefined)
        return "";
    var matchResult = program.event_id.match(/events\/(.+)$/);
    if (matchResult === null)
        return "";
    return matchResult.length ? matchResult[1] : "";
}
function getActorImageByGenre(image) {
    for (var idx = 0; image.length > idx; idx++) {
        if (image[idx].genre === 's') {
            return image[idx].url;
        }
        else if (image[idx].genre === 'm') {
            return image[idx].url;
        }
        else {
            return image[idx].url;
        }
    }
}
var liveRenderActorNgStationList = [
    {
        id: 'FMT'
    }
];
function generateDisplayActorsList(actorList, eventId) {
    var displayItems = new Array();
    actorList.forEach(function (v) {
        var item = {
            id: v.key,
            name: v.name,
            englishName: v.nameEnglish,
            imageUrl: '',
            eventId: eventId,
            hasImageUrl: false
        };
        var image = getActorImageByGenre(v.imagesList);
        if (image === undefined) {
            item.imageUrl = './images/person-silhouette.png';
        }
        else {
            item.imageUrl = image;
            item.hasImageUrl = true;
        }
        displayItems.push(item);
    });
    return displayItems;
}
var actorRenderer = {
    init: function (items) {
        if (items.length > 0) {
            this.renderActorsSection();
            this.renderItems(items);
        }
        else {
            showLiveUtil.initActorSection();
        }
    },
    renderActorsSection: function () {
        var actorsSection = document.createElement('div');
        actorsSection.id = 'actors_section';
        var actorsVP = document.createElement('div');
        actorsVP.id = 'actor_viewport';
        var headerTitle = document.createElement('h2');
        headerTitle.innerText = '出演者の追加情報';
        var additionalMessage = document.createElement('h3');
        additionalMessage.innerText = 'by ARTIST COMMONS';
        additionalMessage.id = 'actors_additional_message';
        actorsSection.appendChild(headerTitle);
        actorsSection.appendChild(actorsVP);
        actorsSection.appendChild(additionalMessage);
        var displaySection = showLiveUtil.actor.getActorDisplay();
        displaySection.appendChild(actorsSection);
    },
    renderItems: function (items) {
        var _this_1 = this;
        var actorViewport = showLiveUtil.actor.getViewPort();
        items.forEach(function (item) {
            var actorItem = _this_1.renderActorItem(item);
            actorViewport.appendChild(actorItem);
        });
    },
    renderActorItem: function (item) {
        var img = this.renderActorImage(item.imageUrl, item.hasImageUrl);
        var name = this.renderActorNameContainer(item.name, item.englishName);
        var actorItem = document.createElement('div');
        actorItem.className = 'actor_item';
        actorItem.appendChild(img);
        actorItem.appendChild(name);
        var actorItemLink = this.renderLink(item.id, item.eventId);
        actorItemLink.appendChild(actorItem);
        return actorItemLink;
    },
    renderLink: function (personId, eventId) {
        var actorLink = document.createElement('a');
        actorLink.className = 'actor-item-container';
        actorLink.href = "./persons/" + personId;
        actorLink.setAttribute("data-tdhittype", "event");
        actorLink.setAttribute("data-ecategory", "live_broadcast");
        actorLink.setAttribute("data-eaction", "click");
        actorLink.setAttribute("data-elabel", "person");
        actorLink.setAttribute("data-eperson-id", personId);
        actorLink.setAttribute("data-eprogram-event-id", eventId);
        actorLink.setAttribute("target", "_blank");
        return actorLink;
    },
    renderActorImage: function (imageUrl, hasImageUrl) {
        var image = document.createElement('img');
        image.src = imageUrl;
        var actorImage = document.createElement('div');
        actorImage.className = 'actor_image';
        actorImage.appendChild(image);
        if (!hasImageUrl) {
            image.id = 'actor_no_image';
        }
        return actorImage;
    },
    renderActorNameContainer: function (name, englishName) {
        var acotorName = document.createElement('dt');
        acotorName.className = 'actor_name';
        acotorName.innerText = name;
        var acotorNameEng = document.createElement('dd');
        acotorNameEng.className = 'actor_name_eng';
        acotorNameEng.innerText = englishName;
        var actorNameContainer = document.createElement('dl');
        actorNameContainer.className = 'actor_name_container';
        actorNameContainer.appendChild(acotorName);
        actorNameContainer.appendChild(acotorNameEng);
        return actorNameContainer;
    }
};
var showLiveUtil = {
    actor: {
        getActorDisplay: function () {
            return document.getElementById('actor_display');
        },
        getActorSection: function () {
            return document.getElementById('actors_section');
        },
        getViewPort: function () {
            return document.getElementById('actor_viewport');
        }
    },
    initActorSection: function () {
        var actorsEl = showLiveUtil.actor.getActorSection();
        if (actorsEl)
            actorsEl.remove();
    },
    renderActorListAsync: function (ftYmd, stationId, models) {
        showLiveUtil.initActorSection();
        var isLiveRenderActorNgStation = function () {
            var isRender = true;
            liveRenderActorNgStationList.map(function (liveRenderActorNgStation) {
                if (liveRenderActorNgStation.id === stationId) {
                    return isRender = false;
                }
                return;
            });
            return isRender;
        };
        if (!isLiveRenderActorNgStation()) {
            return;
        }
        ;
        reqStation(ftYmd, stationId).then(function (stations) {
            var program = findProgram(stations.stations[0].programs.program, models.models[0].attributes.ft);
            if (program !== undefined && program.key_station_id === 'FMT') {
                return;
            }
            var actorIdItems = getActorIdList(program);
            var eventId = getEventId(program);
            if (actorIdItems.length > 0) {
                window.RadikoGrpc.getActors(actorIdItems).then(function (actorList) {
                    var displayItems = generateDisplayActorsList(actorList, eventId);
                    actorRenderer.init(displayItems);
                });
            }
        });
    }
};
var showLive = function (_stationId) {
    (function (window, $, Backbone, _, moment, undefined) {
        loadTemplate({
            '#contents': '/apps/templates/prg/index.html',
            '#footer': '/apps/templates/common/footer.html'
        }, function () {
            var intervals = [];
            (function (Radiko) {
                var getDate = function () {
                    var m = moment();
                    if (m.format('YYYYMMDDHHmmss') >= m.format('YYYYMMDD050000')) {
                        return m;
                    }
                    else {
                        return moment(m.subtract('day', 1).format('YYYY-MM-DD'));
                    }
                };
                var isAdClose = false;
                Radiko.Live = (function () {
                    var Live = function () {
                        this.areaFreeCollection = null;
                        this.stationCollection = null;
                        this.nowProgramsCollection = null;
                        this.musicsCollection = null;
                        this.ticketCollection = null;
                        this.merchCollection = null;
                        this.StationWeeklyCollection = null;
                        this.othersCollection = null;
                        this.syncAdCollection = null;
                        this.adHifstoryCollection = null;
                        this.stationTimelinesCollection = null;
                    };
                    _.extend(Live.prototype, Backbone.Events);
                    Live.prototype.initialize = function () {
                        this.createModels();
                        this.createViews();
                        this.fetchAll({
                            model: this.areafreeCollection
                        }, {
                            model: this.StationWeeklyCollection
                        }, {
                            model: this.othersCollection
                        }, {
                            model: this.syncAdCollection
                        }, {
                            model: this.adHistoryCollection
                        });
                        this.subscribeAll();
                    };
                    Live.prototype.createModels = function () {
                        this.areafreeCollection = new AreaFreeCollection();
                        this.stationCollection = new StationsCollection(this.areafreeCollection);
                        this.nowProgramsCollection = new NowProgramsCollection({
                            areafree: this.areafreeCollection,
                            station: this.stationCollection
                        });
                        this.musicsCollection = new radikoNOA.Collection(this.nowProgramsCollection, {
                            station_id: _stationId
                        });
                        this.ticketCollection = new RadikoTicket.Collection(this.musicsCollection, {
                            station_id: _stationId,
                            is_live: true,
                            programCollection: this.nowProgramsCollection
                        });
                        this.merchCollection = new RadikoMerch.Collection(this.musicsCollection, {
                            station_id: _stationId
                        });
                        this.stationTimelinesCollection = new StationTimelinesCollection(this.nowProgramsCollection);
                        this.StationWeeklyCollection = new StationWeeklyCollection();
                        this.othersCollection = new OthersCollection();
                        this.syncAdCollection = new SyncAdCollection();
                        this.adHistoryCollection = new AdHistoryCollection();
                    };
                    Live.prototype.createViews = function () {
                        $.Radiko.views.push(new StationsView({
                            collection: this.stationCollection
                        }));
                        $.Radiko.views.push(new NowProgramsListView({
                            el: document.getElementById('now-programs-list'),
                            collection: {
                                stations: this.stationCollection,
                                program: this.nowProgramsCollection,
                                areafree: this.areafreeCollection
                            }
                        }));
                        $.Radiko.views.push(new MusicsView({
                            el: document.getElementById('play-musics'),
                            collection: {
                                ticket: this.ticketCollection,
                                merch: this.merchCollection
                            }
                        }));
                        $.Radiko.views.push(new StationTimelinesView({
                            el: document.getElementById('timeline-station'),
                            collection: this.stationTimelinesCollection
                        }));
                        $.Radiko.views.push(new WeeklyListView({
                            el: document.getElementById('program-table'),
                            collection: this.StationWeeklyCollection
                        }));
                        $.Radiko.views.push(new OthersView({
                            el: document.getElementById('others-program'),
                            collection: this.othersCollection
                        }));
                        $.Radiko.views.push(new AdHistoryView({
                            el: document.getElementById('ad-history'),
                            collection: this.adHistoryCollection
                        }));
                    };
                    Live.prototype.fetchAll = function () {
                        return $.when.apply($, _.map(_.toArray(arguments), function (queue) {
                            return queue.model.fetch(queue.options || {});
                        }));
                    };
                    Live.prototype.subscribeAll = function () {
                        var _this = this;
                        var nowOnAir = setInterval(function () {
                            _this.musicsCollection.fetch();
                        }, 17 * 1000);
                        intervals.push(nowOnAir);
                        var timer = setInterval(function () {
                            var to = $('.live-detail__body').attr('to');
                            if (to < moment().format('YYYYMMDDHHmmss')) {
                                _this.nowProgramsCollection.fetch();
                            }
                        }, 5 * 1000);
                        intervals.push(timer);
                    };
                    return Live;
                })();
                var AreaFreeModel = Backbone.Model.extend({
                    "default": {}
                });
                var AreaFreeCollection = Backbone.Collection.extend({
                    model: AreaFreeModel,
                    url: '/v3/station/region/full.xml',
                    parse: function (data) {
                        return _.map($('station', data), function (station) {
                            var $station = $(station);
                            return {
                                id: $station.find('id').text(),
                                areaId: $station.find('area_id').text(),
                                logo: $station.find('logo').first().text(),
                                tf_max_delay: $station.find('tf_max_delay').text()
                            };
                        }, this);
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = 'xml';
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    },
                    initialize: function () {
                        this.listenTo(this.collection, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        this.render(models);
                    }
                });
                var StationModel = Backbone.Model.extend({
                    defaults: {
                        tf_max_delay: 60
                    }
                });
                var StationsCollection = Backbone.Collection.extend({
                    model: StationModel,
                    initialize: function (models) {
                        this.isStationList = _.contains($.Radiko.before_station_list, _stationId);
                        this.listenTo(models, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        if (models.where({ id: _stationId }).length === 0) {
                            notFound();
                            $('body').attr('class', 'page-default');
                            return;
                        }
                        var data = models.where({ id: _stationId })[0].toJSON();
                        this.areaId = data.areaId;
                        $('.heading-area__title img').attr('src', data.logo);
                        $('.heading-area__title a').attr('href', '/#!/timetable/' + data.id + '/live');
                        if ($.Radiko.login_status.areafree && !this.isStationList) {
                            $.cookie('areafree_id', this.areaId, { path: '/' });
                        }
                        else if (this.isStationList) {
                            this.areaId = getAreaId();
                        }
                        else {
                            this.areaId = $.cookie('default_area_id');
                        }
                        this.url = '/v3/station/list/' + this.areaId + '.xml';
                        this.fetch();
                    },
                    parse: function (data) {
                        var areaId = this.areaId;
                        var $stations = $(data).find('station');
                        var stations = _.map($stations, function (station) {
                            var obj = {
                                id: $(station).find('id').text(),
                                name: $(station).find('name').text(),
                                areafree: +$(station).find('areafree').text()
                            };
                            var $delay = $(station).find('tf_max_delay');
                            if ($delay.length) {
                                $.extend(obj, {
                                    tf_max_delay: +$delay.text()
                                });
                            }
                            return obj;
                        });
                        isDefaultArea = !!_.find(stations, function (station) {
                            return station.id === _stationId;
                        });
                        return _.filter(stations, function (station) {
                            return $.cookie('default_area_id') === areaId
                                || station.areafree !== 0;
                        });
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = 'xml';
                        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) {
                        this.render(models);
                    },
                    render: function (models) {
                        $('#station-list').html(JST['common/station-list']({ models: models.toJSON() }));
                        window.Radiko.UI.fixedHeaderHeight();
                        return this;
                    }
                });
                var StreamModel = Backbone.Model.extend({
                    defaults: {
                        streamUrl: 'rtmpe'
                    }
                });
                var NowProgramModel = Backbone.Model.extend({
                    defaults: {
                        stationId: 'RGK',
                        stationName: 'RAGIKO',
                        progs: []
                    }
                });
                var NowProgramsCollection = Backbone.Collection.extend({
                    model: NowProgramModel,
                    host: 'https://' + location.host,
                    initialize: function (models) {
                        this.areafree = models.areafree;
                        this.listenTo(models.station, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        var data = this.areafree.where({ id: _stationId })[0].toJSON();
                        var areaId = data.areaId;
                        this.logo = '';
                        this.url = '/v3/program/now/' + areaId + '.xml';
                        this.fetch();
                    },
                    parse: function (resp) {
                        var self = this;
                        var $station = $(resp).find('#' + _stationId);
                        return _.map($station, function (station) {
                            var $station = $(station);
                            var $prog = $station.find('prog');
                            $prog = $prog.filter(function (index, element) {
                                return $(element).attr('to') > moment().format('YYYYMMDDHHmmss');
                            });
                            $prog = $prog.length === 0 ? $station.find('prog').last() : $prog.first();
                            var $stationId = $station.attr('id');
                            var iCalURL = this.getIcalUrl($stationId, $prog);
                            var googleCalUrl = this.getGoogleCalUrl($stationId, $prog);
                            var stationName = $station.find(' > name').text();
                            var shareText = this.getShareText(stationName, $prog);
                            var shareUrl = this.host + '/share/?sid=' + $stationId + '&t=';
                            var twitterUrl = 'http://twitter.com/share?text='
                                + encodeURIComponent(shareText) + '&hashtags=radiko&url=' + encodeURIComponent(shareUrl);
                            var facebookUrl = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(shareUrl);
                            var clipUrl = shareText + ' ' + shareUrl;
                            var txt = this.omitString($prog.find('pfm').first().text(), 11);
                            window.stationTimelineKey = 'from:radiko_jp';
                            var twitter = null;
                            var metas = $prog.find('metas').first().find('meta');
                            for (var i = 0; i < metas.length; i++) {
                                var value = metas[i].getAttribute('value');
                                if (value.match(/^from:/)) {
                                    twitter = value;
                                    window.stationTimelineKey = twitter;
                                }
                            }
                            var img = $prog.find('img').text();
                            if (img === '') {
                                img = '/images/radio-api-noimage_live.png';
                            }
                            var ftmt = moment($prog.attr('ft'), 'YYYYMMDDHHmmss');
                            var tomt = moment($prog.attr('to'), 'YYYYMMDDHHmmss');
                            return {
                                stationId: $stationId,
                                stationName: $station.find('name').first().text(),
                                progTitle: $prog.find('title').first().text(),
                                progPfm: txt,
                                progPfm2: $prog.find('pfm').first().text(),
                                ft: $prog.attr('ft'),
                                to: $prog.attr('to'),
                                progFt: $prog.attr('ft'),
                                progTo: $prog.attr('to'),
                                progSchedule: self.progScheduleString(ftmt, tomt),
                                progImage: img,
                                progUrl: $prog.find('url').first().text(),
                                progDesc: $prog.find('desc').first().text(),
                                progInfo: $prog.find('info').first().text(),
                                date: $prog.find('date').text(),
                                iCalUrl: iCalURL,
                                googleCalUrl: googleCalUrl,
                                twitterUrl: twitterUrl,
                                clipUrl: clipUrl,
                                facebookUrl: facebookUrl,
                                twitter: twitter,
                                metaTitle: this.getMetaTitle($station.find('name'), $prog),
                                shareUrl: shareUrl + $prog.attr('ft'),
                                nowPlaying: this.getPlayingStatus($stationId, $prog.attr('ft')),
                                progs: _.map($station.find('prog'), function (prog) {
                                    var $prog = $(prog);
                                    var size = 8;
                                    var txt = $prog.find('pfm').first().text();
                                    var suffix = '…';
                                    var b = 0;
                                    for (var i = 0; i < txt.length; i++) {
                                        b += txt.charCodeAt(i) <= 255 ? 0.5 : 1;
                                        if (b > size) {
                                            txt = txt.substr(0, i) + suffix;
                                            break;
                                        }
                                    }
                                    var img = $prog.find('img').text();
                                    if (img == '') {
                                        img = '/images/radio-api-noimage_live.png';
                                    }
                                    var ftmt = moment($prog.attr('ft'), 'YYYYMMDDHHmmss');
                                    var tomt = moment($prog.attr('to'), 'YYYYMMDDHHmmss');
                                    return {
                                        progTitle: $prog.find('title').first().text(),
                                        progPfm: txt,
                                        progSchedule: self.progScheduleString(ftmt, tomt),
                                        progImage: img,
                                        progUrl: $prog.find('url').first().text(),
                                        progDesc: $prog.find('desc').first().text(),
                                        ft: $prog.attr('ft'),
                                        to: $prog.attr('to'),
                                        date: $prog.find('date').text()
                                    };
                                })
                            };
                        }, this);
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = 'xml';
                        options.cache = false;
                        this.listenTo(this.area, 'sync', Backbone.Collection.prototype.fetch.call(this, options));
                    },
                    dateToFormatedString: function (dateString, outputFormat) {
                        return moment(dateString, ['YYYY-MM-DD HH:mm:ss', 'YYYYMMDDHHmmss']).format(outputFormat);
                    },
                    progScheduleString: function (ftmt, tomt) {
                        var radioHours = translateRadikoTimeHours(ftmt, tomt);
                        if (radioHours.ft_hour >= 24) {
                            ftmt.subtract(1, 'days');
                        }
                        var ret = ftmt.format('M月D日（ddd） ');
                        ret += sprintf('%02d:%02d-%02d:%02d', radioHours.ft_hour, ftmt.minute(), radioHours.to_hour, tomt.minute());
                        return ret;
                    },
                    getIcalUrl: function (_stationId, program) {
                        return '/v2/api/ical'
                            + '?station_id=' + _stationId
                            + '&ft=' + program.attr('ft')
                            + '&to=' + program.attr('to')
                            + '&title=' + encodeURIComponent(program.find('title').first().text())
                            + '&url=' + encodeURIComponent(this.host + '/#!/ts/' + _stationId + '/' + program.attr('ft'));
                    },
                    getGoogleCalUrl: function (_stationId, program) {
                        return 'http://www.google.com/calendar/event'
                            + '?action=TEMPLATE'
                            + '&text=' + encodeURIComponent(program.find('title').first().text())
                            + '&dates=' + program.attr('ft').substring(0, 8) + 'T' + program.attr('ft').substring(8, 14)
                            + '/' + program.attr('to').substring(0, 8) + 'T' + program.attr('to').substring(8, 14)
                            + '&details=' + encodeURIComponent(this.host + '/#!/ts/' + _stationId + '/' + program.attr('ft'))
                            + '&location='
                            + '&trp=false'
                            + '&sprop='
                            + '&sprop=name:';
                    },
                    getShareText: function (stationName, program) {
                        var ftmt = moment(program.attr('ft'), 'YYYYMMDDHHmmss');
                        var tomt = moment(program.attr('to'), 'YYYYMMDDHHmmss');
                        var radioHours = translateRadikoTimeHours(ftmt, tomt);
                        if (radioHours.ft_hour >= 24) {
                            ftmt.subtract(1, 'days');
                        }
                        return program.find('title').first().text()
                            + ' | ' + stationName
                            + sprintf(' | %04d/%02d/%02d/%s ', ftmt.year(), ftmt.month() + 1, ftmt.date(), ftmt.format('ddd'))
                            + sprintf(' %02d:%02d-%02d:%02d', radioHours.ft_hour, ftmt.minute(), radioHours.to_hour, tomt.minute());
                    },
                    getMetaTitle: function (_stationName, program) {
                        var ftmt = moment(program.attr('ft'), 'YYYYMMDDHHmmss');
                        var tomt = moment(program.attr('to'), 'YYYYMMDDHHmmss');
                        var radioHours = translateRadikoTimeHours(ftmt, tomt);
                        if (radioHours.ft_hour >= 24) {
                            ftmt.subtract(1, 'days');
                        }
                        var day = sprintf('%04d/%02d/%02d/%s ', ftmt.year(), ftmt.month() + 1, ftmt.date(), ftmt.format('ddd'));
                        var time = sprintf(' %02d:%02d-%02d:%02d', radioHours.ft_hour, ftmt.minute(), radioHours.to_hour, tomt.minute());
                        return day + " " + time
                            + ' | ' + program.find('title').first().text()
                            + ' | ' + _stationName.first().text()
                            + ' | radiko';
                    },
                    omitString: function (string, size) {
                        var txt = string;
                        var suffix = '…';
                        var b = 0;
                        for (var i = 0; i < txt.length; i++) {
                            b += txt.charCodeAt(i) <= 255 ? 0.5 : 1;
                            if (b > size) {
                                txt = txt.substr(0, i) + suffix;
                                break;
                            }
                        }
                        return txt;
                    },
                    getPlayingStatus: function (stationId, ft) {
                        if (_.isUndefined(player) || !player.isPlaying() || !player.isLive()) {
                            return false;
                        }
                        return player.station_id() === stationId && !player.chasing();
                    }
                });
                var NowProgramsListView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.collection.program, 'sync', this.onSync);
                        this.listenTo($.Radiko.Player.Model, 'change:isPlaying', this.onChangeIsPlaying);
                        this.listenTo($.Radiko.Player.Model, 'change:isLoaded', this.onChangeIsLoaded);
                        this.stationTimelinesView = null;
                    },
                    onSync: function (models) {
                        var ftYmd = getDate().format('YYYYMMDD');
                        var stationId = models.models[0].attributes.stationId;
                        this.render(models);
                        showLiveUtil.renderActorListAsync(ftYmd, stationId, models);
                    },
                    onChangeIsPlaying: function (model, isPlaying) {
                        var url = $('#url').val(), $tmpUrl = $('#tmpUrl');
                        if ($tmpUrl.length > 0 && url.indexOf($tmpUrl.val()) === -1) {
                            return;
                        }
                        var $detailButton = $('.live-detail__play');
                        $detailButton.html(JST['live-detail/play-button']({
                            nowPlaying: isPlaying
                        }));
                    },
                    onChangeIsLoaded: function (model, isLoaded) {
                        $('.live-detail__play').removeClass('disabled');
                    },
                    render: function (programs) {
                        var data = programs.findWhere({
                            stationId: _stationId
                        });
                        var program = data.toJSON();
                        dataLayer.push({
                            eStationId: program.stationId,
                            eProgramName: program.progTitle,
                            eStartTime: moment(program.ft, 'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm')
                        });
                        this.renderNowPrgram(program);
                        if (!_.isUndefined(this.programTicker)) {
                            clearInterval(this.programTicker);
                        }
                        this.setColorBox(program, this.collection.areafree);
                        $('.btn--tooltip').on('click', function (e) {
                            e.preventDefault();
                            $(this).toggleClass('btn--disabled').next().toggleClass('tooltip--open');
                        });
                        var $playRadio = $('.live-detail__play');
                        if ($.Radiko.Player.Model.get('isLoaded')) {
                            $('.live-detail__play').removeClass('disabled');
                        }
                        $playRadio.on('click', '.btn--play', function () {
                            if (typeof player === 'undefined') {
                                return;
                            }
                            if ($.Radiko.Player.Model.get('isStartStreaming')) {
                                return;
                            }
                            if (!$.Radiko.login_status.areafree && !isDefaultArea) {
                                $.colorbox({
                                    width: '60%',
                                    inline: true,
                                    speed: 0,
                                    href: '#colorbox--premium',
                                    open: true,
                                    opacity: 0.5
                                });
                                return;
                            }
                            $.Radiko.Player.Model.set('isStartStreaming', true);
                            $.Radiko.Ticker.Model.set('stationId', data.get('stationId'));
                            var playerArea = $('#player-area');
                            playerArea.addClass('player-default');
                            playerArea.removeClass('player-timeshift');
                            var $url = $('#url');
                            var url = $url.val();
                            var tmpUrl = $('#tmpUrl').val();
                            if (url === '' || tmpUrl.match(/^#/) !== null) {
                                url = tmpUrl;
                                $url.val(url);
                            }
                            window.Radiko.Logger.recommendType = undefined;
                            dataLayer.push({
                                playerStationId: program.stationId,
                                playerProgramName: program.progTitle,
                                playerStartTime: moment(program.ft, 'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm')
                            });
                            $.Radiko.Player.View.setTDCategory('live_player');
                            play(url);
                            window.Radiko.Player.ProgramModel.set({
                                station_id: data.get('stationId'),
                                station_name: data.get('stationName'),
                                thumbnail: data.get('progImage'),
                                title: data.get('progTitle'),
                                performer: data.get('progPfm'),
                                start: data.get('ft'),
                                end: data.get('to')
                            });
                            window.Radiko.History.collection.add(window.Radiko.Player.ProgramModel.toJSON());
                            $.Radiko.logger.fromShare = false;
                            updatePlayingProgramInfo({
                                ft: data.get('progFt'),
                                to: data.get('progTo'),
                                title: data.get('progTitle'),
                                pfm: data.get('progPfm'),
                                stationId: data.get('stationId'),
                                stationName: data.get('stationName')
                            });
                        });
                        $playRadio.on('click', '.btn--stop', function () {
                            if (!player.isPlaying()) {
                                return;
                            }
                            $.Radiko.Player.Model.set('isPlaying', false);
                            $.Radiko.RAPF.BannerModel.set('show', false);
                            player.stop();
                        });
                        this.setMetaContent(program);
                        this.renderTopic();
                    },
                    renderNowPrgram: function (programList) {
                        var $btnList = $('.btn-list');
                        $('#now-programs-list').html(JST['live-detail/now-programs-list'](programList));
                        if (programList.progPfm2.length > 10) {
                            $('.live-detail__cast-name').marquee().css('font-size', '15px');
                        }
                        $('.live-detail__description a').attr('target', '_blank');
                        if (!$.Radiko.login_status.areafree && !isDefaultArea) {
                            $('.live-detail__play').replaceWith(JST['live-detail/area-out']);
                            $btnList.remove();
                        }
                    },
                    setColorBox: function (programs, stations) {
                        var _this_1 = this;
                        var result = JST['live-detail/colorbox-share'](programs);
                        $('#share-box').html(result);
                        var clipSelector = '#clipboard';
                        $(clipSelector).on('click', function () {
                            var clipboardCallBack = _this_1.getClipboardCallback(programs, 'copy');
                            _this_1.prepareClipboard(clipSelector, clipboardCallBack);
                        });
                        var covertMoment = function (datetime) {
                            return moment(datetime, 'YYYYMMDDHHmmss');
                        };
                        var ftMoment = covertMoment(programs.progFt);
                        var toMoment = covertMoment(programs.progTo);
                        var playtime = toMoment.diff(ftMoment, 'seconds');
                        $('.end').text('-' + sec_to_disptime(playtime / 1000));
                        var self = this;
                        $('.btn--share').colorbox({
                            width: '685px',
                            inline: true,
                            speed: 0,
                            opacity: 0.5,
                            onOpen: function () {
                                window.Radiko.Share.ProgramModel.set({
                                    station_id: programs.stationId,
                                    station_name: programs.stationName,
                                    thumbnail: programs.progImage,
                                    title: programs.progTitle,
                                    performer: programs.progPfm,
                                    start: programs.progFt,
                                    end: programs.progTo
                                });
                                $.Radiko.Player.isShareOpenForBanner = true;
                                $.Radiko.RAPF.BannerModel.set('isTabActive', false);
                                var delay = stations.findWhere({
                                    id: _stationId
                                }).get('tf_max_delay');
                                var playableMoment = ftMoment.clone().add(delay, 'seconds').add($.Radiko.playingBuffer, 'seconds');
                                if (playableMoment.isSameOrAfter() && ftMoment.isSameOrBefore()) {
                                    $('.cnt-text').show();
                                    $('.btn-list').hide();
                                    setInterval(function () {
                                        var time = playableMoment.diff(moment(), 'seconds');
                                        if (time <= 0) {
                                            $('.cnt-text').hide();
                                            $('.btn-list').show();
                                            return;
                                        }
                                        $('#colorbox--share').find('.colorbox__text .sec').text(time);
                                    }, 1000);
                                }
                                else {
                                    $('.btn-list').show();
                                    $('.cnt-text').hide();
                                    var totalPlayTime = playtime;
                                    var nowPlayTime = moment().diff(ftMoment, 'seconds') - 60;
                                    var rate = nowPlayTime / totalPlayTime;
                                    if (rate >= 1) {
                                        rate = 1;
                                        nowPlayTime = totalPlayTime;
                                    }
                                    else if (rate <= 0) {
                                        rate = 0;
                                        nowPlayTime = 0;
                                    }
                                    var seekBar = $('.colorbox__seek .seek-bar');
                                    var seekBarWidth = seekBar.width();
                                    var nowPointerPos = seekBarWidth * rate;
                                    if (nowPointerPos >= seekBarWidth) {
                                        nowPointerPos = seekBarWidth;
                                    }
                                    else if (nowPointerPos <= 0) {
                                        nowPointerPos = 0;
                                    }
                                    else {
                                    }
                                    seekBar.find('.knob').css('left', nowPointerPos - 3);
                                    seekBar.find('.active').css('width', nowPointerPos - 3);
                                    var remainingPlayTime = totalPlayTime - nowPlayTime;
                                    $.Radiko.Share.setSeekPlayTime(nowPlayTime, remainingPlayTime);
                                    var tsUrlParam = {
                                        station_id: programs.stationId,
                                        ft: new XDate(ftMoment.valueOf(), false),
                                        to: new XDate(toMoment.valueOf(), false),
                                        seek: new XDate(ftMoment.clone().add(nowPlayTime, 'seconds').valueOf(), false)
                                    };
                                    var tsUrl = create_ts_url(tsUrlParam);
                                    var shareFB = $('.btn__facebook');
                                    var shareTW = $('.btn__twitter');
                                    var clipBoard = $('#clipboard');
                                    var fShareUrl = shareFB.data('url');
                                    var tShareUrl = shareTW.data('urlbase');
                                    var cShareUrl = clipBoard.data('urlbase');
                                    var now = xdate_to_tm(tsUrlParam.seek);
                                    shareFB.attr('href', fShareUrl + now);
                                    shareTW.attr('href', tShareUrl + now);
                                    clipBoard.attr('data-clipboard-text', cShareUrl + now);
                                    seekBar.attr('data-ts', now);
                                    $('#share-url').val(tsUrl);
                                }
                                $(window).on('resize.visible', function () {
                                    $('#colorbox').css('overflow', 'visible');
                                });
                                self.renderColorboxEmbedCode(programs);
                            },
                            onClosed: function () {
                                $(window).off('resize.visible');
                                self.sharePlayerStop();
                                $.Radiko.Player.isShareOpen = false;
                                $.Radiko.Player.isShareOpenForBanner = false;
                                $.Radiko.RAPF.BannerModel.set('isTabActive', true);
                            }
                        });
                        $('.btn__facebook').on('click', function () {
                            window.open(this.href, 'TWwindow', 'width=650, height=450, menubar=no, toolbar=no, scrollbars=yes');
                            var ts = $('.colorbox__seek .seek-bar').attr('data-ts');
                            dataLayer.push({
                                event: 'FireTdEvent',
                                eCategory: 'live_broadcast',
                                eAction: 'click',
                                eLabel: 'share_facebook'
                            });
                            $.Radiko.logger.share_log({
                                type: 'do_share',
                                sns: 'facebook',
                                t: ts,
                                stationId: programs.stationId,
                                timeType: 'live'
                            });
                            return false;
                        });
                        $('.btn__twitter').on('click', function () {
                            window.open(this.href, 'FBwindow', 'width=650, height=450, menubar=no, toolbar=no, scrollbars=yes');
                            var ts = $('.colorbox__seek .seek-bar').attr('data-ts');
                            dataLayer.push({
                                event: 'FireTdEvent',
                                eCategory: 'live_broadcast',
                                eAction: 'click',
                                eLabel: 'share_twitter'
                            });
                            $.Radiko.logger.share_log({
                                type: 'do_share',
                                sns: 'twitter',
                                t: ts,
                                stationId: programs.stationId,
                                timeType: 'live'
                            });
                            return false;
                        });
                    },
                    onClose: function () {
                        clearInterval(this.programTicker);
                        _.each(intervals, function (timer) {
                            clearInterval(timer);
                        });
                        if (this.stationTimelinesView) {
                            this.stationTimelinesView.onClose();
                            this.stationTimelinesView.remove();
                        }
                    },
                    setMetaContent: function (data) {
                        var setting = {};
                        var desc = '';
                        desc += data.progDesc == '' ? '' : data.progDesc.replace(/(<([^>]+)>)/ig, '');
                        desc += data.progInfo == '' ? '' : data.progInfo.replace(/(<([^>]+)>)/ig, '');
                        setting.title = data.metaTitle;
                        setting['og:title'] = data.metaTitle;
                        setting['og:type'] = 'article';
                        setting['og:description'] = desc.substr(0, 93);
                        setting['og:url'] = data.shareUrl;
                        setting['og:image'] = data.progImage;
                        setting['twitter:title'] = data.metaTitle;
                        setting['twitter:description'] = desc.substr(0, 93);
                        setMetaText(setting);
                    },
                    renderTopic: function () {
                        var topicCollection = new TopicCollection();
                        $.Radiko.views.push(new TopicView({
                            el: document.getElementById('topic-list'),
                            collection: topicCollection
                        }));
                        topicCollection.fetch();
                    },
                    renderColorboxEmbedCode: function (programs) {
                        var _this_1 = this;
                        var clipSelector = '#clipboard-embed';
                        var copyButton = $(clipSelector);
                        var widthInput = $('.width-text');
                        var self = this;
                        $('.btn--embedcode').colorbox({
                            width: '850px',
                            inline: true,
                            speed: 0,
                            opacity: 0.5,
                            onCleanup: function () {
                                $('#colorbox--embedcode iframe').attr({ src: '' });
                            },
                            onClosed: function () {
                                $(window).off('resize.visible');
                                self.sharePlayerStop();
                                $.Radiko.Player.isShareOpen = false;
                                $.Radiko.Player.isShareOpenForBanner = false;
                                $.Radiko.RAPF.BannerModel.set('isTabActive', true);
                                $('#embed-showcode').off();
                                if ($('#embed-showcode').prop('checked')) {
                                    $('#embed-showcode').removeAttr('checked').prop('checked', false);
                                    var cboxContentEl = $('#cboxContent')[0];
                                    var origin = cboxContentEl.style.height !== null ? parseInt(cboxContentEl.style.height) : 0;
                                    $('#colorbox--embedcode section')[0].style.top = origin + "px";
                                    $('#colorbox--embedcode section').removeClass('embedcode-section-show');
                                    $('#colorbox--embedcode .embedcode-background').removeClass('embedcode-background-show');
                                }
                                $('#cboxContent')[0].style.transition = "none";
                                if ($('#cboxLoadedContent')[0]) {
                                    $('#cboxLoadedContent')[0].style.transition = "none";
                                }
                            }
                        });
                        this.setHeightOption();
                        if ($('.easy-select-box').length == 0) {
                            $('#colorbox--embedcode').find("select").easySelectBox({
                                onClick: function (e) {
                                    var selectedHeight = e.value;
                                    var currentIframeHeight = $('#colorbox--embedcode iframe').attr('height');
                                    if (selectedHeight !== currentIframeHeight) {
                                        self.updateIframe(programs);
                                    }
                                    $('#colorbox--embedcode').find(".esb-displayer").append('<i class="icon icon--arrow-d-gray"></i>');
                                }
                            });
                            $('#colorbox--embedcode').find(".esb-displayer").append('<i class="icon icon--arrow-d-gray"></i>');
                        }
                        widthInput.on('blur', function () {
                            var widthVal = widthInput.val();
                            var lowerWidthVal = _this_1.inputToHalf(widthVal);
                            var supZeroNum = lowerWidthVal.replace(/^0+/, '');
                            var width = Math.round(supZeroNum.split(/[^0-9.]/)[0]) || 0;
                            var isOnlyNum = !/[^0-9.]/.test(lowerWidthVal) && /^[0-9]+\.?[0-9]*$/.test(lowerWidthVal);
                            var hasPercent = /%/.test(lowerWidthVal);
                            var hasPx = /px/.test(lowerWidthVal);
                            var isPercent = /^[0-9]+\.?[0-9]*%/.test(lowerWidthVal);
                            var isPx = /^[0-9]+\.?[0-9]*px/.test(lowerWidthVal);
                            if ((hasPercent && hasPx) || (!isOnlyNum && !isPx && !isPercent)) {
                                widthInput.val("40%");
                            }
                            else if (isPx) {
                                widthInput.val(width + "px");
                                if (width < 300)
                                    widthInput.val("300px");
                                if (width > 750)
                                    widthInput.val("750px");
                            }
                            else if (isOnlyNum || isPercent) {
                                widthInput.val(width + "%");
                                if (width < 40)
                                    widthInput.val("40%");
                                if (width > 100)
                                    widthInput.val("100%");
                            }
                            var currentIframeWidth = $('#colorbox--embedcode iframe').attr('width');
                            if (widthInput.val() !== currentIframeWidth) {
                                self.updateIframe(programs);
                            }
                        });
                        copyButton.on('click', function () {
                            var iframeAttr = _this_1.getIframeAttr(programs);
                            var embedCode = _this_1.getEmbedCode(iframeAttr);
                            _this_1.updateEmbedCopyString(embedCode);
                            var clipboardCallback = _this_1.getClipboardCallback(programs, 'embed');
                            _this_1.prepareClipboard(clipSelector, clipboardCallback);
                        });
                        $('#embed-showcode').on('change', function () {
                            var cboxContentEl = $('#cboxContent')[0];
                            var origin = cboxContentEl.style.height !== null ? parseInt(cboxContentEl.style.height) : 0;
                            var isChecked = $('#embed-showcode').prop("checked");
                            if (isChecked) {
                                $('#colorbox--embedcode section')[0].style.top = origin + 80 + "px";
                            }
                            else {
                                $('#colorbox--embedcode section')[0].style.top = origin + "px";
                            }
                            $('#colorbox--embedcode section').toggleClass('embedcode-section-show', isChecked);
                            $('#colorbox--embedcode .embedcode-background').toggleClass('embedcode-background-show', isChecked);
                        });
                        $('#embedcode').on('dragSeekKnob skipSeconds', function () {
                            var iframeAttr = _this_1.getIframeAttr(programs);
                            var embedCode = _this_1.getEmbedCode(iframeAttr);
                            self.updateEmbedCodeView(embedCode);
                        });
                        $('.btn--embedcode').one('click', function () {
                            _this_1.updateIframe(programs);
                        });
                    },
                    updateIframe: function (programs) {
                        var iframeAttr = this.getIframeAttr(programs);
                        var embedCode = this.getEmbedCode(iframeAttr);
                        var title = iframeAttr.title, width = iframeAttr.width, height = iframeAttr.height, src = iframeAttr.src;
                        $('#colorbox--embedcode iframe').attr({
                            title: title,
                            src: src,
                            width: width,
                            height: height + "px"
                        });
                        this.updateEmbedCodeView(embedCode);
                        this.updateEmbedCopyString(embedCode);
                    },
                    updateEmbedCodeView: function (embedCode) {
                        var codeView = $('#embedcode');
                        codeView.text(embedCode);
                    },
                    updateEmbedCopyString: function (embedCode) {
                        var copyButton = $('#clipboard-embed');
                        copyButton[0].dataset.clipboardText = embedCode;
                    },
                    getEmbedCode: function (iframeAttr) {
                        var title = iframeAttr.title, width = iframeAttr.width, height = iframeAttr.height, src = iframeAttr.src;
                        return "<iframe title=\"" + title + "\" src=\"" + src + "\" width=\"" + width + "\" height=\"" + height + "px\" allow=\"clipboard-write *; web-share *;\"></iframe>";
                    },
                    getIframeAttr: function (programs) {
                        var title = programs.progTitle;
                        if (title.match(/\"/)) {
                            title = title.replace(/\"/g, '&quot;');
                        }
                        var width = $('.width-text').val();
                        var height = $('.esb-displayer').text() === "標準(288px)" ? 288 : 104;
                        var heightType = $('.esb-displayer').text() === "標準(288px)" ? "default" : "compact";
                        var sid = programs.stationId;
                        var ts = $('.colorbox__seek .seek-bar').attr('data-ts') || programs.ft;
                        var src = window.location.origin + "/embed/events?sid=" + sid + "&t=" + ts + "&type=" + heightType;
                        return { title: title, width: width, height: height, src: src };
                    },
                    getClipboardCallback: function (programs, snsShareLog) {
                        var successCallback = function () {
                            alert('コピーしました。');
                            var ts = $('.colorbox__seek .seek-bar').attr('data-ts');
                            $.Radiko.logger.share_log({
                                type: 'do_share',
                                stationId: programs.stationId,
                                sns: snsShareLog,
                                t: ts,
                                timeType: 'live'
                            });
                        };
                        return successCallback;
                    },
                    prepareClipboard: function (selector, successCallBack) {
                        if (typeof Clipboard !== 'undefined' && Clipboard.isSupported()) {
                            if (window.clipboardObject) {
                                window.clipboardObject.destroy();
                            }
                            window.clipboardObject = new Clipboard(selector, {
                                container: $(selector)[0]
                            });
                            window.clipboardObject.on('success', successCallBack);
                        }
                        else {
                            var client_1 = new ZeroClipboard($(selector));
                            client_1.on('ready', function () {
                                client_1.on('aftercopy', successCallBack);
                            });
                        }
                    },
                    setHeightOption: function () {
                        var select = $('select[name=height]');
                        var defaultHeight = $('<option></option>', {
                            value: '288px',
                            text: '標準(288px)'
                        });
                        var compactHeight = $('<option></option>', {
                            value: '104px',
                            text: 'コンパクト(104px)'
                        });
                        select.append(defaultHeight[0].outerHTML);
                        select.append(compactHeight[0].outerHTML);
                    },
                    sharePlayerStop: function () {
                        changePlayButton();
                        if (isSharePlay && player.isPlaying()) {
                            player.stop();
                        }
                        isSharePlay = false;
                        player._player._isSharePlay = isSharePlay;
                        if ($.Radiko.Share.isBeforePlaying) {
                            $.Radiko.Share.isBeforePlaying = false;
                            window.Radiko.History.collection.add(window.Radiko.Player.ProgramModel.toJSON());
                            play($('#url').val());
                        }
                    },
                    inputToHalf: function (input) {
                        return input.replace(/ｐｘ|％|[０-９]+/g, function (fullString) {
                            var halfString = "";
                            for (var i = 0; i < fullString.length; i++) {
                                halfString += String.fromCharCode(fullString.charCodeAt(i) - 0xFEE0);
                            }
                            return halfString;
                        });
                    }
                });
                var MusicsView = Backbone.View.extend({
                    prevMusicItemId: null,
                    ticketCollection: {},
                    merchCollection: {},
                    initialize: function () {
                        this.ticketCollection = {};
                        this.merchCollection = {};
                        this.listenTo(this.collection.ticket, 'sync', this.onSync);
                        this.listenTo(this.collection.ticket, 'error', this.onError);
                        this.listenTo(this.collection.merch, 'sync', this.onMerchSync);
                        this.listenTo(this.collection.merch, 'error', this.onMerchError);
                    },
                    onSync: function (ticketCollection) {
                        this.ticketCollection = ticketCollection;
                        this.addMerchData();
                    },
                    onError: function (ticketCollection) {
                        this.ticketCollection = ticketCollection.collection;
                        this.addMerchData();
                    },
                    onMerchSync: function (merchCollection) {
                        this.merchCollection = merchCollection;
                        this.addMerchData();
                    },
                    onMerchError: function (merchCollection) {
                        this.merchCollection = merchCollection.collection;
                        this.addMerchData();
                    },
                    remove: function () {
                    },
                    addMerchData: function () {
                        if (!Object.keys(this.ticketCollection).length || !Object.keys(this.merchCollection).length) {
                            return false;
                        }
                        var First_ticketCollection_stamp = this.ticketCollection.models[0].get('stamp_original');
                        var First_merchCollection_stamp = this.merchCollection.models[0].get('stamp_original');
                        if (!moment(First_ticketCollection_stamp).isSame(First_merchCollection_stamp)) {
                            return false;
                        }
                        var ticketCollection = this.ticketCollection;
                        var merchCollection = this.merchCollection.models;
                        ticketCollection.models.forEach(function (e) {
                            var set_stamp_original = e.get('stamp_original');
                            var merchInfo = _.find(merchCollection, function (num) {
                                var merchset_stamp_original = num.get('stamp_original');
                                return merchset_stamp_original === set_stamp_original;
                            });
                            if (typeof merchInfo === 'undefined') {
                                e.attributes.merch = {};
                            }
                            else {
                                var merch = merchInfo.attributes.merch;
                                e.attributes.merch = merch;
                            }
                        });
                        this.render(ticketCollection);
                    },
                    render: function (ticketCollection) {
                        var newItemId = ticketCollection.at(0).get('itemId');
                        if (this.prevMusicItemId === newItemId) {
                            return false;
                        }
                        this.prevMusicItemId = newItemId;
                        var data = ticketCollection.toJSON();
                        var first = data[0], other = data.slice(1);
                        $('#play-musics').html(JST['detail-common/play-musics']({
                            models: other,
                            stream_type: 'LV'
                        }));
                        $('#noa').html(JST['detail-common/noa-item']({
                            model: first,
                            stream_type: 'LV'
                        }));
                        $('.ticket-list__link a').on('click', function () {
                            var $ticketColorBox = $('#colorbox--ticket');
                            $ticketColorBox.html(new RadikoTicket.DialogView({
                                noa_item: data[0],
                                stream_type: 'LV'
                            }).el);
                            $.colorbox({
                                scrolling: false,
                                inline: true,
                                href: $ticketColorBox,
                                speed: 0,
                                opacity: 0.5
                            });
                        });
                        $('.tune-list__item').heightLine();
                        this.listMore();
                        $('.tune-list__ticket button').on('click', function (e) {
                            var id = $(e.target).data('id');
                            var $ticketColorBox = $('#colorbox--ticket');
                            $ticketColorBox.html(new RadikoTicket.DialogView({
                                noa_item: other[id],
                                stream_type: 'LV'
                            }).el);
                            $.colorbox({
                                scrolling: false,
                                inline: true,
                                href: $ticketColorBox,
                                speed: 0,
                                opacity: 0.5
                            });
                        });
                        return this;
                    },
                    listMore: function () {
                        var showNum = 3;
                        var showItems = $('.tune-list__item');
                        showItems.addClass('hide-tune-item');
                        var listNum = showItems.length;
                        showItems.hide();
                        var moreBtn = $('.tune-list__more');
                        if (showNum > listNum) {
                            showNum = listNum;
                            moreBtn.remove();
                        }
                        var hideItems = $('.hide-tune-item');
                        for (var i = 0; i < showNum; i++) {
                            hideItems.eq(i).show();
                            hideItems.eq(i).removeClass('hide-tune-item');
                            hideItems.eq(i).addClass('show-tune-item');
                        }
                        moreBtn.on('click', function () {
                            var showItems = $('.hide-tune-item');
                            hideItems.show();
                            showItems.removeClass('hide-tune-item');
                            showItems.addClass('show-tune-item');
                            $(this).remove();
                            $(this).off('click');
                        });
                    }
                });
                var StationTimelineModel = Backbone.Model.extend({
                    defaults: {}
                });
                var StationTimelinesCollection = Backbone.Collection.extend({
                    model: StationTimelineModel,
                    initialize: function (models) {
                        this.listenTo(models, 'sync', this.onSync);
                    },
                    onSync: function () {
                        this.url = '/v2/twitter/search/' + window.stationTimelineKey + '.json';
                        this.fetch();
                    },
                    parse: function (resp) {
                        return _.map(resp.statuses, function (status) {
                            status.created_at = moment(status.created_at, 'ddd MMM DD HH:mm:ss ZZ YYYY').format('YYYY年M月D日 HH:mm');
                            var urlEntities = status.entities.urls;
                            if (status.entities.media) {
                                urlEntities = _.flatten([urlEntities, status.entities.media]);
                            }
                            status.text = twttr.txt.autoLink(status.text, { urlEntities: urlEntities });
                            return status;
                        });
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = 'json';
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    }
                });
                var StationTimelinesView = Backbone.View.extend({
                    initialize: function () {
                        this.listenTo(this.collection, 'sync', this.onSync);
                        var self = this;
                        this.timer = setInterval(function () {
                            self.collection.fetch();
                        }, 60000);
                    },
                    onSync: function (models) {
                        this.render(models);
                    },
                    render: function (models) {
                        var data = models.toJSON();
                        $('#timeline-station').html(JST['live-detail/timeline-station']({
                            models: data
                        }));
                        $('.stream-item-text a').attr('target', '_blank');
                        return this;
                    },
                    onClose: function () {
                        clearInterval(this.timer);
                    }
                });
                var StationWeeklyModel = Backbone.Model.extend({
                    defaults: {}
                });
                var StationWeeklyCollection = Backbone.Collection.extend({
                    model: StationWeeklyModel,
                    initialize: function () {
                        this.stationId = _stationId;
                        this.areaId = $.Radiko.area.id;
                        this.currentDate = moment();
                        if (this.currentDate.format('HHmmdd') <= '050000') {
                            this.currentDate.subtract(1, 'day');
                        }
                    },
                    setCurrentDate: function (moment) {
                        this.currentDate = moment;
                    },
                    url: function () {
                        return '/v3/program/station/weekly/' + this.stationId + '.xml';
                    },
                    fetch: function (options) {
                        return Backbone.Collection.prototype.fetch.call(this, _.extend({
                            dataType: 'xml'
                        }, options));
                    },
                    parse: function (resp) {
                        return _.map($('progs', resp), function (progs) {
                            var _this = this;
                            var $progs = $(progs);
                            var now = getDate();
                            var stationId = $progs.parent('station').attr('id');
                            return {
                                date: $progs.find('date').text(),
                                progs: _.map($progs.find('prog'), function (prog) {
                                    var $prog = $(prog);
                                    var ftl = $prog.attr('ftl');
                                    var tol = $prog.attr('tol');
                                    var ft = $prog.attr('ft');
                                    var to = $prog.attr('to');
                                    now = moment();
                                    var addClass = '';
                                    var programUrl = '/#!/ts/' + stationId + '/' + ft;
                                    var listenType = 0;
                                    if (to <= now.format('YYYYMMDDHHmmss')) {
                                        addClass += 'item--past ';
                                        listenType = _this.getListenType(stationId, ft, to);
                                    }
                                    else if (ft >= now.format('YYYYMMDDHHmmss')) {
                                        addClass += 'item--future ';
                                    }
                                    else {
                                        programUrl = '/#!/live/' + stationId;
                                        addClass += 'item--onair ';
                                    }
                                    return {
                                        id: stationId,
                                        ftl: ftl,
                                        ft: ft,
                                        to: to,
                                        tol: tol,
                                        dur: parseInt($prog.attr('dur'), 10),
                                        title: $prog.find('title').first().text(),
                                        pfm: $prog.find('pfm').first().text(),
                                        img: $prog.find('img').text(),
                                        addClass: addClass,
                                        program_url: programUrl,
                                        scheduleString: _this.getScheduleString(ft, to),
                                        listenType: listenType
                                    };
                                })
                            };
                        }, this);
                    },
                    getScheduleString: function (ft, to) {
                        var ftmt = moment(ft, 'YYYYMMDDHHmmss');
                        var tomt = moment(to, 'YYYYMMDDHHmmss');
                        var radioHours = translateRadikoTimeHours(ftmt, tomt);
                        if (radioHours.ft_hour >= 24) {
                            ftmt.subtract(1, 'days');
                        }
                        var ftTime = sprintf('%02d:%02d', radioHours.ft_hour, ftmt.minute());
                        var toTime = sprintf('%02d:%02d', radioHours.to_hour, tomt.minute());
                        return ftTime + '〜' + toTime;
                    }
                });
                _.extend(StationWeeklyCollection.prototype, $.Radiko.Mixins.Utility);
                var WeeklyListView = Backbone.View.extend({
                    initialize: function () {
                        this.currentDate = null;
                        this.listenTo(this.collection, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        this.currentDate = this.collection.currentDate;
                        this.render(models);
                    },
                    render: function (models) {
                        var modelsJson = models.toJSON();
                        this.renderProgramDate();
                        this.renderProgramItems(modelsJson);
                        this.defineUi();
                        setScrollInit();
                        return this;
                    },
                    renderProgramDate: function () {
                        var _this = this;
                        var beforeDate = _.map(Array.apply(null, new Array(7)), function (d, i) {
                            var date = getDate().subtract(i + 1, 'days');
                            return {
                                dateFullString: date.format('YYYYMMDD'),
                                dateString: date.format('M/D'),
                                dayString: date.format('(ddd)'),
                                isCurrent: _this.currentDate.isSame(date, 'day'),
                                isSat: date.day() === 6,
                                isSun: date.day() === 0
                            };
                        });
                        beforeDate.reverse();
                        var afterDate = _.map(Array.apply(null, new Array(7)), function (d, i) {
                            var date = getDate().add(i, 'days');
                            return {
                                dateFullString: date.format('YYYYMMDD'),
                                dateString: date.format('M/D'),
                                dayString: date.format('(ddd)'),
                                isCurrent: _this.currentDate.isSame(date, 'day'),
                                isSat: date.day() === 6,
                                isSun: date.day() === 0
                            };
                        });
                        $('.program-table__date-outer').html(JST['live-detail/program-table-date']({
                            dateList: beforeDate.concat(afterDate)
                        }));
                    },
                    renderProgramItems: function (data) {
                        var beforeProgs = data.splice(0, 7);
                        $('.program-table__items').html(JST['common/program-table-items']({
                            models: beforeProgs.concat(data),
                            tableWidth: (data.length * 159 - 1) + 'px'
                        }));
                    },
                    defineUi: function () {
                        $('.js-scroll').css('left', '-945px');
                        $('.js-next').hide();
                    },
                    events: {
                        'click .js-select-date': 'selectDateClickHandler',
                        'click .js-prev': 'prevClickHandler',
                        'click .js-next': 'nextClickHandler'
                    },
                    selectDateClickHandler: function (ev) {
                        ev.preventDefault();
                        $.Radiko.EventEmitter.trigger('change:currentDate', ev.target.hash.substring(1));
                    },
                    prevClickHandler: function (ev) {
                        ev.preventDefault();
                        if ($('.js-prev').hasClass('btn-disable')) {
                            return;
                        }
                        var $scrolls = $('.js-scroll');
                        var left = parseInt($scrolls.css('left').replace('px', ''));
                        $scrolls.stop(true, true);
                        $('.js-prev').addClass('btn-disable');
                        $scrolls.animate({
                            left: left + 135
                        }).promise().done(function () {
                            $scrolls.each(function (index, elScroll) {
                                $scrolls.css('left', left + 135);
                            });
                            $('.js-prev').removeClass('btn-disable');
                            var left = parseInt($scrolls.css('left').replace('px', ''));
                            if (left >= 0) {
                                $scrolls.css('left', 0);
                                $('.js-next').show();
                                $('.js-prev').hide();
                            }
                            else {
                                $('.js-next').show();
                            }
                        });
                    },
                    nextClickHandler: function (ev) {
                        ev.preventDefault();
                        if ($('.js-next').hasClass('btn-disable')) {
                            return;
                        }
                        var $scrolls = $('.js-scroll');
                        var left = parseInt($scrolls.css('left').replace('px', ''));
                        $('.js-next').addClass('btn-disable');
                        $scrolls.stop(true, true);
                        $scrolls.each(function (index, elScroll) {
                            $scrolls.css('left', left);
                        }).animate({
                            left: left - 135
                        }, function () {
                            $('.js-next').removeClass('btn-disable');
                            var left = parseInt($scrolls.css('left').replace('px', ''));
                            if (left <= -945) {
                                $scrolls.css('left', -945);
                                $('.js-prev').show();
                                $('.js-next').hide();
                            }
                            else {
                                $('.js-prev').show();
                            }
                        });
                    }
                });
                var OtherModel = Backbone.Model.extend({
                    defaults: {
                        models: []
                    }
                });
                var OthersCollection = Backbone.Collection.extend({
                    model: OtherModel,
                    url: '/v3/radioweb/bansen/station/' + _stationId + '.xml',
                    parse: function (resp) {
                        return _.map($('item', resp), function (item) {
                            var $item = $(item);
                            return {
                                image_url: $item.find('image_url').text(),
                                program_name: $item.find('program_name').text(),
                                description: $item.find('description').text().replace(/(<([^>]+)>)/ig, ''),
                                onair: $item.find('onair').text(),
                                type: $item.find('type').text(),
                                url: $item.find('radioweb_detail_url').text()
                            };
                        }, this);
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = 'xml';
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    }
                });
                var OthersView = 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 result = JST['common/others-program']({
                            models: data
                        });
                        $('#others-program').html(result);
                        $('.img-list__text').each(function () {
                            var size = 35;
                            var txt = $(this).text();
                            var suffix = '…';
                            var b = 0;
                            for (var i = 0; i < txt.length; i++) {
                                b += txt.charCodeAt(i) <= 255 ? 0.5 : 1;
                                if (b > size) {
                                    txt = txt.substr(0, i) + suffix;
                                    break;
                                }
                            }
                            $(this).text(txt);
                        });
                        $('.img-list__item').heightLine();
                        return this;
                    }
                });
                var SyncAdModel = Backbone.Model.extend({
                    defaults: {
                        models: []
                    }
                });
                var SyncAdCollection = Backbone.Collection.extend({
                    model: SyncAdModel,
                    url: '/v3/feed/pc/extra/' + _stationId + '.xml',
                    parse: function (resp) {
                        return _.map($('item', resp), function (item) {
                            var $item = $(item);
                            return {
                                content_url: $item.attr('content_url'),
                                event: $item.attr('event'),
                                evid: $item.attr('evid'),
                                href: $item.attr('href'),
                                img: $item.attr('img'),
                                itemid: $item.attr('itemid'),
                                stamp: $item.attr('stamp')
                            };
                        }, this);
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = 'xml';
                        options.cache = false;
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    }
                });
                var AdHistoryModel = Backbone.Model.extend({
                    defaults: {
                        models: []
                    }
                });
                var AdHistoryCollection = Backbone.Collection.extend({
                    model: AdHistoryModel,
                    url: '/v3/feed/pc/cm/' + _stationId + '.xml',
                    parse: function (resp) {
                        return _.map($('item', resp), function (item) {
                            var $item = $(item);
                            return {
                                desc: $item.attr('desc'),
                                href: $item.attr('href'),
                                img: $item.attr('img'),
                                evid: $item.attr('evid'),
                                stamp: $item.attr('stamp')
                            };
                        }, this);
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = 'xml';
                        options.cache = false;
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    }
                });
                var AdHistoryView = Backbone.View.extend({
                    events: {
                        'click a': 'onClick'
                    },
                    initialize: function () {
                        this.listenTo(this.collection, 'sync', this.onSync);
                        var self = this;
                        this.timer = setInterval(function () {
                            self.collection.fetch();
                        }, 11000);
                    },
                    onClose: function () {
                        clearInterval(this.timer);
                    },
                    preCmList: null,
                    onSync: function (models) {
                        var cmList = models.toJSON();
                        if (!this.preCmList || this.isSame(cmList)) {
                            this.render(models);
                            this.sendViewBeacon(cmList);
                        }
                        this.preCmList = cmList;
                    },
                    onClick: function (e) {
                        $.Radiko.logger.ad_log('click.gif?ad_id=' + $(e.currentTarget).data('evid') + '&station_id=' + _stationId);
                    },
                    isSame: function (cmList) {
                        if (!this.preCmList) {
                            return false;
                        }
                        return -1 == _.findIndex(this.preCmList, { stamp: cmList[0].stamp });
                    },
                    render: function (models) {
                        $('#ad-history').html(JST['live-detail/ad-history']({
                            models: models.toJSON()
                        }));
                        if (!_.contains($.Radiko.user_station_list, _stationId)) {
                            $('.live-detail__attention').show();
                        }
                        else {
                        }
                        return this;
                    },
                    sendViewBeacon: function (cmList) {
                        var preList = this.preCmList;
                        _.each(_.filter(cmList, function (item) {
                            return undefined === _.find(preList, function (preItem) {
                                return item.stamp === preItem.stamp;
                            });
                        }), function (item) {
                            $.Radiko.logger.ad_log('view.gif?ad_id=' + item.evid + '&station_id=' + _stationId);
                        });
                    }
                });
                var TopicModel = Backbone.Model.extend({
                    defaults: {
                        models: []
                    }
                });
                var TopicCollection = Backbone.Collection.extend({
                    model: TopicModel,
                    url: '/v3/feed/pc/topic/' + _stationId + '.xml',
                    parse: function (resp) {
                        return _.map($('item', resp), function (item) {
                            var $item = $(item);
                            return {
                                desc: $item.attr('desc'),
                                href: $item.attr('href'),
                                img: $item.attr('img'),
                                evid: $item.attr('evid'),
                                stamp: $item.attr('stamp')
                            };
                        }, this);
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = 'xml';
                        options.cache = false;
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    }
                });
                var TopicView = Backbone.View.extend({
                    events: {
                        'click a': 'onClick'
                    },
                    initialize: function () {
                        this.exclude_topic_id = [];
                        this.listenTo(this.collection, 'sync', this.onSync);
                        var self = this;
                        this.timer = setInterval(function () {
                            self.collection.fetch();
                        }, 60 * 1000);
                    },
                    onClose: function () {
                        clearInterval(this.timer);
                    },
                    preCmList: null,
                    onSync: function (models) {
                        var topicList = models.toJSON();
                        this.render(models);
                        this.sendViewBeacon(topicList);
                    },
                    onClick: function (e) {
                        $.Radiko.logger.ad_log('click.gif?ad_id=' + $(e.currentTarget).data('evid') + '&station_id=' + _stationId);
                    },
                    render: function (models) {
                        $('#topic-list').html(JST['live-detail/topic-list']({
                            topics: models.toJSON()
                        }));
                        return this;
                    },
                    sendViewBeacon: function (topicList) {
                        var preList = this.preCmList, _self = this;
                        _.each(_.filter(topicList, function (item) {
                            return undefined === _.find(preList, function (preItem) {
                                return item.stamp === preItem.stamp;
                            });
                        }), function (item) {
                            if (_.contains(_self.exclude_topic_id, item.evid)) {
                                return;
                            }
                            _self.exclude_topic_id.push(item.evid);
                            $.Radiko.logger.ad_log('view.gif?ad_id=' + item.evid + '&station_id=' + _stationId);
                        });
                    }
                });
            })($.Radiko || ($.Radiko = {}));
            $('#header').html(JST['common/header']({ logo: '/apps/images/img_logo_blue_01.png' }));
            var live = new $.Radiko.Live();
            $.Radiko.EventEmitter.once('radikoshowlive', function () {
                makeHeader();
                live.initialize();
                playerEvent();
                sharePlayerEvent({ eCategory: 'live_broadcast' });
                $('input[type="text"]').placeholder();
                $('#tmpUrl').val('#' + _stationId);
                $('#heading-area-link').find('a').on('click', function () {
                    $('html, body').animate({
                        scrollTop: $('#program-table').offset().top - $('#header-nav').height() * 2
                    }, 500);
                    return false;
                });
            });
            if (_.isString($.Radiko.area.id)) {
                $.Radiko.EventEmitter.trigger('radikoshowlive');
            }
            if (window.area != undefined) {
                $('span.area').text(window.area);
            }
        });
    })(window, jQuery, Backbone, _, moment);
};
