/**
 * BAM Game ID library converts valid Game IDs into Game objects that allow dot notation 
 * access to relevant information for the game.
 *
 * Example usage:
 * --------------
 *   // load the library
 *   bam.loadSync('/shared/scripts/bam/packed/bam.gameId.js');
 *
 *   // create a Game object
 *   var g    = bam.gameId.game('2008_09_16_nyamlb_bosmlb_1');
 *
 *   // access info from the Game ID
 *   alert(g.awayTeam.team_code);  // alerts 'nya'
 *   alert(g.homeTeam.team_code);  // alerts 'bos'
 *   alert(g.sportCode);           // alerts 'mlb'
 *   alert(g.gameNum);             // alerts '1'
 *
 *   // access file paths / team properties
 *   alert(g.getFilePath());              // alerts '/components/game/mlb/year_2008/month_09/day_16/gid_2008_09_16_nyamlb_bosmlb_1'
 *   alert(g.awayTeam.club);              // alerts 'nyy'
 *   alert(g.homeTeam.name_display_long); // alerts 'The Boston Red Sox'
 *
 * 
 * bam.gameId.game API
 *   .year
 *   .month
 *   .day
 *   .awayTeam       Away Team properties object. Provides dot notation access for all team properties stored in /properties/mlb_properties.xml
 *       .club
 *       .name_display_long
 *       [etc]
 *
 *   .homeTeam       Home Team properties object. Provides dot notation access for all team properties stored in /properties/mlb_properties.xml
 *       .club
 *       .name_display_long
 *       [etc]
 *
 *   .sportCode      Home team sport code
 *   .gameNum        Game number
 *   .gameDate       bam.datetime object of game date
 *   .getFilePath()  Returns path for game datafiles according to Gameday file-naming convention
 *
 * @author   jferrer
 * @requires bam.datetime
 *
 */

({
	gameId : (function( domain ) {
		bam.loadSync( bam.homePath + 'bam.datetime.js' );	

		var teamPropsRequest,
            teamProps,
            tbdProps,

            statusRules = [
                // live
                {
                    id       : "live",
                    label    : "Live",
                    statuses : [
                        'Pre-Game',
                        'Warmup',
                        'Delayed Start',
                        'In Progress',
                        'Delayed'
                    ]
                },

                // preview
                {
                    id       : "preview",
                    label    : "Schedule",
                    statuses : [
                        'Preview',
                        // 'Pre-Game',
                        // 'In Progress',
                        'Resumed' // 'Suspended' // Resume
                    ]
                },
                
                // final
                {
                    id       : "final",
                    label    : "Final",
                    statuses : [
                        'Game Over',
                        'Final',
                        'Completed Early',
                        'Forfeit',
                        'Suspended',
                        'Postponed',
                        'Cancelled'
                    ]
                }
            ],
            
            NLAllStarProps = {
               // id:"36014"
               display_code:"nl",
               club:"nl",
               team_code:"nas",
               // club_id:"2",
               // team_id:"108",
               club_full_name:"National League All-Stars",
               // club_spanish_name:"Los Angels de Los Angeles de Anaheim",
               club_common_name:"National",
               // esp_common_name:"Angels",
               name_display_long:"NL All-Stars",
               name_display_short:"NL All-Stars",
               league:"National" 
            },
            
            ALAllStarProps = {
               // id:"36014",
               display_code:"al",
               club:"al",
               team_code:"aas",
               // club_id:"2",
               // team_id:"108",
               club_full_name:"American League All-Stars",
               // club_spanish_name:"Los Angels de Los Angeles de Anaheim",
               club_common_name:"American",
               // esp_common_name:"Angels",
               name_display_long:"AL All-Stars",
               name_display_short:"AL All-Stars",
               league:"American" 
            };

            ALChampionProps = {
               display_code:"alc",
               club:"alc",
               team_code:"alc",
               club_full_name:"American League Champion",
               // club_spanish_name:"",
               club_common_name:"AL Champion",
               // esp_common_name:"Angels",
               name_display_long:"AL Champion",
               name_display_short:"AL Champion",
               league:"American" 
            };

            NLChampionProps = {
               display_code:"nlc",
               club:"nlc",
               team_code:"nlc",
               club_full_name:"American League Champion",
               // club_spanish_name:"",
               club_common_name:"NL Champion",
               // esp_common_name:"Angels",
               name_display_long:"NL Champion",
               name_display_short:"NL Champion",
               league:"National" 
            };

            function getGameState( gameStatus, resumeDate ) {
                var i,
                    statusRule;

                // if( gameStatus === 'Suspended' && !!resumeDate ) {
                //     resumeDate = bam.datetime.parseYMD( resumeDate.replace( '/', '') );
                //     if( this.gameDate.toYMD() === resumeDate.replace( '/', '' ) ) {

                //     }
                // } else {

                    for( i = 0; i < statusRules.length; i++ ) {
                        statusRule = statusRules[ i ];
                        if( $.inArray( gameStatus, statusRule.statuses ) !== -1 ) {
                            return statusRule;
                        }
                    } 
                // }

                return null;
            }

        // load MLB team properties, if on MLB.com
        if( domain.indexOf( 'mlb.com' ) !== -1 ) { 		
			// check to see if club props have already been loaded before requesting
			// this only applies for mlb and club homepages
			var context = bam.mlbhome || bam.clubhome || {},
				dataStoreExists = (!!context.get && !!context.get("clubprops"));			
			if(dataStoreExists){
				teamProps = context.get("clubprops");				
			} else {
	            teamPropsRequest = {
	                url      : '/scripts/club_properties.jsp',
	                dataType : 'json',
	                async    : false,
	                data     : {
	                    "responseType" : "json"
	                },
	                success  : function( response ) {
	                    teamProps = response;
						if(dataStoreExists) context.set("clubprops", teamProps);	
	                }
	            };	
	            if( domain.indexOf( 'dev-' ) !== -1 ) {
	                teamPropsRequest.cache = false;
	            }	
        	    $.ajax( teamPropsRequest );			
			}
        }

        /**
         * Returns MLB team properties as defined in mlb_properties.xml
         * This only works for MLB.com teams
         *
         * @param  {String} teamCode 
         * @return {Object} team properties
         */
		function getTeamProps( teamCode ) {
			var club, 
			    t,
                prop;

            for( t in teamProps ) {
                if( teamProps.hasOwnProperty( t ) ) {
                    club = teamProps[ t ];

                    // load TBD props
                    if( !tbdProps ) {
                        tbdProps = {};
                        for ( prop in club ) {
                            tbdProps[ prop ] = 'TBD';
                        }
                    }

                    if( club.team_code === teamCode ) {
                        return club;
                    }
                }
            }

            // return team props for teams not in mlb_properties.xml
			if ( teamCode == 'zza' || teamCode == 'zzn' || teamCode == 'taa' || teamCode == 'tab' || teamCode == 'tna' || teamCode == 'tnb' ) {
                return tbdProps;

            } else if( teamCode === "aas" ) {
                return ALAllStarProps;

            } else if( teamCode === "nas" ) {
                return NLAllStarProps;

            } else if( teamCode === "alc" ) {
                return ALChampionProps;

            } else if( teamCode === "nlc" ) {
                return NLChampionProps;
            }
  
			return null;
		}

        function Game( gid ) {
            if( !( this instanceof Game ) ) {
                return new Game( gid );
            }

            this.year        = gid.substring( 0, 4 );
            this.month       = gid.substring( 5, 7 );
            this.day         = gid.substring( 8, 10 );
            this.sportCode   = gid.substring(21,24);
            this.gameNum     = gid.substring(25,26);
            this.gamedayLink = gid.replace(/\//g,"_").replace(/-/g,"_");

            this.awayTeam    = {
                team_code : gid.substring( 11, 14 ),
                sportCode : this.sportCode
            };

            this.homeTeam    = {
                team_code : gid.substring( 18, 21 ),
                sportCode : this.sportCode
            };

            // add team properties
            if( !!teamProps ) {
                $.extend( this.awayTeam, getTeamProps( this.awayTeam.team_code ) );
                $.extend( this.homeTeam, getTeamProps( this.homeTeam.team_code ) );
            }

            // build game id
            this.gameId = this.year+'/'+this.month+'/'+this.day+'/'+this.awayTeam.team_code + this.awayTeam.sportCode+'-'+this.homeTeam.team_code + this.homeTeam.sportCode+'-'+this.gameNum;

            // create gameDate bam.datetime object
            this.gameDate = bam.datetime.DateTime( bam.datetime.parseYMD( this.year + this.month + this.day ) );
            
            $.bindable( this );
        }

        Game.prototype = {
            events : {
                getLinescoreSuccess : "getLinescore:success",
                getLinescoreError : "getLinescore:error"
            },

            /**
             * Returns a Gameday file path based on Game ID
             *
             * @returns {String} Game path
             */
            getFilePath : function() {
                return "/components/game/"+this.sportCode+"/year_"+this.year+"/month_"+this.month+"/day_"+this.day+"/gid_"+this.gamedayLink+"/";
            },

            getLinescore : function() {

                var linescoreRequest = {
                    url      : "/gdcross" + this.getFilePath() + "linescore.json",
                    dataType : "json",

                    success  : $.proxy( function( response ) {
                        this.linescore           = response.data.game;
                        // this.linescore.gamestate = bam.object.proxy( getgamestate, this, this.linescore.status, this.linescore.resume_date );
                        this.linescore.gamestate = bam.object.proxy( getGameState, this, this.linescore.status )();
                        this.trigger(this.events.getLinescoreSuccess, [ this.linescore ] );
                    }, this ),
                    
                    error    : $.proxy( function() {
                        this.trigger(this.events.getLinescoreError);
                    }, this )

                };

                // workaround for weird dev caching thing; probably b/c of the proxy
                if( document.location.href.indexOf( 'dev-' ) !== -1 ) {
                    linescoreRequest.cache = false; 
                }

                $.ajax( linescoreRequest );
            }



        };


		var _self = {
			/**
			 * Returns a Game object with helper members/methods for working with BAM game id's
			 *
			 * @param  {String} gid     Game ID. Accepts '/', '_' and '-' delimiters. 
			 * @return {object} gameObj if valid game id is passed, otherwise returns null
			 */
			game: Game
		};
		return _self;

	})( document.domain )
})

