
/**
 * @requires bam.MediaGrid.js
 * @requires MediaURL
 * @requires GamedayAudioLogin.js
 */
var MiLB_TV = (function() {

        var MiLB_TV,         // self
            SETTINGS,    // audio app settings
            playMedia,       // proxy that binds fetchMediaURL() call w/ user's isLogged status
            playerContainer,  // flv player container

            GRID = new bam.services.MediaGrid({ sportCode : "min", fileName : "grid_min" }),
            LOGIN_FAIL_SILENT = false,

            catalogContainer, // catalog container // is this still needed?
            
            audioCatalogContainer,
            //TPL_AUDIO_CATALOG_URL = TPL_DIR + '/audioCatalog.js.tpl',
            TPL_AUDIO_CATALOG,

            nowPlayingLabelContainer,
            //TPL_NOW_PLAYING_URL = TPL_DIR + '/nowPlaying.js.tpl',
            TPL_NOW_PLAYING,

            MEDIA_TOKEN = bam.cookies.get( 'media.token' ),

            DEFAULT_VOLUME = 70,
            
            MEDIA_ON = "MEDIA_ON",
            MEDIA_STAGING = "MEDIA_STAGING",
            MEDIA_ARCHIVE = "MEDIA_ARCHIVE",
            MEDIA_DONE = "MEDIA_DONE",
            
            IS_PLAYING_EVENT = 'isPlaying',
            
            LOGIN_MODULE;

        SETTINGS = {
            catalogContainerID  : 'mediaGrid',
            playerContainerID   : 'flvPlayerContainer',
            event_id            : null,
            playback_scenario   : null,
            teams               : null,
            nowPlaying          : null
        };


        /**
         * Enables Social Links for currently playing item
         */
        function enableSocialLinks(settings) {
                $("#share_tools").show();

                $("#facebook").unbind("click").click(function(calendar_event_id, ymdDate, label) { 
                    return function(){
                        bam.tracking.track({
                            async:{
                                isDynamic    : false, 
                                compName     : "MiLB.tv/Comments", 
                                compActivity : "MiLB.tv Facebook Link Click", 
                                actionGen    : true
                            }
                        });					
                        window.open("http://www.facebook.com/sharer.php?u="+encodeURIComponent(prodCacheServerURLGlobal+"/milb/multimedia/milbtv.jsp?calendar_event_id="+calendar_event_id+"&ymd="+bam.datetime.DateTime(ymdDate).formatDate('yyyyMMdd')+"&affiliateId=facebook_share")+"&t="+encodeURIComponent("I am watching " + label + " on MiLB.TV. Check it out."),"milbtvsharefb","width=626,height=436");
                        return false;
                    };
                }(settings.calendar_event_id, settings.gridDate, settings.label));
			
                $("#twitter").unbind("click").click(function(calendar_event_id, ymdDate, label){ 
                    return function(){
                        bam.tracking.track({
                            async:{
                                isDynamic    : false, 
                                compName     : "MiLB.tv/Comments", 
                                compActivity : "MiLB.tv Twitter Link Click", 
                                actionGen    : true
                            }
                        });					
                        window.open("http://twitter.com/share?text="+encodeURIComponent("I am watching " + label + " on MiLB.TV. Check it out. @minorleagues #milbtv")+"&url="+encodeURIComponent(prodCacheServerURLGlobal+"/milb/multimedia/milbtv.jsp?calendar_event_id="+calendar_event_id+"&ymd="+bam.datetime.DateTime(ymdDate).formatDate('yyyyMMdd')+"&tcid=tw_share"),"milbtvsharetw","width=626,height=436");
                        return false;
                    };
                }(settings.calendar_event_id, settings.gridDate, settings.label));
        }


        /**
         * Displays "You are watching" label
         */
        function displayMediaLabel (settings) {
            $("#video_info").html("You are watching: " + settings.label);
        }

        /**
         * Binds click handlers for Catalog links
         */
        function liveBindMediaLinks() 
        {
            var metadata    = this.value.split('|'),
                contentID   = metadata[0],
                callLetters = metadata[1];

            LOGIN_FAIL_SILENT = false;
            
            MiLB_TV.trigger( 'feedSelected', [ true ] );

            // bind isLoggedIn status with contentID for fetchMediaUrl call
            playMedia = $.eventProxy(function(sessionStatus, isContext) {
                if (isContext) {
                    fetchMediaURL( contentID, sessionStatus.isLoggedIn );
                }
            });

            LOGIN_MODULE
                .bind(LOGIN_MODULE.events.isLoggedIn, playMedia)
                .isLoggedIn(true);

        }
    
        /**
         * Tries to fetch URL for specified audio item. 
         *
         * If user is logged in, the URL is fetched. If the user is not logged in, then require login first
         */
        function fetchMediaURL( contentID, isLoggedIn ) 
        {

            if( isLoggedIn ) {


	        $("#video-blackout-message").remove();

                // TODO: explore whether these handlers should use 'bind' or 'one'; think they should be 'bind'
                MediaURL.one( 'fetch:complete', function( event, url, mediaParams ) {
                        handleFetchComplete( event, url, mediaParams);
                });
                MediaURL.one('fetch:loginRequired', LOGIN_MODULE.display);
                MediaURL.one('fetch:error', handleFetchError );
                MediaURL.one('fetch:blackout', handleBlackout);

                var mediaParams = {
                    event_id          : SETTINGS.event_id,
                    content_id        : contentID,
                    playback_scenario : SETTINGS.playback_scenario
                };

                MediaURL.fetch( mediaParams );
                
            } else {

                LOGIN_MODULE.display();

            }
        }

        /**
         * Handles MediaURL's fetch complete event. Tries to play media, if a URL is returned. 
         * Otherwise, displays upsell messaging
         */
        function handleFetchComplete( event, url, mediaParams)
        {
            var player,
                streamConfigObj;
            
            // got a URL, so attempt playback
            if( !!url ) {
                //console.log( 'received URL', url );

                streamConfigObj = {
                    type             : "video",
                    path             : unescape( url ),
                    userId           : LOGIN_MODULE.ipid,
                    bitrateKbps      : "32",
                    playbackScenario : mediaParams.playback_scenario,
                    content_id       : mediaParams.content_id,
                    //calendarEventId  : GD_SETTINGS.game.gameId + ':' + callLetters + ':' + mediaParams.event_id,
                    //game_pk          : GD_SETTINGS.game_pk,
                    connectionType   : "STREAM"
                };
                
                VideoPlayer.destroy();

                if (mediaParams.source_aspect_ratio === "SD") {
                    VideoPlayer.settings.width = 480;
                    VideoPlayer.settings.height = 360;
                    $("#"+VideoPlayer.settings.containerId).addClass("sd");
                } else {
                    VideoPlayer.settings.width = 640;
                    VideoPlayer.settings.height = 360;
                    $("#"+VideoPlayer.settings.containerId).removeClass("sd");
                }

                player = window.player = VideoPlayer.play( streamConfigObj );

                SETTINGS.nowPlaying = mediaParams.content_id;

                MiLB_TV.trigger( IS_PLAYING_EVENT, [SETTINGS] );

            // no URL means no entitlement, so display upsell
            } else {
                LOGIN_MODULE.displayUpsell();
            }

            LOGIN_MODULE.unbind(LOGIN_MODULE.events.isLoggedIn, playMedia);
            MediaURL.unbind('fetch:loginRequired', LOGIN_MODULE.display);
            MediaURL.unbind('fetch:error', handleFetchError );

        }

        /**
         * Displays blackout messaging
         */
        function handleBlackout() {

            var blackoutMessage = $("<div />", {
                    id : "video-blackout-message",
                    html : "We're sorry. We have determined that you are blacked out of watching the game you selected due to television broadcaster restrictions within this geographic region. An archive copy of the game video will be available on-demand within 24 hours of the game's conclusion."
                });

            blackoutMessage.appendTo("#video_player");
        }

        /**
         * Handles MediaURLs error event
         * TODO: display error in Messenger; should this have it's own messenger? or use GDApp messenger. probably should have unique
         * @param error
         */
        function handleFetchError( event, error ) 
        {
            // console.log( 'error fetching URL. display appropriately ', error );
            var errorMsg = bam.actionMessages.GetMessage( error, 'media' );

            // @TODO: add messenger
            // Messenger( 'messageContainer' ).show( errorMsg, 'error' );
            $("#video_info").addClass("error").html("There was an error loading the video stream for the selected game.");
		$("#share_tools").hide();

            LOGIN_MODULE.unbind( LOGIN_MODULE.events.isLoggedIn, playMedia ); // Media Service returned an error, so don't attempt playback

            //MediaURL.unbind( 'fetch:loginRequired', handleLoginRequired );
            MediaURL.unbind('fetch:loginRequired', LOGIN_MODULE.display);
            MediaURL.unbind( 'fetch:complete', handleFetchComplete );
        }

        MiLB_TV = {
            /**
             * Updates GD Audio App's global settings 
             */
            configure : function( s ) 
            {
                $.extend( SETTINGS, s );
            },

            /**
             * Configures global settings and binds handlers for audio links
             */
            initialize : function( s ) 
            {
                //console.debug( 'MiLB_TV.initialize( ', s, ' )');

                var feed;

                if ( ! LOGIN_MODULE) {
                    LOGIN_MODULE = new MediaLogin(s.sslServer);
                }

                MiLB_TV.configure( s );
                $('#' + SETTINGS.catalogContainerID + ' a.milbtv_link').live( 'click', liveBindMediaLinks );
                
                //TPL_AUDIO_CATALOG = $.template( TPL_AUDIO_CATALOG_URL );
                //TPL_NOW_PLAYING   = $.template( TPL_NOW_PLAYING_URL );
                
                if( ! playerContainer) {
                    playerContainer = $('#' + SETTINGS.playerContainerID);
                }

                GRID
                    .onLoadSuccess($.eventProxy(function(data) {
                        var game, mediaItem, contentID;
                        
                        game = data.find({ calendar_event_id : SETTINGS.calendar_event_id});

                        if (game) {
                            mediaItem = game.getMedia({ playback_scenario : SETTINGS.playback_scenario});


                            if (mediaItem) {

                                // set now playing label data
                                SETTINGS.label = game.away_team_city + " " + game.away_team_name + " @ " + game.home_team_city + " " + game.home_team_name;

                                // find content ID
                                contentID = ($.isArray(mediaItem)) ? mediaItem[0].id : mediaItem.id;

                                // bind isLoggedIn status with contentID for fetchMediaUrl call
                                playMedia = $.eventProxy(function(sessionStatus, isContext) {
                                    if (isContext) {
                                        fetchMediaURL( contentID, sessionStatus.isLoggedIn );
                                    }
                                });

                                LOGIN_MODULE
                                    .bind(LOGIN_MODULE.events.isLoggedIn, playMedia)
                                    .isLoggedIn(true);

                            }
                        }

                    }));


                if (SETTINGS.calendar_event_id) {
                    GRID.load(SETTINGS.gridDate);
                }

                MiLB_TV.bind(IS_PLAYING_EVENT, $.eventProxy(enableSocialLinks));
                MiLB_TV.bind(IS_PLAYING_EVENT, $.eventProxy(displayMediaLabel));

                MiLB_TV.trigger( 'initialize', [ true ] );
            },

            loadStream : function (s) {
                MiLB_TV.configure(s);
                GRID.load(SETTINGS.gridDate);
            }

        };

        return $.bindable( MiLB_TV );
})();


