
/*
* 
* Drawer
*
* @Authors: Caleb Olin | Joe Kanakaraj
* @Created: January 2010
*
* This code does 2 things:
* 
* 1) extends the passed namespace (bam.mlbhome || bam.clubhome || bam) with 2 new properties:
* 
*   drawer: 
*     expands (boolean)
*	  debug (boolean)
*     init, expand, collapse, delayedExpand, delayedCollapse, setCookie (functions)
*
*   drawerplayer:
*     playerObj (object)
*     create, destroy (functions)
* 
* 2) gets the config json:
*
*  on club sites it loads the mlb data file first and checks if its settings should apply to all clubs
*  if apply-to-clubs is "N" it then loads the club-specific drawer
*
*  if the drawer is active, populate a local cache var, cleverly called "cache." Then it inits the drawer.
*  if the drawer is inactive, deletes the drawer and drawerplayer objects from the passed namespace
* 
*  @TODO: move drawerplayer into drawer obj
*  @TODO:figure out which of the live stream end markers is working
*
*/

(function(context){

	var x=0, 
		fields,
		thisField, 
		key,
		dc, 
		mvc,
		appears,
		expires,
		cache={},
		itemTags={}, 
		exceptions=[],
		$container, 
		_club = bam.url.Location( window.location ).getParam( 'c_id' ) || "mlb",
		tpl = "/scripts/homepage/y2011/drawer.tpl",	
		config = "mlb",	
		applies = isException = true,	
		datafile = bam.url.Location( window.location ).getParam( "drawer" ) || "/gen/hb/drawer/mlb.json",		
		drawerAd = "#drawer_ad",
		adFrame = bam.url.Location( window.location ).getParam( "adFrame" ) || "/drawer_ad_300x150.html",		
		adFrameHTML = "<iframe src='"+adFrame+"?c_id="+_club+"' frameborder='0' width='300' height='250' scrolling='no' allowtransparency='true'></iframe>",
		$doc = $(document),
		custom = gotcookie = false,
		videoExists = false,
		compName = (_club=="mlb" || _club=="MLB")?"MLB Drawer":"Club Drawer",
		DRAWER_STATE = 0,
		DRAWER_ID = "#drawer_container",
		OPEN_BUTTON = DRAWER_ID + " .open_close a.open",
		CLOSE_BUTTON = DRAWER_ID + " .open_close a.close",
		COLLAPSED = "collapsed",
		PRESIZING = "presizing",
		COLLAPSED_HEIGHT = 30,
		EXPANDED_HEIGHT = 225,
		DELAY = 12000,
		SPEED = 1200,
		COOKIE = "homeObj.drawer.disable",
		ON_OPEN = ON_CLOSE = function(){},			
		_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;
		},
		_log = function(msg){		
			if (context.drawer.debug && typeof console !== "undefined" && !!console.log && !!console.dir) {
				if (typeof msg === "string") console.log("Drawer: "+msg);
				else if (typeof msg === "object") console.dir(msg);
				else console.log(msg);			
			}		
		},
		// takes a string like "yyyy-mm-ddThh:mm:ss-0500" and returns a number like yyyymmddhhmm
		_formatDate = function(datestr){
			datestr = datestr.replace(/-/g,"").replace(/T/g,"").replace(/:/g,"").substr(0,12); 
			return datestr*1;		
		},
		_sysdate = (bam.env.host.isProd) ? window.sysdate : bam.url.Location(window.location).getParam('ymd') || window.sysdate;

	//Cached jQuery selector getter
	function $get(selector) {
		return $get.cache[selector] = $get.cache[selector]||$(selector);
	}
	$get.cache = {};			
		
	$.extend(context, 
		{drawer: (function() {		
			
		mvc = {
			model: {},
			view: {				
				animateOpen: function(cb) {										
					$get(DRAWER_ID).removeClass(COLLAPSED).animate({
						height: EXPANDED_HEIGHT						
					}, SPEED, "linear", function(){
						if($.isFunction(cb)) {
							cb();
						}
					});					
				},				
				animateClose: function(cb) {					
					$get(DRAWER_ID).animate({
						height: COLLAPSED_HEIGHT						
					}, SPEED, "linear", function(){ 
						$(this).addClass(COLLAPSED);
						if($.isFunction(cb)) {
							cb();
						}
					});
				},
				createPlayer: function(cb) {	
					if(!videoExists) {
						_log("No video item exists. Aborting player creation.");
						return;
					}
					_log("createPlayer");						
					var content_id = $.ensureArray(cache["video-list"].listValue.item)[0]["@id"];						
					context.drawerplayer.create({
						container	: "drawervideo",
						compname	: "Drawer Player",		
						thumb		: (cache.image) ? cache.image.$ : "",
						content_id	: content_id
					});					
					if($.isFunction(cb)) {
						cb();	
					}					
				},
				destroyPlayer: function(cb) {
					context.drawerplayer.destroy();
					if($.isFunction(cb)) {
						cb();	
					}
				},
				customOpen: function(cb) {
					_log("customOpen TESTING");
					
					//bam.hrderby.create();
					//context.hrderby.create();
					if($.isFunction(cb)) {
						cb();	
					}
				},
				customClose: function(cb) {
					_log("customClose");
					
					
					//bam.hrderby.destroy();
					//context.hrderby.destroy();
					if($.isFunction(cb)) {
						cb();	
					}
				}	
			},
			
			// expose this property to public interface
			controller: {		
				debug: _setDebugging("drawer"),	
				expands: true, 				
				load: function(props){
					_log("load");
					cache={}, x=0;
					$.ajax({
    					url: datafile,
    					dataType: 'json',
						timeout: 5000,
    					success: function(json) {  
			  				fields = json.item.field;
							// loop through fields and add them to local hash for faster retrieval	
    						for (; x<fields.length; x++){								
								thisField = fields[x];	
								key = thisField["@key"];					
								cache[key] = thisField; 			
    						}
							
							
							
							
							custom = (cache["custom-content-active"] && cache["custom-content-active"].$ === "Y");		
												
							videoExists = !!$.deep(cache, "video-list.listValue.item");						
							
							_log("videoExists: "+videoExists);							
							
                            // store contentID of current clip in model object
                          	mvc.model.drawerplayer = { 
								content_id : (custom || !videoExists) ? false : $.ensureArray(cache["video-list"].listValue.item)[0]["@id"] || false
							};
							

							// loop through itemTags and add them to local hash for faster retrieval	
							fields = json.item.itemTag;
							for (x=0; x<fields.length; x++){								
								thisField = fields[x];									
								if(thisField["@type"] !== "team_file_code") continue;								
								key = thisField["@value"];					
								exceptions[key] = true; 
    						}

							for (x=0; x<fields.length; x++){								
								thisField = fields[x];	
								key = thisField["@type"];					
								itemTags[key] = thisField;
    						}
							_log("exceptions");
							_log(itemTags);
							// determine whether the current data file applies
							isException = !!exceptions[_club];							
							applies = (cache["apply-to-all-clubs"].$ === "Y");
							applies = ((applies && !isException) || (!applies && isException));
							

							var customHeightExists = typeof itemTags["custom_height"] !== "undefined";
							_log("expand: " + _club === "mlb" && customHeightExists);
							if ( _club === "mlb" && customHeightExists) {
								EXPANDED_HEIGHT = itemTags["custom_height"]["@value"];
							}
							
							// @TODO: just use json.item["@name"] as the value for compname instead of duplicating the string
							if (json.item["@name"] === "2011 MLB Draft Drawer") {
								compName = "Draft Drawer";
							} else if (json.item["@name"] === "2011 Homerun Derby Test Drawer" || json.item["@name"] === "2011 Homerun Derby Drawer") {
								compName = "HR Derby Drawer";
							} else if (json.item["@name"] === "Twitter Drawer") {
								compName = "Twitter Drawer";
							} else if (json.item["@name"] ==="MLB Wall"){
								compName = "Wall Drawer";
							} else if (json.item["@name"] ==="MLB Must C"){
								compName = "Must C Drawer";
							} else if (json.item["@name"] ==="MLB Inside the Game"){
								compName = "Inside the Game Drawer";
							}							

							//custom = (cache["custom-content-active"].$ === "Y");
							//_log("custom:", custom)			
							if(config === "mlb" && _club !=="mlb" && !applies) {
								// load the club config file
								_log("loading club config");
								config = "club";
								datafile = "/gen/hb/drawer/" + _club + ".json";
								context.drawer.load();					
							} else if(cache.active.$ === "Y") {	
								// check appears / expires
								appears = (!!cache.appears) ? _formatDate(cache.appears.$) : 0;
								expires = (!!cache.expires) ? _formatDate(cache.expires.$) : 300000000000;	
								_sysdate = _sysdate*1;	
								if(_sysdate < appears || _sysdate >= expires) return;		
								// write the drawer HTML			
								_log("activating drawer");	
								$container.html($.template(tpl,cache));
								
								context.drawer.init({
    	 							expands: (cache.expands.$ === "Y"),
    	 							customcontent:custom,
									COLLAPSED_HEIGHT:COLLAPSED_HEIGHT,
									EXPANDED_HEIGHT:EXPANDED_HEIGHT
								});	
									
							} else {
								// delete the drawer objects								
								_log("removing drawer");
								$container.remove();
								delete context.drawer;
								delete context.drawerplayer;			
							}
							
						},
						error: function (err) { _log("Error getting JSON object: " + err.status);}
					});	
				
				},
				init: function(props) {		
				
					_log(props);								
					// don't show the drawer for iPad
					if(bam.env.client.isIPad) {
						// Test to add drawer to iPad
						$container.remove();
						return;	
					}						
					EXPANDED_HEIGHT = props.EXPANDED_HEIGHT || EXPANDED_HEIGHT;						
					COLLAPSED_HEIGHT = props.COLLAPSED_HEIGHT || COLLAPSED_HEIGHT;					

					var gotcookie = mvc.controller.getCookie(mvc.model.drawerplayer.content_id);
					_log("gotcookie="+gotcookie);
					_log("mvc.model.drawerplayer.content_id=" + mvc.model.drawerplayer.content_id);

					if(!props.customcontent) {
						ON_OPEN = mvc.view.createPlayer;
						ON_CLOSE = mvc.view.destroyPlayer;
					}else{
						ON_OPEN = mvc.view.customOpen;
						ON_CLOSE = mvc.view.customClose;
					}					
					// write the ad in an iframe (stupid document.write!)
					$(drawerAd).html(adFrameHTML);			
					if(!!props.expands && !gotcookie) {												
						mvc.controller.expands = true;

                        mvc.controller.setCookie(mvc.model.drawerplayer.content_id);

						mvc.controller.delayedExpand();		
						_log("tracking auto open");					
						bam.tracking.track({
							async:{
								isDynamic:true,
								compName:compName,
								compActivity: compName + ': Auto Open',
								actionGen:false
							}
						}, $(this)[0]);						
					} else{
						mvc.controller.expands = false;
						mvc.controller.collapse();	
					}							
				},
				expand: function(cb) {
					mvc.view.animateOpen(
						function(){ 
							ON_OPEN(cb); 
						} 
					);
					DRAWER_STATE = 1;
				},
				collapse: function(cb) {
					mvc.view.animateClose(
						function(){ ON_CLOSE(cb); } 					  
					);
					DRAWER_STATE = 0;
				},
				delayedExpand: function() {					
					setTimeout(mvc.controller.expand, DELAY);	
				},
				delayedCollapse: function() {
					setTimeout(mvc.controller.collapse, DELAY);
				},

                /**
                 * Interprets the drawer disable cookie value (previously played contentID) and returns
                 * a flag indicating whether the drawer should be disabled.
                 *
                 * @param {String} currContentID [optional] contentID of current drawer clip
                 * @return {Boolean}
                 */
                getCookie: function(currContentID) {
                    var lastContentID = bam.cookies.get(COOKIE);

                    currContentID = (typeof currContentID !== "undefined") ? currContentID : false;

                    return (lastContentID === currContentID) || (typeof lastContentID === "boolean" && lastContentID); // disable if two content IDs match or lastContentID == true
                },

				setCookie: function(contentID) {
					var expireDate=new Date();

                    contentID = contentID || true;

					expireDate.setHours(expireDate.getHours()+2);					
					bam.cookies.set({
						name: COOKIE, 
						value: contentID, 
						expires: expireDate,
						domain: "mlb.com"
					});
				}
			}
		};
		
		
		
		
		
		//Events
		$doc.selector = OPEN_BUTTON;
		$doc.live("click", function(e) {
			if(!e.button) {				
				mvc.controller.expand();
			}
			bam.tracking.track({
				async:{
					isDynamic:true,
					compName:compName,
					compActivity:compName + ': Open Click',
					actionGen:true
				}
			}, $(this)[0]);		
		});
		
		$doc.selector = CLOSE_BUTTON;
		$doc.live("click", function(e) {
			if(!e.button) {
				mvc.controller.collapse();
			}
			bam.tracking.track({
				async:{
					isDynamic:true,
					compName:compName,
					compActivity:compName + ': Close Click',
					actionGen:true
				}
			}, $(this)[0]);		
		});		
		
		//if(!custom){
		//Hack for HR Derby to force custom to be false
		if(!custom && false){
			$doc.selector = DRAWER_ID + " .inner";
			$doc.live("click", function(e) {		
				if(DRAWER_STATE===0) {
					bam.tracking.track({
						async:{
							isDynamic:false,
							compName:compName,
							compActivity:compName + ': Collapsed Content Click',
							actionGen:true
						}
					}, $(this)[0]);		
				}else{
					bam.tracking.track({
						async:{
							isDynamic:false,
							compName:compName,
							compActivity:compName + ': Content Click',
							actionGen:true
						}
					}, $(this)[0]);	
				}
			});
		}
		return mvc.controller;
	})()},	
	
	
	/**
	* 
	*
	* video player
	*
	*
	*/
	
	
	{drawerplayer: (function() {
		
		var _homeObjStr = (!!bam.mlbhome) ? "bam.mlbhome" : (!!bam.clubhome) ? "bam.clubhome" : "bam", 
		
		ps, curClipData, hasinitted = false, playerWidth=320, playerHeight=180, 
	
		_settings = {},
		
		_playbackScenarios = ["FLASH_300K_320X180", "FLASH_600K_400X224", "FLASH_500K_400X224", "FLASH_1200K_640X360", "FLASH_300K_256X144"],
	
		_trackPlaylistBegin = function(){			
			bam.tracking.track({ 
				async_media:{
					mediaID        : _settings.content_id + "|MLB_FLASH_128K_PROGDNLD",
					playerType     : "Flash",
					playerContext  : _settings.compname,
					contextVersion : "2.0",
					streamType     : "Progressive Download",
					bitRate        : "128K",
					actionGen	   : true
				}
			});		
		},						
	
		_self = {		
			playerObj: null,				
			destroy: function(){
				_log("destroy drawerplayer");				
				$("#"+_settings.container).empty();
				$("#drawer_unmute").hide();
				_self.playerObj=null;
			},				
			create: function(props){		
				_log("creating drawerplayer.");								
				$.extend(_settings,props);				
				// access media data file	
				curClipData = bam.media.getMetaData(_settings.content_id);					
				if (curClipData && typeof curClipData.urls!=="undefined"){
					_log("Populated curClipData. Going through URLs");	
					_settings.duration = bam.media.getDurationInSeconds(curClipData.duration); 		
					// @TODO: loop through _playbackScenarios and compare with curClipData, instead of the other way around
					$.each(curClipData.urls, function(i, url){ 					
						ps = url.getAttribute("playback_scenario");							
						if(~$.inArray(ps, _playbackScenarios) && !!url.firstChild) {
							_settings.path=url.firstChild.nodeValue;		
							return false;
						}								
					});
				}else {
					_log("Meta data is not available or bad. Returning false.");
					return;
				}				
				
				
				/*
				if(ps==="FLASH_300K_256X144") {
					playerHeight = 144;
					playerWidth = 256;
				}
				*/
				
				// for testing/preview: 
				playerWidth = bam.url.Location( window.location ).getParam( "playerWidth" ) || playerWidth;
				playerHeight = bam.url.Location( window.location ).getParam( "playerHeight" ) || playerHeight;
				// end test
				
				
				
				 
				$(DRAWER_ID).addClass("drawer_"+playerWidth+"x"+playerHeight);
				
				_self.playerObj = new bam.FlvPlayer({
					skin           : "mlb_mini_2010",
					hideControls   : false,
					self           : _homeObjStr + ".drawerplayer.playerObj",
					elemId         : "bamdrawerplayer",
					height         : playerHeight,  
					width          : playerWidth,
					containerId    : _settings.container,
					siteSection		: "mlb/homepage/index/drawer",
					volume		   : 0,
					debugMode      : context.drawer.debug,
					autoRewind	   : true,
					autoHideSkin	:  true,
					onCollapse     : function(){
						_log("end marker received. closing drawer.");								
						context.drawer.collapse();							
					},	
					onPlayerLoaded : function(){						
						_log("Player loaded. content_id="+_settings.content_id + ", path=" + _settings.path + ", scenario=" + ps );														
						_self.playerObj.startPlaylist([{
							type       : 'video',
							path       : _settings.path,
							content_id : _settings.content_id,
							duration   : _settings.duration												
						}]);							
					},					
					contentStarted : function(){
						_log("contentStarted.");	
						// "Unmute mask"
						if(!hasinitted){
							$("#drawer_unmute").show().click(function(){
								context.drawerplayer.playerObj.execute('changeVolume', 60);	
								$(this).fadeOut();	
								bam.tracking.track({
									async:{
										isDynamic:true,
										compName:compName,
										compActivity: compName + ': Unmute Click',
										actionGen:true
									}
								});	
							});
							hasinitted=true;
						}
						// turn off club.com CVC if it's running
						if(!!context.playerObj) {
							context.playerObj.execute("pausePlayback");	
						}
					},    					
					onPlaylistBegin : function(){ 	
						_log("Playlist begin.");						
						_trackPlaylistBegin(); 
					},					
					onPlaylistComplete: function() {
						
						if(!_settings.thumb){
							_settings.thumb = "/images/drawer/defaultposter_" + playerWidth + "x" + playerHeight + ".jpg";						
						}
						_self.playerObj.setBeginPoster('/flash/video/y2009/beginposter_v3.swf?stagew='+playerWidth+'&stageh='+playerHeight+'&thumb='+escape(_settings.thumb));	
						bam.tracking.track({videoComplete:{playerContext:_settings.compname}});
					}
				});				
			}		
		};
		
		return _self;
		
		})() }
		// end video player	
	);
	
	
	
	
	$(function() {	
	
		$container = $get(DRAWER_ID);
		_club = _club.toLowerCase();
		context.drawer.load();		
		
	});
	
//})(bam.mlbhome || bam.clubhome || bam);	
})(window.bam);	

