var app = app || {};

app.MatchDetailView = Backbone.View.extend({
    el: "#match",
    eventList: new app.Models.MatchCollection(),
    currentTab: null,
    initialize: function (matchObj) {
        var self = this;
        this.tabs = $("#tabs>div[id^='tab-']");
        TabUtils.init(this.tabs.length, 0, 500, this.tabHandler);
        $("#loading").show();
        $("#menu").mmenu({ position: "right" }, {});
        $("#home-team-sub-tab, #away-team-sub-tab").tap(function () {
            if (!$(this).hasClass("selected")) {
                if (this.id == "home-team-sub-tab") {
                    $("#home-squad-holder").css("display", "");
                    $("#away-squad-holder").css("display", "none");
                    $("#away-team-sub-tab").removeClass("selected");
                } else {
                    $("#away-squad-holder").css("display", "");
                    $("#home-squad-holder").css("display", "none");
                    $("#home-team-sub-tab").removeClass("selected");
                }
                $(this).addClass("selected");
            }
        });
        $("#tab-matchcast img").tap(function () {
            self.showMatchCast();
        });

        app.Services.MatchService.getMatchDetail(function (match) {
            self.model = match;
            self.render();
            self.showSurvey();
        }, function (matchUpdate) {
            if (matchUpdate.get("isUpdateNecessary")) {
                app.Services.MatchService.getMatchDetail(function (match) {
                    self.model = match;
                    self.render();
                    self.showSurvey();
                }, false, matchObj.match, true);
            } else {
                var time = matchUpdate.get("time");
                if (!isNaN(parseFloat(time)) && isFinite(time)) {
                    time = time + "'";
                } else {
                    if (!isNaN(parseFloat(time)) && isFinite(time)) {
                        time = (time + "'");
                    } else {
                        if (matchState == 2) {
                            time = "HT";
                        } else if (matchState == 4) {
                            time = "FT";
                        } else if (matchState == 5 || matchState == 6) {
                            time = "ET";
                        } else if (matchState == 9) {
                            time = "PP";
                        } else if (matchState == 10) {
                            time = "DEC";
                        } else if (matchState == 11) {
                            time = "SUSP";
                        }
                    }
                }
                self.model.set({
                    "score": matchUpdate.get("score"),
                    "time": time
                });
                var template = Handlebars.templates.matchDetail;
                self.$el.find("tbody").html(template(self.model.toJSON()));
                $("[data-dynamic='true']").localize("lang", localizationOptions);
            }
        }, matchObj.match, false);
        
        
    },
    
    events: {
        "tap td.home": "navigateToHome",
        "tap td.away": "navigateToAway"
    },
    
    navigateToHome: function() {
        window.location.href = "/team-detail.html?teamId=" + this.model.get("homeTeamId");
    },

    navigateToAway: function () {
        window.location.href = "/team-detail.html?teamId=" + this.model.get("awayTeamId");
    },

    initTabs: function () {
        if (this.model.getIsFinished()) {
            $("#tab-matchcast img").hide();
        }

        if (this.model.getIsFinished() || this.model.get("isInBlacklist")) {
            $("#tab-alert, #tab-header-alert").remove();
        }

        if (!this.model.get("runningballId") || this.model.get("matchState") == 0) {
            $("#tab-matchcast, #tab-header-matchcast").remove();
        }

        if (!(this.model.get("homeSquad").length || this.model.get("awaySquad").length)) {
            $("#tab-lineups, #tab-header-lineups").remove();
        }

        if (this.model.get("isElimination")) {
            $("#tab-standing, #tab-header-standing").remove();
        }

        this.tabs = $("#tabs>div[id^='tab-']");

        TabUtils.init(this.tabs.length, 0, 500, this.tabHandler);
    },

    tabHandler: function (tabIndex) {
        var tab = app.CurrentView.tabs[tabIndex];
        app.CurrentView.currentTab = tab;
        switch (tab.id) {
            case "tab-form":
                if (!$(tab).attr("loaded")) {
                    app.CurrentView.showForm();
                }
                break;
            case "tab-standing":
                if (!$(tab).attr("loaded")) {
                    app.CurrentView.showStandings();
                }
                break;
            case "tab-alert":
                if (!$(tab).attr("loaded")) {
                    app.CurrentView.showAlerts(true);
                }
                break;
        }
    },

    render: function () {

        this.initTabs();
        var template = Handlebars.templates.matchDetail;
        this.$el.find("tbody").html(template(this.model.toJSON()));
        var self = this;
        var notItem = { assetId: this.model.get("id"), assetType: 1 };
        if (this.model.getIsLiveOrNotStarted() || Settings.isSubscribed(notItem) || !this.model.get("isInBlacklist")) {
            $("#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");
                    $("#favorite img").attr("src", Settings.isSubscribed(notItem) ? "/img/ic_star_top_selected.png" : "/img/ic_star_top.png");
                    if (Settings.isSubscribed(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-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: "1", changeType: Settings.isSubscribed(notItem) ? "delete" : "add" });
            });
            $("#favorite").show();
        } else {
            $("#favorite").hide();
        }


        $("#home-team-sub-tab").text(this.model.get("homeTeam"));
        $("#away-team-sub-tab").text(this.model.get("awayTeam"));

        $("#league").text(this.model.get("leagueName"));
        if (this.model.get("stadium")) {
            $("#stadium").text(this.model.get("stadium"));
        } else {
            $(".stadium-row").hide();
        }

        if (this.model.get("referee")) {
            $("#referee").text(this.model.get("referee"));
        } else {
            $(".referee-row").hide();
        }

        if (this.model.get("matchDate")) {
            $("#date").text(this.model.get("matchDate"));
        } else {
            $(".date-row").hide();
        }

        var managerText = "";
        if (this.model.get("homeManager")) {
            managerText = this.model.get("homeManager");
        } else if (this.model.get("awayManager")) {
            managerText += (" , " + this.model.get("awayManager"));
        }

        if (managerText) {
            $("#managers").text(managerText);
        } else {
            $(".manager-row").hide();
        }


        var events = this.model.get("events");
        var eventsHolder = $("#event-list");
        eventsHolder.html("");
        for (var i = events.length - 1 ; i >= 0; i--) {
            var event = events.at(i);
            var eventView = new app.EventView({ model: event });
            eventsHolder.append(eventView.render().el);
        }

        var homeSquad = this.model.get("homeSquad");
        var squadHolder = $("#home-lineup-list");
        squadHolder.html("");
        for (var i = 0; i < homeSquad.length; i++) {
            var player = homeSquad.at(i);
            var lineupView = new app.LineupView({ model: player });
            squadHolder.append(lineupView.render().el);
        }

        var awaySquad = this.model.get("awaySquad");
        squadHolder = $("#away-lineup-list");
        squadHolder.html("");
        for (var i = 0; i < awaySquad.length; i++) {
            var player = awaySquad.at(i);
            var lineupView = new app.LineupView({ model: player });
            squadHolder.append(lineupView.render().el);
        }

        var homeSubs = this.model.get("homeSubstitutes");
        var subHolder = $("#home-subs-list");
        subHolder.html("");
        for (var i = 0; i < homeSubs.length; i++) {
            var player = homeSubs.at(i);
            var lineupView = new app.LineupView({ model: player });
            subHolder.append(lineupView.render().el);
        }

        var awaySubs = this.model.get("awaySubstitutes");
        subHolder = $("#away-subs-list");
        subHolder.html("");
        for (var i = 0; i < awaySubs.length; i++) {
            var player = awaySubs.at(i);
            var lineupView = new app.LineupView({ model: player });
            subHolder.append(lineupView.render().el);
        }

        var matchStats = this.model.get("stats");
        var matchStatsHolder = $("#match-stats");
        matchStatsHolder.html("");
        for (var i = 0; i < matchStats.length; i++) {
            var stat = matchStats.at(i);
            matchStatsHolder.append(Handlebars.templates.stat(stat.toJSON()));
        }
        $("#loading").hide();
        $("[data-dynamic='true']").localize("lang", localizationOptions);
        return this;
    },

    showMatchCast: function () {
        var self = this;
        app.Services.MatchService.getMatchCastToken(function (token) {
            var width = $(document).width();
            self.model.set("token", token);
            $("#tab-matchcast img").hide();
            $("#tab-matchcast iframe").attr({ height: width * 0.46, "src": "http://visualisation.performgroup.com/animation/index.html?token=" + self.model.get("token") + "&matchId=" + self.model.get("runningballId") + "&width=" + width + "&lang=en" }).show();
            $("#match-cast-overlay").css({ width: width + "px", height: (width * 0.46 + "px"), top: 0 });
            $("#match-cast-overlay").parent().css({ height: (width * 0.46 + "px") });
        }, self.model.get("runningballId"));
    },

    showForm: function () {
        var self = this;
        app.Services.MatchService.getForm(function (collectionHolder) {
            $("#tab-form").attr("loaded", true);
            var homeMatches = collectionHolder.homeMatches;
            var awayMatches = collectionHolder.awayMatches;
            var oldMatches = collectionHolder.oldMatches;
            var homeMatchesHolder = $("#home-form-list tbody");
            for (var i = 0; i < homeMatches.length; i++) {
                var match = homeMatches.at(i);
                var matchView = new app.MatchView({ model: match });
                homeMatchesHolder.append(matchView.render(true).el);
            }

            var awayMatchesHolder = $("#away-form-list tbody");
            for (var i = 0; i < awayMatches.length; i++) {
                var match = awayMatches.at(i);
                var matchView = new app.MatchView({ model: match });
                awayMatchesHolder.append(matchView.render(true).el);
            }

            var oldMatchesHolder = $("#old-form-list tbody");
            for (var i = 0; i < oldMatches.length; i++) {
                var match = oldMatches.at(i);
                var matchView = new app.MatchView({ model: match });
                oldMatchesHolder.append(matchView.render(true).el);
            }

            $("#tab-form>div:eq(0)").text(self.model.get("homeTeam"));
            $("#tab-form>div:eq(1)").text(self.model.get("awayTeam"));
            $("[data-dynamic='true']").localize("lang", localizationOptions);
        }, self.model.get("id"));
    },

    showSurvey: function () {
        var self = this;
        app.Services.MatchService.getMatchSurvey(function (survey) {
            self.model.set("survey", survey);
            var surveyHolder = $("#option-list");
            var surveyView = new app.SurveyView({ model: survey });
            surveyHolder.append(surveyView.render().el);
            if (!surveyHolder.find(".disabled").length) {
                surveyHolder.find("img").tap(function () {
                    var optionId = $(this).attr("optionId");
                    app.Services.MatchService.vote(function (voteResult) {
                        Settings.setVotes(self.model.get("id"), optionId);
                        self.model.get("survey").set("options", voteResult.get("options"));
                        self.model.get("survey").set("isVotable", false);
                    }, self.model.get("id"), optionId);
                });
            }
            $("[data-dynamic='true']").localize("lang", localizationOptions);
        }, self.model.get("id"));
    },

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

    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": 1 });
            } 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);
    }
});




