var app = app || {};

app.CompetitionsView = Backbone.View.extend({

    initialize: function (querystring) {
        var self = this;
        $("#menu").mmenu({ position: "right" }, {});
        if (querystring && querystring.cupId) {
            app.Services.CompetitionService.getLeaguesByCup(function (leagues) {
                self.renderLeagues(leagues, querystring.groupId, querystring.cupName);
            }, querystring.cupId, querystring.groupId);
        }
        else if (querystring && querystring.groupId) {
            app.Services.CompetitionService.getLeaguesAndCupsByGroup(function (leagues) {
                self.renderLeagues(leagues, querystring.groupId, querystring.groupName);
            }, querystring.groupId);
        } else {
            app.Services.CompetitionService.getGroups(function (competitionHolder) {
                var leagues = competitionHolder.leagues;
                var groups = competitionHolder.groups;
                self.renderGroups(leagues, groups);
            }, querystring ? querystring.continentId : 0);
        }
    },
    renderGroups: function (leagues, groups) {

        var leagueHolder = $("#competition-list");
        var groupHolder = $("#group-list");
        for (var i = 0; i < leagues.length; i++) {
            var item = leagues[i];
            var league = new app.LeagueHeaderView({ model: item });
            leagueHolder.append(league.render().el);
        }

        for (var i = 0; i < groups.length; i++) {
            var item = groups[i];
            var league = new app.LeagueHeaderView({ model: item });
            groupHolder.append(league.render().el);
        }
        $("#groups").show();
    },

    renderLeagues: function (leagues, groupId, name) {
        var leagueHolder = $("#league-list");
        for (var i = 0; i < leagues.length; i++) {
            var item = leagues[i];
            var league = new app.LeagueHeaderView({ model: item });
            var el = league.render().el;
            $(el).find(".flag").css("display", "none");
            leagueHolder.append(el);
            
        }
        $("#leagues .sub-header img").attr("src", "/img/football/" + groupId + ".gif");
        $("#leagues .sub-header").append(decodeURIComponent(name));
        $("#leagues").show();
    }
});



