/*
     @TODO: 
     load/unload css based on mode?
     separate templates for each mode?
     allow editorial override for game to display?
     phase 2: create a writeLineups and allow lineups to update on autorefresh
     phase 2: bind callbacks & config for each mode to a trigger that fires when the mode changes
     phase 2: in writeLive, only replace html for elements that have changed. can use a transition(fade) to alert that there was a change
*/
bam.gameticker = (function($, context) {

    var _container = "#gameticker",
        _teamID, // populated @ init
        _flip = bam.getFlipDisplayDate(club),
        _end = bam.datetime.DateTime(_flip),
        _startDate = "'" + bam.datetime.formatDate(_flip, "yyyy/MM/dd") + "'",
        _endDate = "'" + bam.datetime.formatDate(_end.incrementWeeks(2), "yyyy/MM/dd") + "'",
        _season = bam.datetime.formatDate(_flip, "yyyy"),
        _config = {
            isAllStar: false,
            isPostSeason: true,
			game_type: 'W'
        },
        _tpl = "/scripts/homepage/y2011/gameticker" + ((_config.isAllStar) ? "_asg" : (_config.isPostSeason) ? "_ps" : "") + ".tpl",
        _errors = {},
        _heartbeat = null,
        _gameHeartbeat = null,
        _refreshInterval = 30000,
        $doc = $(document),
        _tixCarouselIndex = 0,
        _highlightsCarouselIndex = 0,
        _previousMode, _autorefresh = true,
        _ismock = (~document.location.search.indexOf("ismock")) ? true : false,
        _club = bam.url.Location(window.location).getParam('c_id'),
        _CLUB = _club.toUpperCase(),

        _log = function(msg) {
            if (bam.gameticker.debug && typeof console !== "undefined" && !! console.log && !! console.dir) {
                if (typeof msg === "string") console.log("Gameticker: " + msg);
                else if (typeof msg === "object") console.dir(msg);
                else console.log(msg);
            }
        },


        _testBroadcast = function(msg) {
            var $bcast = $(".tkr_broadcast");
            //_log(msg + " : bcast html = " + $bcast.html());
        },


        _setDebugging = function(component) {
            var d = bam.url.Location(window.location).getParam("debug");
            if (!bam.env.host.isProd && !! d && (d === "true" || ~d.indexOf(component))) return true;
            else
            return false;
        },


        _formatDate = function() {
            var start, ampm, day, dt = _config.game.team_game_time,
                zone = _config.game.team_time_zone,
                month = _config.game.month,
                month_full = _config.game.month_full;
            if (~dt.indexOf("3:33")) return "TBD";
            start = dt.split(" ")[1].split(":");
            start = start[0] + ":" + start[1];
            ampm = dt.split(" ")[2];
            day = dt.split("/")[1];
            //Request from ARI to display their zone as MST, not MT
            //zone = zone.charAt(0) + zone.charAt(zone.length-1);		
            _log(month);
			_log(month_full)
			month_full = (month === "8") ? "Aug." : (month === "9") ? "Sept." : (month === "10") ? "Oct." : (month === "11") ? "Nov." : month_full;
            return month_full + " " + day + ", " + start + " " + ampm + " " + zone;

        },


        _createCarousel = function( /* "highlights" or empty */ ) {
          
            var isTix = (arguments[0] === "highlights") ? false : true,
                selector = (isTix) ? " .tkr_carousel_tix " : " .tkr_carousel_highlights ",
                $container = $("#gameticker" + selector + ".tkr_carousel_container"),
                btnNext = "#gameticker" + selector + ".tkr_arrow_right",
                btnPrev = "#gameticker" + selector + ".tkr_arrow_left";
            $container.find(".tkr_carousel").jCarouselLite = null;
            $(btnNext).unbind("click");
            $(btnPrev).unbind("click");
            $container.find(".tkr_carousel").jCarouselLite({
                btnNext: btnNext,
                btnPrev: btnPrev,
                //visible: (_config.mode==="matchup" || !isTix) ? 2 : 1,
                visible: (_config.isPostSeason && _config.mode === "matchup") ? 3 : (_config.mode === "matchup" || !isTix) ? 2 : 1,
                easing: "easeOutCirc",
                speed: 600,
                circular: false,
                //scroll: (_config.mode === "matchup") ? 3 : 1,
                scroll: 1,
                start: (isTix) ? _tixCarouselIndex : _highlightsCarouselIndex,
                afterEnd: function(elem) {
                    // preserve carousel index on refresh		
                    if (isTix) {
                        _tixCarouselIndex = elem.parent().children().index(elem);
                    } else {
                        _highlightsCarouselIndex = elem.parent().children().index(elem);
                    }
                },
                afterInit: function() {
                    $(btnNext + ", " + btnPrev).click("click", function() {
                        var $container = $("#gameticker"),
                            tracking = $(this).attr("data-tracking"),
                            mode = ($container.hasClass("tkr_matchup")) ? "Preview" : ($container.hasClass("tkr_lineup")) ? "Pre-Game" : "Live",
                            component = _CLUB + " " + mode + " Matchup",
                            //remove lineup toaster
                            $isHome = $(".nextHomeGame"),
                            $tickets = $(".tkr_carousel ul li a.bam-button-tickets");
                        if ($isHome) {
                            $isHome.remove();
                            $tickets.fadeIn();
                        }


                        bam.tracking.track({
                            async: {
                                isDynamic: false,
                                compName: component,
                                compActivity: component + ": " + tracking + " Click",
                                actionGen: true
                            }
                        });
                    });
                }
            });
        },


        _writeLive = function() {
            var $new = $.template(_tpl, _config),
                //var $new = _getNewHTML(),			
                gameHTML = $new.find(".tkr_game").html(),
                buttonsHTML = $new.find(".tkr_3").html();
            $(_container).find(".tkr_game")
            //.hide()
            .html(gameHTML)
            //.fadeIn()
            .end().find(".tkr_3").html(buttonsHTML).end().find(".tkr_player img").unbind("error").error(function() {
                $(this).attr("src", "/images/players/silhouettes/37x37/anon.png").unbind("error");
            });



        },



/*
    we call write tix in 2 places:
    
    - in the context.bind function at the bottom. it fires when tixprosomos has loaded in bam.clubhome
    
    - in the "mode switch" part of the _write function. this is done so the tix promos call doesnt have to wait
    
    */


        _writeTix = function() {
            _log("_writeTix");
            var i = 0,
                t, curGameLink = "/ticketing/singlegame.jsp?c_id=" + _club,
                $new = $.template(_tpl, _config).find(".tkr_carousel_tix"),
                newHTML = $new.html();
 				/* assign tlink to tickets button for current game. */
            for (; i < _config.tixpromos.length; i++) {
                t = _config.tixpromos[i];
                if (t.game_id === _config.linescore.data.game.id && t.ticket_link && t.ticket_link.tlink) {
                    curGameLink = t.ticket_link.tlink;
                    break;
                }
            }
            $(_container).find(".tkr_carousel_tix").html(newHTML).end().find(".tkr_tix_current").attr("href", curGameLink);
            if ($new.find(".tkr_carousel")[0]) _createCarousel();
			_log("******newHTML*****");
			_log(newHTML);
			_log("******newHTML*****");
        },


        _writeBroadcast = function() {
			_log(_config.broadcast);
            var $new = $.template(_tpl, _config).find(".tkr_broadcast"),
                newHTML = $new.html();
            _log("_writeBroadcast: newHTML=" + newHTML);
            $(_container).find(".tkr_broadcast").html(newHTML);
			_log("newHTML");
			_log(newHTML);
        },


        _load = function(props) {
            return $.ajax({
                url: props.url,
                type: "get",
                dataType: "json",
                timeout: 5000,
                data: props.params || {},
                error: function(xhr) {

/*
                // self destruct after 2 successive	failed load attempts
                if(_errors[props.key]){
                    _log("Error loading " + props.key + ". Self-destructing in 3..2..1...");
                    _log(xhr);
                    _destroy();				
                } else {
                    _errors[props.key] = xhr;
                    _load(props); // @TODO: not sure this will work because it needs to return its promise to the calling function
                }
                */


                    _log("Error loading " + props.key);
                    _log("Disabling auto-refresh");
                    _config[props.key] = {};
                    clearInterval(_heartbeat);

                },
                success: function(r) {
                    _config[props.key] = r;
                    delete _errors[props.key];
                }
            });
        },

        _getLineupsURL = function() {
            var out = "/gen/lineups/",
                gid;
            if (_config.game) {
                gid = _config.game.game_id;
                out += gid.substr(0, 10);
                out += ".json";
            }
            if (~document.location.search.indexOf("debug")) out = "/test/data/nyybos_lineups_debug.json";
            if (~document.location.search.indexOf("debug2")) out = "/test/data/nyybos_lineups_debug2.json";
            return out;
        },

        _loadPostSeasonSked = function() {
            var srs_num = (club === "nyy" || club === "det") ? 1 : (club === "tex" || club === "tb") ? 2 : (club === "phi" || club === "stl") ? 3 : 4;
            if(_config.game_type === "L"){
				srs_num = (club === "det" || club === "tex")? 1 : 2;
			} else if (_config.game_type === "W"){
				srs_num = 1;
			}
			return _load({
                key: "ps",
                //url: (_ismock) ? "/test/data/ps_sked2.json" : _getLineupsURL()		
                //url: (_ismock) ? "/scripts/homepage/y2011/lineups.json" : _getLineupsURL()			
                //url : "/lookup/json/named.schedule_team_complete.bam?start_date=%272010%2F09%2F01%27&end_date=%272011%2F11%2F30%27&team_id="+_teamID+"&season=2010&game_type=%27"+_config.game_type+"%27"
                url: "/lookup/json/named.schedule_series.bam?season=2011&sport_code=%27mlb%27&game_type=%27" + _config.game_type + "%27&ser_nbr=" + srs_num

            });
        },

        _loadLineups = function() {
            return _load({
                key: "lineups",
                url: (_ismock) ? "/test/data/mock/lineups.json" : _getLineupsURL()
                //url: (_ismock) ? "/scripts/homepage/y2011/lineups.json" : _getLineupsURL()			
            });
        },

        _loadBroadcast = function() {
            return _load({
                key: "broadcast",
                url: "/lookup/json/named.mlb_broadcast_info.bam",
                params: {
                    game_pk: _config.game.game_pk,
                    season: _season,
                    sort_by: 'game_time_et_asc'
                }
            }).done(function() {
				var dfd = new jQuery.Deferred();
				var loadAndSort = function(){
					_config.broadcast = bam.util.getQueryResults(_config.broadcast, "mlb_broadcast_info");
	                _config.broadcast.sort(function(a, b) {
						return (a.sort_order - b.sort_order);
						
	                });
					dfd.resolve();
					return dfd.promise()
				}
				$.when(loadAndSort()).done(function(){
					_writeBroadcast();
				})
            });
        },


        _getLinescoreURL = function() {
            var out = "",
                base = "/gdcross/components/game/",
                gid, month, year, day, sportcode, gameday;
            if (_config.game) {
                gid = _config.game.game_id;
                year = gid.substring(0, 4);
                month = gid.substring(5, 7);
                day = gid.substring(8, 10);
                sportcode = gid.substring(21, 24);
                gameday = gid.replace(/\//g, "_").replace(/-/g, "_");

				out = base + sportcode + "/year_" + year + "/month_" + month + "/day_" + day + "/gid_" + gameday + "/linescore.json";


                

            }
            if (_ismock && _config.isAllStar) {
                out = "/test/data/mock/linescore_asg.json";
            } else if (_ismock && _config.isPostSeason) {
                out = "/test/data/linescore_ps2.json";
            } else if (_ismock) {
                out = "/test/data/linescore.json";
            }
            return out;
        },

        _loadLinescore = function() {
            return _load({
                key: "linescore",
                url: (_ismock) ? "/test/data/linescore_ps2.json" : _getLinescoreURL()	
                //url: (_ismock) ? "/scripts/homepage/y2011/linescore.json" : _getLinescoreURL()	
                //url: _getLinescoreURL()
            });
        },


        _getHighlightsURL = function() {
            var out = "",
                base = "/gdcross/components/game/",
                gid, year, sportcode;
            if (_config.game) {
                gid = _config.game.game_id;
                year = gid.substring(0, 4);
                sportcode = gid.substring(21, 24);
                out = (bam.env.host.isQA || bam.env.host.isDev) ? "/test/data/light.json" : base + sportcode + "/year_" + year + "/media/" + _config.game.game_pk + "_light.json";
            }
            return out;
        },


        // @ TODO: does this need the return?
        _loadHighlights = function() {
            return _load({
                key: "highlights",
                url: (_ismock) ? "/scripts/homepage/y2011/rth.json" : _getHighlightsURL()
            }).done(function() {
                var tempobj = _config.highlights.highlights;
                _config.highlights = tempobj;
            }).complete(_writeHighlights);
        },


        _writeHighlights = function() {
            var $new = $.template(_tpl, _config).find(".tkr_2"),
                newHTML = $new.html();
            $(_container).find(".tkr_2").html(newHTML).find(".tkr_ad").show();
            if ($new.find("li").length) _createCarousel("highlights");
        },


        _isResumedGame = function(game) {
            return ( !! _config.linescore.data.game.resume_date);
        },



        _setGame = function() {
            // @VERIFY: that this works correctly for all these scenarios. 
            // if selected game is final, search for next game and check its id
            // can use double_header_sw in sked lkup
            var status, gamesArr = bam.util.getQueryResults(_config.schedule, "schedule_team_complete"),
                i = 0;
            if (gamesArr.length) {
                // sets the game to i and increments i; will fail when gamesArr[i] is undefined
                for (i = 0, n = gamesArr.length; i < n; i++) {
                    _log(gamesArr[i]);
                    _config.game = gamesArr[i];
                    status = _config.game.game_status;
                    // skip to the next game if status is PPD or SUSP
                    if ((status !== "Postponed" && status !== "Cancelled" && status !== "Suspended" && status !== "Final") || _config.game.resumed_from || _config.game.double_header_sw === "N") {
 						break;
                    }
                }
                if (!_config.game) {
                    _destroy();
                    return false;
                }
                _config.game.formattedDate = _formatDate();

                delete _config.schedule;
                return true;
            } else {
                _destroy();
                return false;
            }
        }


        _destroy = function() {
            context.unbind();
            $(_container).remove();
            clearInterval(_heartbeat)
            delete bam.gameticker;
        },


        _storeLineups = function() {
            var i = 0,
                lineupsArr = (_config.lineups) ? $.ensureArray(_config.lineups.list) : [],
                arrLen = lineupsArr.length,
                arrItem;
            _log(lineupsArr);
            for (; i < arrLen; i++) {
                arrItem = lineupsArr[i];
                if (arrItem.game_pk === _config.game.game_pk && arrItem.players && !! arrItem.length) {
                    if (arrItem.team_id === _config.game.team_id) _config.lineups.team = arrItem.players;
                    else if (arrItem.team_id === _config.game.opponent_id) _config.lineups.opponent = arrItem.players;
                }
            }
            if (_config.lineups && _config.lineups.list) delete _config.lineups.list;
        },


        _gameHasBegun = function() {
            var status = _config.linescore.data.game.status;
            return !(status === "Preview" || status === "Pre-Game" || (status === "Suspended" && _isResumedGame()));
        },


        _setMode = function() {
            _storeLineups();
            if (_config.linescore && _config.lineups) {
                // if status is PPD or SUSP go to maytchup mode and show status			
                if (_config.linescore.data.game.status === "Postponed" || _config.linescore.data.game.status === "Suspended") {
                    _config.mode = "matchup";
                    delete _config.lineups;
                    return;
                }
                if (_gameHasBegun()) {
                    _config.mode = "live";
                    delete _config.lineups;
                } else if (_config.lineups.team || _config.lineups.opponent) {
                    _config.mode = "lineup";
                } else {
                    _config.mode = "matchup";
                    delete _config.lineups;
                }
            }
        },

        _getNewHTML = function() {
			
			var out = $.template(_tpl, _config).contents().find(".tkr_home_probable, .tkr_away_probable, .tkr_player").find("img").unbind("error").error(function() {
                var newImg = "/images/players/silhouettes/37x37/anon.png";
                if (_config.mode === "matchup") newImg = "/images/players/silhouettes/68x68/anon.png";
                $(this).attr('src', newImg).fadeIn().unbind("error");
            }).end().end();
			
            return out.parent().html();
        },

        // centers player names beneath their mugshot in matchup mode
        _fixPlayerAlignment = function() {
            if (_config.mode !== "matchup") return;
            var
            $mug = $(".tkr_mugshot"),
                $name, nameWidth, mugshotWidth = $mug.first().find("img").width(),
                space;
            $mug.each(function(idx, elem) {
                $name = $(elem).next();
                nameWidth = $name.width();
                if (nameWidth < mugshotWidth) {
                    _log("Fixing player name alignment");
                    space = (mugshotWidth - nameWidth) / 2;
                    $name.css("margin", "0 " + space + "px")
                }
            });
        },

        _postLoad = function() {
            if (_config.mode === "live") {
                _writeLive();
                _loadHighlights();
            } else if (!_config.broadcast) {
                _loadBroadcast();
            }
            _fixPlayerAlignment();
        },


        _write = function() {
            if (!_config.mode) return;
            var htmlToInsert, $kids, counter;
            if (!_previousMode) {
                _log("FIRST FULL WRITE");
                htmlToInsert = _getNewHTML();			
                
              //  _log(htmlToInsert.html());

                $(_container).removeClass("tkr_matchup tkr_lineup tkr_live").addClass("tkr_" + _config.mode).addClass(_config.isAllStar && "tkr_allstar").addClass(_config.isPostSeason && "tkr_ps").animate({
                    height: (_config.mode === "matchup") ? "90px" : "115px"
                }, 700, "linear", function() {                    
					_log("animation complete");
                    $(this).html(htmlToInsert);
                    _log("animation complete 2");
                    _postLoad();
                });
            } else if (_config.mode !== _previousMode) {
                _log("MODE SWITCH");
                htmlToInsert = _getNewHTML();
                $kids = $(_container).children();
                counter = $kids.length;
                $kids.fadeOut(400, function() {
                    counter--;
                    if (!counter) {
                        _log("fade out 1");
                        $(_container).removeClass("tkr_matchup tkr_lineup tkr_live").addClass("tkr_" + _config.mode).animate({
                            height: (_config.mode === "matchup") ? "90px" : "115px"
                        }, 1000, "linear", function() {
                            $(this).html(htmlToInsert).children().fadeIn();
                            _writeTix();
                            _postLoad();
                        });
                    }
                });

            } else if (_config.mode === _previousMode) {
                _log("Refreshing");
                _postLoad();
            }
            _previousMode = _config.mode;
        },


        _update = function() {
            _testBroadcast("_update");
            _log("_updating");
            
			if (!_config.mode || _config.mode !== "live") {
                _loadLineups().complete(function() {
                    _setMode();
                    _write();
                });
            }
			
			$.when(_loadLinescore(), _loadPostSeasonSked()).done(function(){
				_setMode();
                _write();
			}).fail(_destroy);

			/*
			if (!_config.mode || _config.mode !== "live") {
                _loadLineups().complete(function() {
                    _setMode();
                    _write();
                });
            }
			
			
            _loadLinescore().done(function() {
                _setMode();
                _write();
            }).fail(_destroy);

            //create ps object if in PS mode
            if (_config.isPostSeason) {
                _loadPostSeasonSked().complete(function() {
                    var $bcast = $(".tkr_broadcast");
                    _log("_loadPostSeasonSked. bcast html: " + $bcast.html());
                    _write();
                    var $bcast2 = $(".tkr_broadcast");
                    _log("_loadPostSeasonSked. bcast2 html: " + $bcast2.html());
                });
            }
			*/
        },


        _RUN = function() {
            var params = {
                start_date: _startDate,
                end_date: _endDate,
                team_id: _teamID,
                season: _season
            };
            _load({
                key: "schedule",
                //url: (_ismock)? "/test/data/test_sked.json" : "/lookup/json/named.schedule_team_complete.bam",	
                url: "/lookup/json/named.schedule_team_complete.bam",
                params: params
            }).done(function() {
                if (_setGame()) _update();
            });
        };


    //tracking	
    $doc.selector = "#gameticker *[data-tracking]";
    $doc.live("click", function(e) {
        var $target = $(e.target).closest("*[data-tracking]"),
            ///make sure we have the right hook
            $container = $("#gameticker"),
            tracking = $target.attr("data-tracking"),
            mode = ($container.hasClass("tkr_matchup")) ? "Preview" : ($container.hasClass("tkr_lineup")) ? "Pre-Game" : "Live",
            component = _CLUB + " " + mode + " Matchup";
        bam.tracking.track({
            async: {
                isDynamic: false,
                compName: component,
                compActivity: component + ": " + tracking + " Click",
                actionGen: true
            }
        });
    });

    /* Events */
    $doc.selector = "#gameticker.tkr_lineup .tkr_toggle_left";
    $doc.live("click", function(e) {
        var $lineups = $(e.target).closest(".tkr_3").find("div.tkr_lineup_list");
        $lineups.last().hide();
        $("#gameticker .tkr_toggle_right").removeClass("tkr_toggle_on");
        $("#gameticker .tkr_toggle_left").addClass("tkr_toggle_on");
        $lineups.first().fadeIn();
    });

    $doc.selector = "#gameticker.tkr_lineup .tkr_toggle_right";
    $doc.live("click", function(e) {
        var $lineups = $(e.target).closest(".tkr_3").find("div.tkr_lineup_list");
        $lineups.first().hide();
        $("#gameticker .tkr_toggle_right").addClass("tkr_toggle_on");
        $("#gameticker .tkr_toggle_left").removeClass("tkr_toggle_on");
        $lineups.last().fadeIn();
    });





/*
    $doc.selector = "#gameticker .tkr_carousel_tix .tkr_carousel li:not('.tkr_carousel_last') a";
    $doc.live("click", function(e) {	
        var $target = $(e.target),
            thelink = $target.attr("href"),
            loc = ($target.hasClass("tkr_tlink_home")) ? "home" : "away";							
        window.openTIXXWindow(thelink,loc,["matchup", "C1"]);	
   	 	return false;
    });	
    */

    $doc.selector = "#gameticker .bam-button-tickets";
    $doc.live("click", function(e) {
        var $target = $(e.target).closest("a.bam-button-tickets"),
            thelink = $target.attr("href"),
            loc = ($target.hasClass("tkr_tlink_home")) ? "home" : "away";
        if (~thelink.indexOf("singlegame")) return true;
        window.openTIXXWindow(thelink, loc, ["matchup", "C1"]);
        return false;
    });

    $doc.selector = "#gameticker .nextHomeGame";
    $doc.live("click", function(e) {
        var $target = $(e.target).closest("a"),
            thelink = $target.attr("href"),
            loc = "home";
        if (~thelink.indexOf("singlegame")) return true;
        window.openTIXXWindow(thelink, loc, ["matchup", "C1"]);
        return false;
    });


    $doc.selector = "#gameticker.tkr_live .tkr_1 .tkr_game table.tkr_gd_enabled";
    $doc.live("click", function(e) {
        var gameday = $.deep(_config, "linescore.data.game.gameday_link");
        if ( !! gameday) launchGameday({
            gid: gameday,
            mode: 'gameday',
            c_id: _club
        });
    });

    context.bind("dataLoaded", function(event, key) {

        _testBroadcast("dataLoaded");
        // fires when tix/promo data has been set in context (bam.clubhome)		
        // if gameticker is used in another environment this will need to be replaced with an ajax call		
        if (key === "tixpromos") {

            _config.tixpromos = context.get("tixpromos");
			
			$.available("#gameticker .tkr_carousel_tix", true, function() {
                _writeTix();
            });

            // hack for ASG start time		
        } else if (key === "clubprops" && _config.isAllStar) {
            var
            props = context.get("clubprops")[_club],
                startTime = "8:00 PM ET",
                timezone = props.timezone,
                newHTML = "2011 All-Star Game<br />July 12, ",
                elemStr = "#gameticker.tkr_matchup.tkr_allstar .tkr_1 .tkr_hdr, #gameticker.tkr_lineup.tkr_allstar .tkr_1 .tkr_hdr";
            if (timezone === "CT") {
                startTime = "7:00 PM CT";
            } else if (timezone === "MT") {
                startTime = "6:00 PM MT";
            } else if (timezone === "MST") {
                startTime = "5:00 PM MST";
            } else if (timezone === "PT") {
                startTime = "5:00 PM PT";
            }
            newHTML += startTime;
            $.available(elemStr, true, function() {
                $(this).html(newHTML).show();
            });
        }
    });

    return {
        debug: _setDebugging("gameticker"),
        init: function(props) {
            _log("initializing");
            _teamID = (_config.isAllStar) ? 160 : props.teamID;
            _RUN();
            if (_autorefresh) _heartbeat = setInterval(_update, _refreshInterval);
            _log(_config);
        },
        stop: function() {
            clearInterval(_heartbeat);
        },
        setGame: function(gameid) {
            // update _config.game to only have game id
            // set config.game here and bypass _RUN
            // call _update directly
            // or maybe just do this in the init
        },
        getMode: function() {
            return _config.mode;
        },
        getConfig: function() {
            return _config;
        },
        getDescription: function() {
            var out = $.deep(_config, "linescore.data.game.status");

            return $.deep(_config, "linescore.data.game.status");
        },
        getStatus: function() {
            var out = $.deep(_config, "linescore.data.game.status");
            //return (_isResumedGame()) ? 
            return $.deep(_config, "linescore.data.game.status");
        },
        getStartDate: function(pattern) {
            var out = _startDate.replace(/\'/g, "");
            if (pattern) {
                out = out.replace(/\//g, "");
                out = bam.datetime.parseYMD(out).formatDate(pattern);
            }
            return out;
        },
        getGroupedStatus: function() {
            var st = $.deep(_config, "linescore.data.game.status");
            if (!st) return null;
            if (st === "Warmup" || st === "Delayed Start" || st === "In Progress" || st === "Delayed") {
                return "Live";
            } else if (st === "Preview" || st === "Pre-Game") {
                return "Preview";
            } else {
                return "Final";
            }
        }
    };

})(jQuery, bam.clubhome || {});
