"use strict";
var radikoTt = function () {
    (function (window, $, Backbone, _, moment, undefined) {
        loadTemplate({
            '#contents': '/apps/templates/timetable/index.html',
            '#footer': '/apps/templates/common/footer.html'
        }, function () {
            (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 tsTimetable = (function () {
                    function tsTimetable() {
                        this.stationCollection = null;
                        this.stationsCollection = null;
                    }
                    tsTimetable.prototype.initialize = function () {
                        this.createModels();
                        this.createViews();
                        this.fetchAll([
                            {
                                model: this.stationsCollection
                            }
                        ]);
                        this.subscribeAll();
                    };
                    tsTimetable.prototype.createModels = function () {
                        this.stationsCollection = new StationsCollection();
                        this.stationCollection = new StationCollection(this.stationsCollection);
                    };
                    tsTimetable.prototype.createViews = function () {
                        $.Radiko.views.push(new TimetableListView({
                            el: document.getElementById('program-table'),
                            collection: this.stationCollection
                        }));
                    };
                    tsTimetable.prototype.fetchAll = function (models) {
                        return $.when.apply($, _.map(models, function (queue) {
                            return queue.model.fetch(queue.options || {});
                        }));
                    };
                    tsTimetable.prototype.subscribeAll = function () {
                        var _this = this;
                        $.Radiko.EventEmitter.on('change:currentDate', function (date) {
                            _this.stationCollection.setCurrentDate(moment(date, 'YYYYMMDD'));
                            _this.stationCollection.fetch();
                        });
                    };
                    return tsTimetable;
                }());
                Radiko.Timetable = tsTimetable;
                var StationsModel = Backbone.Model.extend({
                    defaults: {
                        id: "RGK",
                        name: "RAGIKO"
                    }
                });
                var StationsCollection = Backbone.Collection.extend({
                    model: StationsModel,
                    initialize: function () {
                        this.areaId = getAreaId();
                    },
                    url: function () {
                        return "/v3/station/list/" + this.areaId + ".xml";
                    },
                    parse: function (data) {
                        var parsed = [];
                        $.Radiko.exclude_station_list = [];
                        $(data).find('station').each(function () {
                            var stationId = $(this).find('id').text();
                            var stationName = $(this).find('name').text();
                            if (!_.contains($.Radiko.user_station_list, stationId) && +$(this).find('areafree').text() == 0) {
                                $.Radiko.exclude_station_list.push(stationId);
                            }
                            parsed.push({ id: stationId, name: stationName });
                        });
                        return parsed;
                    },
                    fetch: function (options) {
                        options = options || {};
                        options.dataType = "xml";
                        return Backbone.Collection.prototype.fetch.call(this, options);
                    }
                });
                var StationModel = Backbone.Model.extend({
                    defaults: {
                        station_id: '',
                        name: '',
                        progs: []
                    }
                });
                var StationCollection = Backbone.Collection.extend({
                    model: StationModel,
                    initialize: function (models) {
                        this.areaId = getAreaId();
                        this.currentDate = getDate();
                        this.listenTo(models, 'sync', this.onSync);
                    },
                    onSync: function () {
                        this.fetch();
                    },
                    setCurrentDate: function (moment) {
                        this.currentDate = moment;
                    },
                    url: function () {
                        return "/v3/program/date/" + this.currentDate.format('YYYYMMDD') + "/" + this.areaId + ".xml";
                    },
                    fetch: function (options) {
                        return Backbone.Collection.prototype.fetch.call(this, _.extend({
                            dataType: 'xml'
                        }, options));
                    },
                    parse: function (resp) {
                        return _.map($('station', resp), function (station) {
                            var _this = this;
                            var $station = $(station);
                            var now = moment();
                            var stationId = $station.attr('id');
                            return {
                                station_id: stationId,
                                name: $station.find('name').first().text(),
                                progs: _.map($station.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');
                                    var addClass = '';
                                    var listenType = 0;
                                    var programUrl = '/#!/ts/' + stationId + '/' + ft;
                                    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,
                                        tol: tol,
                                        dur: parseInt($prog.attr('dur'), 10),
                                        title: $prog.find('title').first().text(),
                                        pfm: $prog.find('pfm').first().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);
                        var ftTime = sprintf("%02d:%02d", radioHours.ft_hour, ftmt.minute());
                        var toTime = sprintf("%02d:%02d", radioHours.to_hour, tomt.minute());
                        return ftTime + '〜' + toTime;
                    }
                });
                _.extend(StationCollection.prototype, $.Radiko.Mixins.Utility);
                var TimetableListView = Backbone.View.extend({
                    initialize: function () {
                        this.currentDate = null;
                        this.startPosition = null;
                        this.listenTo(this.collection, 'sync', this.onSync);
                    },
                    onSync: function (models) {
                        this.currentDate = this.collection.currentDate;
                        this.render(models);
                    },
                    render: function (models) {
                        _.map($.Radiko.exclude_station_list, function (stationId) {
                            models.remove(models.where({ station_id: stationId }));
                        });
                        var programs = models.toJSON();
                        var modelsJson = models.toJSON();
                        if (programs.length >= 7) {
                            if (this.startPosition === null) {
                                this.startPosition = this.getStartPosition(programs.length);
                            }
                            modelsJson = this.swapProgram(this.startPosition, programs);
                        }
                        this.renderProgramDate();
                        this.renderProgramChannel(modelsJson);
                        this.renderProgramItems(modelsJson);
                        if (models.length < 7) {
                            var areaWidth = this.$el.find('.program-table__outer').width() - this.$el.find('.program-table__hour').width();
                            var singleWidth = ~~(areaWidth / models.length);
                            this.$el.find('.program-table__items .item-outer').width(singleWidth - 1);
                            this.$el.find('.program-table__channel').width(singleWidth - 9);
                            this.$el.find('.program-table__pager').hide();
                        }
                        setScrollInit();
                        var $selectDate = $('.js-select-date');
                        $selectDate.off('click', 'a');
                        $selectDate.on('click', 'a', this.selectDateClickHandler);
                        return this;
                    },
                    renderProgramDate: function () {
                        var _this = this;
                        $('.program-table-header__list').html(JST['timetable/program-table-date']({
                            dateList: _.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
                                };
                            })
                        }));
                    },
                    renderProgramChannel: function (data) {
                        $('.program-table__channel-outer').html(JST['timetable/program-table-channel']({
                            models: data,
                            tableWidth: (data.length * 159 - 1) + 'px'
                        }));
                    },
                    renderProgramItems: function (data) {
                        $('.program-table__items').html(JST['common/program-table-items']({
                            models: data,
                            tableWidth: (data.length * 159 - 1) + 'px'
                        }));
                    },
                    getViewModel: function (models) {
                        var _this = this;
                        var _models = models.toJSON();
                        _models.unshift(_models.pop());
                        return {
                            dateList: _.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
                                };
                            }),
                            models: _models,
                            tableWidth: (_models.length * 159 - 1) + 'px'
                        };
                    },
                    defineUi: function () {
                    },
                    events: {
                        'click .js-prev': 'prevClickHandler',
                        'click .js-next': 'nextClickHandler'
                    },
                    selectDateClickHandler: function (ev) {
                        ev.preventDefault();
                        $.Radiko.EventEmitter.trigger('change:currentDate', ev.currentTarget.hash.substring(1));
                        var $programs = $('.program-table__items');
                        $programs.fadeOut(500);
                        $programs.fadeIn(500);
                    },
                    prevClickHandler: function (ev) {
                        ev.preventDefault();
                        var $scrolls = $('.js-scroll');
                        $scrolls.stop(true, true);
                        $scrolls.each(function (index, elScroll) {
                            var $items = $('.js-scroll-item', elScroll);
                            $items.last().insertBefore($items.first());
                            $scrolls.css('left', -159);
                        }).animate({
                            'left': 0
                        });
                        var nextPosition = this.startPosition - 1;
                        this.startPosition = nextPosition < 0 ? this.collection.length - 1 : nextPosition;
                    },
                    nextClickHandler: function (ev) {
                        ev.preventDefault();
                        var $scrolls = $('.js-scroll');
                        $scrolls.stop(true, true);
                        $scrolls.animate({
                            'left': -159
                        }).promise().done(function () {
                            $scrolls.each(function (index, elScroll) {
                                var $items = $('.js-scroll-item', elScroll);
                                $items.first().insertAfter($items.last());
                                $scrolls.css('left', 0);
                            });
                        });
                        var nextPosition = this.startPosition + 1;
                        this.startPosition = nextPosition >= this.collection.length ? 0 : nextPosition;
                    },
                    getStartPosition: function (programLength) {
                        return Math.floor(Math.random() * programLength);
                    },
                    swapProgram: function (startPosition, programs) {
                        var tmp1 = programs.slice(0, startPosition);
                        var tmp2 = programs.slice(startPosition);
                        return tmp2.concat(tmp1);
                    }
                });
            })($.Radiko || ($.Radiko = {}));
            $('#header').html(JST['common/header']({ logo: '/apps/images/img_logo_blue_01.png' }));
            var areabox = _.template($('#tmpl-colorbox-area-list').html());
            $('#colorbox--area-list').html(areabox());
            $(".btn--share").colorbox({
                width: "80%",
                inline: true,
                speed: 0,
                opacity: 0.5
            });
            $('.colorbox-area-list__list span[data-id=' + getAreaId() + ']').replaceWith(function () {
                return $('<a></a>', {
                    href: '/#!/timetable',
                    html: $(this).html()
                });
            });
            var timetable = new $.Radiko.Timetable();
            $.Radiko.EventEmitter.once('radikotimetable', function () {
                timetable.initialize();
                makeHeader();
                $('input[type="text"]').placeholder();
            });
            if (_.isString($.Radiko.area.id)) {
                $.Radiko.EventEmitter.trigger('radikotimetable');
            }
            if (window.area != undefined) {
                $('span.area').text(window.area);
            }
        });
    })(window, $, Backbone, _, moment);
};
