var app = app || {};

app.TeamDetailView = Backbone.View.extend({
    initialize: function (criteria) {
        var self = this;
        self.criteria = criteria;
        
        $("#menu").mmenu({ position: "right" }, {});
        $("#back").tap(function () {
            window.history.back();
        });
        TabUtils.init(4, 0, 500, self.tabHandler);
        
        app.Services.TeamService.getTeamDetail(function (team) {
            self.model = team;
            self.render();
        }, criteria.teamId);
    },

    tabHandler: function (tabIndex) {
        switch (tabIndex) {
            case 2:
                if (!$("#tab-standings").attr("loaded")) {
                    app.CurrentView.showStandings();
                }
                break;
            case 3:
                if (!$("#tab-alert").attr("loaded")) {
                    app.CurrentView.showAlerts(true);
                }
                break;
                
        }
    },

    render: function () {
        var self = this;
        var notItem = { assetId: this.model.get("id"), assetType: 2, assetName: this.model.get("name") };
        $("#favorite img").attr("src", Settings.isSubscribed(notItem) ? "/img/ic_star_top_selected.png" : "/img/ic_star_top.png");
        $(".favorite-btn").addClass(Settings.isSubscribed(notItem) ? "selected" : "");
        $(".favorite-btn").data("localize", Settings.isSubscribed(notItem) ? "on" : "off");
        $(".favorite-btn").localize("lang", localizationOptions);
        $("#favorite, .favorite-btn").tap(function () {
            app.Services.NotificationService.changeSubscription(function (changeType) {
                self.model.set("isSelected", changeType == "add");
                if (changeType == "add") {
                    $("#favorite img").attr("src", "/img/ic_star_top_selected.png");
                    Settings.addToFavorites(notItem);
                    $(".favorite-btn").addClass("selected");
                    $(".favorite-btn").data("localize", "on");
                    if ($("#tab-alert").attr("loaded")) {
                        $("#tab-alert").attr("loaded", false);
                        self.showAlerts(true);
                    }
                } else {
                    $("#favorite img").attr("src", "/img/ic_star_top.png");
                    Settings.removeFromFavorites(notItem);
                    $(".favorite-btn").removeClass("selected");
                    $(".favorite-btn").data("localize", "off");
                    if ($("#tab-alert").attr("loaded")) {
                        self.showAlerts(false);
                    }
                }
                $(".favorite-btn").localize("lang", localizationOptions);
            }, { assetId: self.model.get("id"), assetType: "2", changeType: Settings.isSubscribed(notItem) ? "delete" : "add" });
        });
        $("#team-header .logo img").attr("src", this.model.get("logo"));
        $("#team-header .team-name").text(this.model.get("name"));
        $("#team-header .season").text(this.model.get("seasonName"));
        var matchHolder = $("#match-list tbody");
        var matchList = this.prepareMatchList(this.model.get("matches"));
        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 });
                matchHolder.append(match.render(true).el);
            } else {
                var league = new app.LeagueHeaderView({ model: item });
                matchHolder.append(league.render(true).el);
            }
        }

        var squadHolder = $("#squad-list");
        var squad = this.model.get("squad");
        for (var i = 0; i < squad.length; i++) {
            var item = squad.at(i);
            squadHolder.append(Handlebars.templates.squad(item.toJSON()));
        }
        
        $("[data-dynamic='true']").localize("lang", localizationOptions);
        $("img").error(function () {
            this.onerror = null;
            this.style.visibility = "hidden";
        });
    },

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

        return matchList;
    },

    showStandings: function () {
        var self = this;
        app.Services.StandingService.getStandings(function (leagues) {
            $("#tab-standings").attr("loaded", true);
            var standingHolder = $("#standing-list");
            for (var i = 0; i < leagues.length; i++) {
                var league = leagues[i];
                var standings = league.get("standings");
                var leagueView = new app.LeagueHeaderView({ model: league});
                standingHolder.append(leagueView.render(true,8).el);
                for (var j = 0; j < standings.length; j++) {
                    var standing = standings.at(j);
                    var standingView = new app.StandingView({ model: standing });
                    standingHolder.append(standingView.render().el);
                }
            }
        }, self.criteria);
    },

    showAlerts: function (isShow) {
        var self = this;
        if (isShow) {
            if (self.model.get("isSelected")) {
                app.Services.NotificationService.getSubscriptionDetails(function (subId, alerts) {
                    $("#tab-alert").attr("loaded", true);
                    self.model.set("subscriptionId", subId);
                    var alertHolder = $("#subscription-detail-list");
                    for (var i = 0; i < alerts.length; i++) {
                        var alert = alerts[i];
                        var alertView = new app.SubscriptionDetailView({ model: alert });
                        alertHolder.append(alertView.render().el);
                    }
                }, { "assetId": self.model.get("id"), "assetType": 2 });
            } else {
                $("#tab-alert").attr("loaded", true);
            }
        } else {
            var alertHolder = $("#subscription-detail-list");
            alertHolder.html("");
        }
    },
    updateAlerts: function (detail) {
        detail.subscriptionId = app.CurrentView.model.get("subscriptionId");
        app.Services.NotificationService.updateSubscriptionDetails(detail);
    }
    
});




