


// load dependent libraries
bam.loadSync(bam.homePath+"bam.cookies.js");


bam.clubhome = (function($){

	var _log=function(msg){
		if (_self.debug && typeof console!=="undefined"){		
			if(typeof msg === "string")	{console.log("bam.clubhome: "+msg)}
			else {console.log(msg);}
		}
	},		
	
	_club = bam.url.Location( window.location ).getParam( 'c_id' ),
	_CLUB = _club.toUpperCase(),
	_properties = {},
	_isinit = true,


	

	/**
	@
	@
	@
	@ VIDEO CORNER
	@
	@
	@
	**/	
	
	_videocorner = {
	
		init: function(props){
			this.handleautoplay(props.compName);
			this.createPlayer(props);			
			$("#vc_caption").html(props.caption);			
		},
		
		autoplay: null,
		
		disableautoplay: function(){
			var expireDate=new Date();
			expireDate.setHours(expireDate.getHours()+24);	
			bam.cookies.set({
				name: "clubhome.autoplay.disable", 
				value: true, 
				expires: expireDate,
				domain: "mlb.com"
			});		
			_log("disableautoplay: expires = " + expireDate);
		},
		
		handleautoplay: function(compName){				
			if(!!bam.cookies.get("clubhome.autoplay.disable")) {
				this.autoplay = false;
				$("#vc_autoplay").text("Habilitar video");
			} else {
				this.autoplay = true;
				$("#vc_autoplay").text("Inhabilitar video");
			}			
			var that=this, $doc = $(document); 
			$doc.selector = "#vc_autoplay";			
			$doc.live("click", function(e) {				
				if (!!that.autoplay){
					that.disableautoplay();				
					$("#vc_autoplay").text("Habilitar video");
				} else {
					bam.cookies.remove("clubhome.autoplay.disable"); 
					$("#vc_autoplay").text("Inhabilitar video");	
				}		
				bam.tracking.track({async:{isDynamic:false, compName:compName, compActivity:"Disable Auto-play Click", actionGen:true}});
        	});			
		},		
	
		createPlayer: function(props) {		
			var ap = this.autoplay;		
			bam.clubhome.playerObj = new bam.FlvPlayer({
				skin           : "/flash/video/v2/skins/mlb_teamHPmini.swf",
				hideControls   : false,
				self           : "bam.clubhome.playerObj",
				elemId         : "ClubHomeFlashPlayer",
				height         : 173,
				width          : 256,
				containerId    : "vc_flash",
				defaultVolume  : 35,
				debugMode      : false,
				autoRewind	   : true,
				pageComponent  : "video_corner",				
				onPlayerLoaded : function(){											
					var pObj = bam.clubhome.playerObj;						
					var clip = {type:"video", videoPath:props.file};										
					var clipProps = [{type:"video", videoPath:props.file, content_id:props.id, duration:props.duration}]; 										
					if(bam.FlvPlayer.prerollPlatform==="dc") {
						var head=(Date.parse(new Date())/1000).toString();
						var tail=((Math.round((Math.random() + 1) * 10000)).toString()).slice(1,5);	
						var prerollUrl = "http://ad.doubleclick.net/pfadx/" + props.clubname.toLowerCase().replace(" ","") + ".mlb/homepage;"+dc_keyVal+"pos=1;sz=256x144;tile=1;ord="+head+tail;	
						clipProps = [{type:"dartPreroll", prerollPath:prerollUrl},clip];					
					}					
					if(!!ap){ 			
						pObj.startPlaylist(clipProps);
					}else{					
						pObj.setBeginPoster('/shared/flash/video/beginposter_v3a.swf?stagew=256&stageh=166&thumb='+escape(props.thumb));						
						pObj.setPlaylist(clipProps);							
					}								
				},			
				onPlaylistBegin : function(){ 					
					bam.tracking.track({ 
						async_media:{
							mediaID        : props.id + "|MLB_FLASH_300K_PROGDNLD",
							playerType     : "Flash",
							playerContext  : props.compname,
							contextVersion : "2.0",
							streamType     : "Progressive Download",
							bitRate        : "300K",
							actionGen	   : (!!ap)?false:true
						}
					});
				},
				onPlaylistComplete: function() {
					bam.tracking.track({videoComplete:{playerContext:props.compname}});
				}
			});		
		}	
	},
	
	
	
	/**
	@
	@
	@
	@ VIDEO CAROUSEL
	@
	@
	@
	**/	
	_initVideoCarousel= function(){	
		var videoCarousel = new FlashObject("/flash/mediawall/y2009/thumb_carousel.swf", "carousel_flash_obj", "256", "116", "9", "#ffffff");	
		videoCarousel.addParam("wmode", "transparent");
		videoCarousel.addParam("scale", "noScale");	
   		videoCarousel.addVariable("width", 256);
		videoCarousel.addVariable("height", 116);
		videoCarousel.addVariable("club", _club);
		videoCarousel.addVariable("tracking_call", "bam.clubhome.trackVideoCarouselClicks");	
		videoCarousel.addVariable("esPath", "/gen/es/" + _club + "/components/multimedia/videos.xml");		
		videoCarousel.addVariable("clickThru", "/es/video/play.jsp"); 
		videoCarousel.addVariable("useKicker", "true");	
		videoCarousel.write("video_carousel_flash");	
	},

	
	
	/**
	@
	@
	@
	@ LOAD TICKET AND PROMO DATA
	@
	@
	@
	**/
	_loadtixpromos = function(cb){
		var props = _self.get("clubprops")[_club],	
			daystart = 11,
			begin = bam.datetime.parseYMDHM(sysdate,daystart),				
			end = new Date(begin);				
		bam.datetime.DateTime(end).incrementMonth(2);	
		begin = bam.datetime.toYMD(begin);
		end = bam.datetime.toYMD(end);
		$.ajax({
			url			: "/ticketing-client/json/GameTicketPromotion.tiksrv",		
			type		: "get",
			dataType    : "json",
			timeout		: 5000,						
			error		: function(xhr) {
				_log("Error in _loadtixpromos: " + xhr.status + " " + xhr.statusText); 				
			},						
			data		: { 
				team_id: props.team_id, 
				sport_id: 1,
				sub_category: "spanish",
				begin_date: begin, 
				end_date: end
			},		
			success: 	function(response) {									
				var game_arr = bam.util.ensureArray(response.events.game);		
				bam.clubhome.set("tixpromos",game_arr);
				if($.isFunction(cb)) { cb(); }
			}	
		});				
	},
	
	
	/**
	@
	@
	@
	@ 3 DAY SCHEDULE
	@
	@
	@
	**/
	_writeschedule = function() {		
	
		var props = bam.clubhome.get("clubprops"),
			$next = $("#m_nogame .m_next"),
			nextText = $next.text(),
			d, s;
		// convert next game	
		if($next.length>0 && !!nextText){
   	 		d = new Date(nextText),
			s = bam.datetime.formatDate(d,"EEE, d/M", true, true);		
			$next.html("Pr&oacute;ximo Partido: "+s).show();
		}
		
		// convert venue time
		var $venuetime = $("#m_nogame .m_venue div");
		var timezone = props[_club].timezone; 
		var t = $venuetime.text();		
		if(~t.indexOf("3:33")) {
			$venuetime.text("Time: TBD").parent().show();
		}else{
			var ampm = t.substr(t.length-2);
			t = t.substr(t.indexOf(" ")+1);
			t = t.substr(0,t.lastIndexOf(":"));
			$venuetime.text(t+" "+ampm + " " + timezone).parent().show();
		}
		
		// format sked dates
		$("#m_schedule li").each(function(n){
			var days=["DOM","LUN","MAR","MIE","JUE","VIE","SAB"];			
			var gid = $(this).attr("data-gid"); // Ex: 2010/04/27/lanmlb-nynmlb-1
			var nd = new Date(gid.substr(0,10));				
			var theDay = days[nd.getDay()].toUpperCase();	
			$(this).find(".m_sked_date").text(theDay + ", " + (nd.getMonth()+1) + "/" + nd.getDate());		
		}).show();	
		
		// default opponent icons
		$("img.m_sked_icon, img.m_logo").attr("onerror","this.src='/mlb/images/video/ibn/home_tbd.gif';this.onerror=null;");
	
		var writeTix = function(game_arr) {
			// loop through games
			// if game_id matches any of the data-gid attributes write promo/tix values
			for(i=0;i<game_arr.length;i++){
				var game=game_arr[i];					
				if(!!game.ticket_link || !!game.promotion){						
					var gid = game.game_id;								
					var $target = $("#m_schedule li[data-gid='"+gid+"']").find(".m_sked_tix");
					var $ticketicon = $("<img src='/mlb/images/icon_ticket.gif'>");								
					if(!!game.ticket_link && $target.length>0) {													
						$target.data("tlink",game.ticket_link.tlink)			
						.click(function(){
							var loc = ($(this).closest("li").hasClass("m_sked_home")) ? "home" : "away";
							var thelink = $(this).data('tlink');
							openTIXXWindow(thelink,loc,["next3games", "B1"]);								
						}).append($ticketicon).show();	
					}							
				}					
			}
		};	
	
		var tp = bam.clubhome.get("tixpromos");
		writeTix(tp);
	},
	
	/**
	@
	@
	@
	@ ROOT LEVEL OBJECT
	@ everything in the _self object is exposed to the public interface
	@
	@
	@
	**/	
	_self = {
		debug: true,
		
		playerObj: null,
		
		init: function(){			
			_log("initializing");
			setTimeout(function(){document.location.reload(true);},1800000); // 30 minute refresh	
			_self.loadprops();					
			_loadtixpromos(_writeschedule);
			_initVideoCarousel();				
			// bam.clubhome.videosettings is created in the video corner component
			if(!!bam.clubhome.videosettings)_videocorner.init(bam.clubhome.videosettings); 
			
		},
		
		
		// setter/getter
		set: function(key,value){
			if(key && typeof(value)!=="undefined") {
				_properties[key]=value;
			}
		},
		
		get: function(key) {		
			if(key==="clubprops" && !_properties["clubprops"]) {
				_self.loadprops();
			}		
			return (key && key in _properties)?_properties[key]:null;
		},
		
		loadprops: function(cb){
			$.ajax({
				async: false,
  				url: "/scripts/club_properties.jsp",
  				dataType: 'json',
				timeout: 5000,
  				data: { responseType: "json" },
  				success: function(json){
					_self.set("clubprops",json);	
					if($.isFunction(cb)) { cb(); }
				},
				error: function(xhr) {_log("Error accessing club properties: " + xhr.status + " " + xhr.statusText);}	
			});
		},
		
		/**
		* setGameMode
		* toggles the matchup container display (current game or next game)
		* @args: true/false
		* @public
		*/
		setGameMode: function(){   
			var $container = $("#matchup_container"),
				game = "#m_gameon",
				nogame = "#m_nogame",
				showGame = (arguments[0] === undefined) ? true : !!arguments[0];		
			if(showGame){				
				$container.find(nogame).hide().end().find(game).fadeIn();
			}else{
				$container.find(game).hide().end().find(nogame).fadeIn();
			}			
		},
		
		trackVideoCarouselClicks: function(clickedArea){
			// Ex arg: NYY MORE VIDEOS: 3993637 
			bam.tracking.track({
				async:{
					isDynamic: false,
					compName: _CLUB + " Centro de Video",
					compActivity: "Video Corner Video Link Click",
					actionGen:true
				}
			}, $(this)[0]);
		},	
		
		/**
		* 
		* WRITE MATCHUP
		*
		* this function gets called from the mediawall. It's the "linescorecallback"
		* 
		**/
		
		writematchup: function(c){			
 
			var	$m = $("#m_gameon"), isatbat, thelink;			
				
			$.extend(c,{
				gid			:	bam.mediawall.game.getCurrentGame(),
				$stub1		:	$m.find(".m_stub:first"),
				$stub2		:	$m.find(".m_stub:last"),
				logopath	:	"/images/logos/36x36/",
				mugshotpath	:	"http://gdx.mlb.com/images/gameday/mugshots/mlb/"
			});				
				
			_log("writematchup. displaying data object below:");
			_log(c);
				
			// add class to container for gamestate-specific styling
			$m.removeClass("preview live final").addClass(c.gamestate);	
			
			// team names
			$m.find(".m_away").html(c.away_team_name);
			$m.find(".m_home").html(c.home_team_name);		
					
			// venue
			$m.find(".m_venue").html(c.venue);		
					
			// logos
			$m.find(".m_away_logo").attr("src",c.logopath+c.away_file_code+".png").show();	
			$m.find(".m_home_logo").attr("src",c.logopath+c.home_file_code+".png").show();	
			
			// lineups
			$m.find(".m_lineups").unbind().bind("click",function(){
				var game = bam.mediawall.game.getCurrentGame();
				bam.showLineup(game);
			});
			
			// hide banner links
			$(".m_gamestate a").hide();			
			
			// club records
			if(!!c.away_win && !!c.away_loss) {
				$m.find(".m_away_record").html(c.away_win + "-" + c.away_loss).show();
			} else {
				$m.find(".m_away_record").hide();
			}
			if(!!c.home_win && !!c.home_loss) {
				$m.find(".m_home_record").html(c.home_win + "-" + c.home_loss).show();				
			} else {
				$m.find(".m_home_record").hide();
			}
			
			switch(c.gamestate) {		
					
				//**
				//* 
				//* PREVIEW
				//*
				//**			
				case "preview":			
								
					// gamestate banner links	
					// WATCH					
					$m.find(".m_link_watch").attr("href",c.mlbtv_link).html(c.tvtext).show();		
					$m.find(".m_away_score, .m_home_score, .m_inning, .m_outs").hide();											
					if(!!c.gd_enabled){
						if(!c.gd_link_exists){
							// PREVIEW (If available)
							if(!!c.preview_link) $(".m_link_preview").attr("href",c.preview_link).html(c.previewtext).show();			
						} else if(c.gd_link_exists && !c.audio_exists){	
							// GAMEDAY
							$(".m_link_gameday").attr("href",c.gd_link).html(c.gamedaytext).show();		
						} else if(c.gd_link_exists && !!c.audio_exists){
							// LISTEN
							isatbat = (c.gameday_sw === "P") ? true : false;	
							if(isatbat || !!c.audio_exists) {
								thelink=(isatbat)?c.atbat_link:c.audio_link;
								$(".m_link_audio").attr("href",thelink).html(c.audiotext).show();	
							}		
							// GAMEDAY
							$(".m_link_gameday").attr("href",c.gd_link).html(c.gamedaytext).show();	
						}
					}					
					
					//postblurb links are handled in bam.mediawall.js
					
					// stubs
					var ap_name 	= c.away_probable_pitcher,
						ap_id 		= c.away_probable_pitcher_id || "",
						ap_wins 	= c.away_probable_pitcher_wins || "0",
						ap_loss 	= c.away_probable_pitcher_losses || "0",
						ap_era 		= c.away_probable_pitcher_era || "0.00",
						ap_stats	= "("+ap_wins+"-"+ap_loss+", "+ap_era+")",
						ap_link		= "<a href='/team/player.jsp?player_id="+ap_id+"'>"+ap_name+"</a>",
						ap_mugshot	= c.mugshotpath+ap_id+".jpg";						
						if (!ap_id) {
							ap_mugshot = "/mlb/fantasy/wsfb/images/mugshots/default/default_41x49.jpg";
							ap_link = "TBA";
							ap_stats = "";
						}
					
					var hp_name 	= c.home_probable_pitcher,
						hp_id 		= c.home_probable_pitcher_id || "",
						hp_wins 	= c.home_probable_pitcher_wins || "0",
						hp_loss 	= c.home_probable_pitcher_losses || "0",
						hp_era 		= c.home_probable_pitcher_era || "0.00",
						hp_stats	= "("+hp_wins+"-"+hp_loss+", "+hp_era+")",
						hp_link		= "<a href='/team/player.jsp?player_id="+hp_id+"'>"+hp_name+"</a>",		
						hp_mugshot	= c.mugshotpath+hp_id+".jpg";						
						if (!hp_id) {
							hp_mugshot = "/mlb/fantasy/wsfb/images/mugshots/default/default_41x49.jpg";
							hp_link = "TBA";
							hp_stats = "";
						}				
					
					c.$stub1
						.find(".m_stub_text").text("Lanzador programado: " + c.away_file_code.toUpperCase())
						.end()
						.find(".m_stub_container img").attr("src",ap_mugshot)					
						.end()
						.find(".m_stub_name").html(ap_link)
						.end()
						.find(".m_stub_stats").html(ap_stats)
						.end().show();					
					
					c.$stub2
						.find(".m_stub_text").text("Lanzador programado: " + c.home_file_code.toUpperCase())
						.end()
						.find(".m_stub_container img").attr("src",hp_mugshot)
						.end()
						.find(".m_stub_name").html(hp_link)
						.end()
						.find(".m_stub_stats").html(hp_stats)
						.end().show();	
					
				break;
				
				//**
				//* 
				//* LIVE
				//*
				//**
				case "live":				
				
					// gamestate banner links					
					$(".m_link_watch").attr("href",c.mlbtv_link).html(c.tvtext).show();										
					if(!!c.gd_enabled){		
						isatbat = (c.gameday_sw === "P") ? true : false;						
						if(isatbat || !!c.audio_exists) { 
							thelink=(isatbat) ? c.atbat_link : c.audio_link;
							$(".m_link_audio").attr("href",thelink).html(c.audiotext).show();		
						}																						
						$(".m_link_gameday").attr("href",c.gd_link).html(c.gamedaytext).show();								
					}					

					//postblurb links are handled in bam.mediawall.js

					// score
					$m.find(".m_away_score").html(c.away_team_runs).show();
					$m.find(".m_home_score").html(c.home_team_runs).show();
			
					// inning
					$m.find(".m_inning .homesprite").addClass(((c.top_inning === "Y") ? "m_top":"m_btm"))
					.next().text(c.inning).parent().show();
			
					// bases
					$m.find(".m_bases").removeClass().addClass("homesprite m_bases m_bases_" + c.runner_on_base_status).show();
			
					// outs
					$m.find(".m_outs").html(c.outs + " out" + ((c.outs==="1")?"":"s")).show();
				
				
					// stubs
					var p_stats = "",
						p_name 	= c.current_pitcher,
						p_id 	= c.current_pitcher_id,
						p_wins 	= c.current_pitcher_wins,
						p_loss 	= c.current_pitcher_losses,
						p_era 	= c.current_pitcher_era;
						p_stats	= "("+p_wins+"-"+p_loss+", "+p_era+")";
					
					var b_stats = "",
						b_name 	= c.current_batter,
						b_id 	= c.current_batter_id,
						b_avg	= c.current_batter_avg;
						b_stats	= "("+b_avg+")";					
					
					c.$stub1
					.find(".m_stub_text").text("Lanzando")
					.end()
					.find(".m_stub_container img").attr("src",c.mugshotpath+p_id+".jpg")					
					.end()
					.find(".m_stub_name").html(p_name)
					.end()
					.find(".m_stub_stats").html(p_stats)
					.end().show();
										
					c.$stub2
					.find(".m_stub_text").text("Bateando")
					.end()
					.find(".m_stub_container img").attr("src",c.mugshotpath+b_id+".jpg")
					.end()
					.find(".m_stub_name").html(b_name)
					.end()
					.find(".m_stub_stats").html(b_stats)
					.end().show();
				
				break;
				
				//**
				//* 
				//* FINAL
				//*
				//**	
				case "final":
	
					// gamestate banner links
					if(!!c.wrap_link) {				
						$(".m_link_wrap").attr("href",c.wrap_link).html(c.wraptext).show();	
					}
				
					// hide box link for PPD
					if(c.status!=="Postponed") {
						$(".m_link_box").attr("href",c.boxlinkbase+c.gid).html(c.boxtext).show();		
					}
					
					// hide live mode elements
					$m.find(".m_outs, .m_inning").hide();
					
					// score
					$m.find(".m_away_score").text(c.away_team_runs).show();
					$m.find(".m_home_score").text(c.home_team_runs).show();							
			
					// stubs
					var wp_stats 	= "",
						wp_name 	= c.winning_pitcher,
						wp_id 		= c.winning_pitcher_id,
						wp_wins 	= c.winning_pitcher_wins,
						wp_loss 	= c.winning_pitcher_losses,
						wp_era 		= c.winning_pitcher_era,						
						wp_text		= (c.status.toLowerCase() === "postponed") ? "Lanzador Programado" : "Lanzador Ganador";						
						wp_stats	= "("+wp_wins+"-"+wp_loss+", "+wp_era+")";
					
					if(c.winning_pitcher==="null"){
						wp_name		= "TBA";
						wp_stats	= "";
					}
					
					var lp_stats 	= "",
						lp_name 	= c.losing_pitcher,
						lp_id 		= c.losing_pitcher_id,
						lp_wins 	= c.losing_pitcher_wins,
						lp_loss 	= c.losing_pitcher_losses,
						lp_era 		= c.losing_pitcher_era,
						lp_text		= (c.status.toLowerCase() === "postponed") ? "Lanzador Programado" : "Lanzador Perdedor";						
						lp_stats	= "("+lp_wins+"-"+lp_loss+", "+lp_era+")";
					
					if(c.losing_pitcher==="null"){
						lp_name		= "TBA";
						lp_stats	= "";
					}
					
					c.$stub1
					.find(".m_stub_text").text(wp_text)
					.end()
					.find(".m_stub_container img").attr("src",c.mugshotpath+wp_id+".jpg")					
					.end()
					.find(".m_stub_name").html(wp_name)
					.end()
					.find(".m_stub_stats").html(wp_stats)
					.end().show();
									
					c.$stub2
					.find(".m_stub_text").text(lp_text)
					.end()
					.find(".m_stub_container img").attr("src",c.mugshotpath+lp_id+".jpg")
					.end()
					.find(".m_stub_name").html(lp_name)
					.end()
					.find(".m_stub_stats").html(lp_stats)
					.end().show();
	
			break;				
			} 			

		}	// end writematchup		
	}	

	return _self;			

})(jQuery);

//Lineups popModule
bam.showLineup = function(g){
	bam.load(bam.homePath+"bam.popModule.js", function(){
		//convert gameID format to gameday link	
		if ( ~g.indexOf("/") && ~g.indexOf("-") ) {
			g = g.replace(/\//g,"_");
			g = g.replace(/-/g,"_");
		}
		var newHTML  = "<iframe frameborder='0' width='725' height='438' scrolling='no' src='/mlb/lineups/index.jsp?game_id="+g+"'></iframe>";
		bam.popModule.init({
			css        : "/mlb/lineups/lineups.popModule.css", // this is the default css, but custom css can be set here like so
			overlayCss : "/shared/css/bam/bam.overlay.css"    // (same as above)
		});
		bam.popModule.show({
			htmlContent    : newHTML, 
			width          : 725, // default is 500 (set in CSS file)
			height         : 438,
			overlayOpacity : 0.8,
			preShow        : function(){},
			postShow       : function(){}
		});
	});
};

$(function() {
	bam.clubhome.init();
});




