var app = app || {};

app.MatchesView = Backbone.View.extend({
    el: "#matches tbody",
    dates: [],
    matchList: new app.Models.MatchCollection(),
    allMatchList: new app.Models.MatchCollection(),
    initialize: function () {
        var self = this;

        $("#menu").mmenu({ position: "right" }, {});
        $("#live-filter").tap(function () {
            if ($(this).hasClass("on")) {
                $(this).removeClass("on");
                $(this).find("img").attr("src", "/img/ic_live.png");
                self.render();
            } else {
                $(this).addClass("on");
                $(this).find("img").attr("src", "/img/ic_live_on.png");
                self.showLive();
            }
        });
        var dates = DateUtils.getDateRangeForMatch(new Date());
        var datePicker = $("#date-picker");
        var template = Handlebars.templates.date;
        datePicker.css({ width: (dates.length * 80) + 15 + "px" });
        for (var i = 0; i < dates.length; i++) {
            var dateTable = $(template(dates[i]));
            if (dates[i].requestString == "") {
                dateTable.addClass("selected");
                dateTable.attr("id", "today");
            }
            $.data(dateTable[0], "reqStr", dates[i].requestString);
            datePicker.append(dateTable);
        }
        $("#date-picker-holder").scrollLeft((dates.length * 80 - $("#date-picker-holder").width()) / 2);
        datePicker.find("table").tap(function () {
            if (!$(this).hasClass("selected")) {
                var dateStr = $.data(this, "reqStr");
                $("#date-picker-holder .selected").removeClass("selected");
                $(this).addClass("selected");
                if (dateStr) {
                    app.Services.MatchService.getMatches(function (matches) {
                        self.allMatchList = matches;
                        self.render(self.allMatchList, false);
                    }, 0, dateStr);
                } else {
                    self.collection = self.matchList;
                    self.render();
                }
            }
        });

        app.Services.MatchService.getMatches(function (matches) {
            self.matchList = matches;
            self.collection = matches;
            self.render();
            $("#live-indicator").text(self.collection.getLive().length + self.collection.getFavorite(true).length);
            if (Settings.shouldSendReadCount()) {
                app.Services.NotificationService.sendNotificationCount();
            }
            if (Settings.shouldRefreshSubscriptions()) {
                app.Services.NotificationService.getSubscribedNotifications(null, true);
            }
        });
        
    },
    render: function (col, isLive) {
        this.$el.html("");
        var matchList, favoriteList;
        if (isLive) {
            matchList = this.prepareMatchList(this.collection.getLive());
            favoriteList = this.prepareMatchList(this.collection.getFavorite(true), true);
        } else {
            matchList = col ? this.prepareMatchList(col.getNotFavorite()) : this.prepareMatchList(this.collection.getSummary());
            favoriteList = this.prepareMatchList((col || this.collection).getFavorite(), true);
        }

        for (var i = 0; i < favoriteList.length; i++) {
            var item = favoriteList.at(i);
            if (item instanceof app.Models.MatchModel) {
                var match = new app.MatchView({ model: item });
                this.$el.append(match.render().el);
            } else {
                var league = new app.LeagueHeaderView({ model: item });
                this.$el.append(league.render(true).el);
            }
        }

        for (var i = 0; i < matchList.length; i++) {
            var item = matchList.at(i);
            if (item instanceof app.Models.MatchModel) {
                var match = new app.MatchView({ model: item });
                this.$el.append(match.render().el);
            } else {
                var league = new app.LeagueHeaderView({ model: item });
                this.$el.append(league.render(true).el);
            }
        }
        
        $("[data-dynamic='true']").localize("lang", localizationOptions);
        return this;
    },

    prepareMatchList: function (filteredCol, isFavorite) {
        var matchList = new app.Models.MatchCollection();
        if (!isFavorite) {
            var currentLeagueId = 0;
            var favoriteLeagues = new app.Models.MatchCollection();
            for (var i = 0; i < filteredCol.length; i++) {
                var match = filteredCol.at(i);
                var leagueNotItem = { assetId: match.get("leagueId"), assetType: 4 };
                var cupNotItem = { assetId: match.get("cupId"), assetType: 0 };
                if (Settings.isFavorite(leagueNotItem)
                    || Settings.isFavorite(cupNotItem)) {
                    favoriteLeagues.add(match);
                } else {
                    if (match.get("leagueId") != currentLeagueId) {
                        var leagueHeader = new app.Models.LeagueModel({
                            id: match.get("leagueId"),
                            cupId: match.get("cupId"),
                            name: match.get("groupName") + " " + match.get("leagueName"),
                            groupId: match.get("groupId"),
                            isElimination: match.get("isElimination")
                        });
                        matchList.add(leagueHeader);
                        currentLeagueId = match.get("leagueId");
                    }

                    matchList.add(match);
                }
            }
            currentLeagueId = 0;
            var favoriteIndex = 0;
            for (var i = 0; i < favoriteLeagues.length; i++) {
                var match = favoriteLeagues.at(i);
                if (match.get("leagueId") != currentLeagueId) {
                    var leagueHeader = new app.Models.LeagueModel({
                        id: match.get("leagueId"),
                        cupId: match.get("cupId"),
                        name: match.get("groupName") + " " + match.get("leagueName"),
                        groupId: match.get("groupId"),
                        isElimination: match.get("isElimination")
                    });
                    matchList.add(leagueHeader, { at: favoriteIndex });
                    favoriteIndex++;
                    currentLeagueId = match.get("leagueId");
                }
                matchList.add(match, { at: favoriteIndex });
                favoriteIndex++;
            }
        }

        else {
            for (var i = 0; i < filteredCol.length; i++) {
                var match = filteredCol.at(i);
                match.set("isFavorite", true);
                var leagueHeader = new app.Models.LeagueModel({
                    id: 0,
                    name: "My Scores",
                    groupId: 0,
                    isFavorite: true
                });
                matchList.add(leagueHeader);
                matchList.add(match);
            }
        }
        return matchList;
    },

    showLive: function () {
        this.render(null, true);
    }
});



