
// @TODO: need to figure out vObj undefined bug. is it still happening?	

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


bam.clubhome = (function($){

	var _log=function(msg){
		if (_self.debug && typeof console !== "undefined" && !!console.log && !!console.dir){		
			if (typeof msg === "string") console.log("bam.clubhome: "+msg);
			else if (typeof msg === "object") console.dir(msg);
			else console.log(msg);	
		}
	},		
	
	
	_club = bam.url.Location( window.location ).getParam( 'c_id' ),
	_CLUB = _club.toUpperCase(),	
	_properties = {},	
	$doc = $(document),
	
	/**
	@
	@
	@
	@ VIDEO CORNER
	@
	@
	@
	**/	
	
	_videocorner = {
		
		autoplay: null,
		
		AUTOPLAY: "#vc_autoplay",
		
		settings: {},
		
		init: function(){		
			// When the page is in game mode show a predetermined MLBTV clip.
			// Otherwise, show the first item in the top videos index.
			var vObj = bam.clubhome.videosettings,
				//dont show that mlbtv ad during game mode anymore
				//props = (bam.mediawall.game.isActive()) ? vObj.mlbtv : vObj.topvideo;	
				props = vObj.topvideo;			
			$.extend(this.settings,props);			
			this.handleautoplay(props.compName);
			_log("_videocorner init");
			if(!!props.file) {
				this.createPlayer(props);		
				$("#vc_caption").html(props.caption);	
			}						
		},
		
		disableautoplay: function(){
			$(this.AUTOPLAY).text("Enable Autoplay");
			var expireDate=new Date();
			expireDate.setHours(expireDate.getHours()+(24*90));		
			bam.cookies.set({
				"name": "clubhome.autoplay.disable",
				"value": "true", 
				"expires": expireDate,
				"domain": "mlb.com"
			});				
			_log("Setting cookie: clubhome.autoplay.disable: expires = " + expireDate);
		},
		
		handleautoplay: function(compName){		
			if(!!bam.cookies.get("clubhome.autoplay.disable")) {
				this.autoplay = false;
				$(this.AUTOPLAY).text("Enable Autoplay");
			} else {
				this.autoplay = true;
				$(this.AUTOPLAY).text("Disable Autoplay");
			}				
			var that=this; 
			$doc.selector = this.AUTOPLAY;	
			$doc.live("click", function(e) {	
				var $target = $(e.target);				
				bam.tracking.track({
					async:{
						isDynamic:false,
						compName: _CLUB + " Video Corner",
						compActivity: _CLUB + " Video Corner: " + $target.text(),
						actionGen:true
					}
				}, $(this)[0]);					
				var cookie = bam.cookies.get("clubhome.autoplay.disable");				
				if(!!cookie){	
					bam.cookies.remove({
						"name": "clubhome.autoplay.disable", 
						"domain": "mlb.com"
					});	
					$(that.AUTOPLAY).text("Disable Autoplay");		
				}else{
					that.disableautoplay();
				}						
                return false;					
        	});			
		},		
		
		drawleavebehind: function(){			
			
			var that=this,
				create = this.createPlayer,
				settings = this.settings;
			$("#vc_flash, #vc_caption").hide();
			bam.clubhome.playerObj = null;	
						
			$("#vc_leavebehind_top img").attr("src",settings.thumb2);
			$("#vc_recap").html(settings.caption);					
			$("#vc_leavebehind").fadeIn();		
					
			$("#vc_replay").unbind().click(function(){
				$("#vc_leavebehind").hide();
				$("#vc_caption").html(settings.caption).add("#vc_flash").show();				
				create.apply(that,[settings,true]);							
				bam.tracking.track({
					async:{
						isDynamic: false,
						compName: _CLUB + " Video Corner",
						compActivity: "Video Corner Replay Link Click",
						actionGen:true
					}
				}, $(this)[0]);
			});			
			// tracking callback: the carousel flash uses this
			bam.clubhome.trackVideoCarouselClicks=function(clickedArea){
				// Ex arg: NYY MORE VIDEOS: 3993637 
				bam.tracking.track({
					async:{
						isDynamic: false,
						compName: _CLUB + " Video Corner",
						compActivity: "Video Corner Video Link Click",
						actionGen:true
					}
				}, $(this)[0]);
			};				
			// initialize carousel flash
			
			var h = "128", w = "256";			
			var vc = new FlashObject("/flash/mediawall/y2010/thumb_carousel.swf", "carousel_flash_obj", w, h, "9", "#ffffff");	
				vc.addParam("wmode", "transparent");
				vc.addParam("scale", "noScale");	
   				vc.addVariable("width", w);
				vc.addVariable("height", h);
				vc.addVariable("club", _club);
				vc.addVariable("tracking_call", "bam.clubhome.trackVideoCarouselClicks");			
				vc.addVariable("team_color", "#ffffff"); 						
				vc.write("vc_carousel_flash");		
		},
	
		createPlayer: function(props,isreplay) {		
			_log("creating CVC player");
			var that   = this,
				isXoom = (bam.env && bam.env.client && bam.env.client.isXoom),
				isIPad = (bam.env && bam.env.client && bam.env.client.isIPad);
			bam.clubhome.playerObj = new bam.FlvPlayer({
				//file		   : "/shared/flash/video/flvplayer_v4.swf",
				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 (isIPad || isXoom){
						clip = {
							type:"video",
							path       : props.file,
							content_id : props.id,
							duration   : props.duration
						};
						clipProps = [clip];
					}					
					if(!!isreplay) {
						pObj.startPlaylist([clip]);
					//}else if(!!that.autoplay && !bam.clubhome.drawer){ 	
					}else if(!!that.autoplay){ 								
						pObj.startPlaylist(clipProps);
					}else{								
						if (!isIPad && !isXoom){
							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 + "|FLASH_300K_256X144",
							playerType     : "Flash",
							playerContext  : props.compname,
							contextVersion : "2.0",
							streamType     : "Progressive Download",
							bitRate        : "300K",
							actionGen	   : (!!that.autoplay)?false:true
						}
					});
				},				
				onPlaylistComplete: function() {
					bam.tracking.track({videoComplete:{playerContext:props.compname}});
					if (!isIPad && !isXoom){
						that.drawleavebehind();
					}
				}
			});		
		}	
	},
	
	
	
	/**
	*
	*
	*
	* HEADLINE STACKS
	*
	* components:
	* createStack,  setTab
	*
	*	
	**/		
	_headlines = {		
		// _headlines.init
		init : function(){			
			// Pulse icon click
			$doc.selector = "a.pulseicon";
			$doc.live("click", function(e) {
				e.preventDefault();
				var gameid = $(this).attr("gameid"),
					gamepk = $(this).attr("gamepk");
				bam.show_gamepulse(gamepk, gameid);
				bam.tracking.track({
					async:{
						isDynamic:true,
						compName: _CLUB + " Headline Stack",
						compActivity:_CLUB + " Headline Stack: Pulse Click",
						actionGen:true
					}
				}, $(this)[0]);
				return true;
			});					
			// News and Notes
			_headlines.createStack({
				url			:	"/gen/news/headlines.json",
				container	:	"#news_1 dl.hl_list",
				endAt		:	3
			});						
		},
		/*
		* @createStack 	
		*
		* @function
		* @args: 
		* 	url : "/gen/news/headlines.json"	[json]
		* 	container : "ul#someID"				[selector]
		*	endAt : 6							[number]
		* 	success : function(){}				[function]
		*   callback : function(){}				[function]
		*
		* @requires
		* 	$.template
		*
		*/		
		createStack : function(p) {				
			var tpl = "/mlb/components/home/y2010/headlines_pulse.tpl";		
			// var tpl = "/mlb/components/home/y2010/headlines.tpl";		
			$.ajax({
				url:		p.url,
				type:		"get",
				timeout: 	5000,
				dataType:	"json",						
				error: 		function(xhr) {_log("Error: " + xhr.status + " " + xhr.statusText);},						
				success: 	function(json) {			
					var arr = bam.util.ensureArray(json.members),
						$headlines = $.template(tpl,arr).find("dd").slice(0,p.endAt);							
					$(p.container).empty().append($headlines);		
					if($.isFunction(p.success)) {
						p.success(json);	
					}											
				},
				complete:	function(){
					if($.isFunction(p.callback)) {
						p.callback();	
					}
				}
			});	
		},	
		// _headlines.setTab
		setTab: function(e,idx){		
			var container = "#headlines_container .h_module_content:eq("+idx+") dl.hl_list";			
			if($(container + " li").length === 0 && idx<1) {	
				_headlines.createStack({
					url			:	"/gen/"+_club+"/news/headlines.json",
					container	:	container,
					endAt		:	5
				});						
			} 
		}
	},

	
	/**
	@
	@
	@
	@ VIDEO MODULE
	@
	@
	@
	**/	
	
	_videoModule = {		
		init: function(){
			// channel locator
			$("#video_container #vm_mlbn_body img").click(function(){		
				popWin("http://mlbn.viewerlink.tv/?zip="+$("#video_container #vm_mlbn_body input").val(),"channel_locator",603,500,"scrollbars=yes,resizable=yes");
				return false; 
			}).css({cursor:"pointer"});
			// show random ad
			var _rotatingads = $(".vm_rotate"),
				_idx = Math.floor(Math.random()* _rotatingads.length);		
			$(".vm_rotate:eq("+_idx+")").show();			
		},				
		setTab: function(e,idx){			
			var $target = $(e.target);				
			var $container = $target.closest(".h_module");			
			var $activeContent = $container.find(".h_module_content:eq("+idx+")");				
			if (!!_videoModule.heartbeat) clearInterval(_videoModule.heartbeat);					
			// load tabs on demand				
			$activeContent.find(".vm_slide_thumb").each(function(){		
				$(this).attr("src",$(this).parents(".vm_slide").attr("thumb"));
			});				
			var $navli = $target.closest("li");					
			var ismlbtv = !!~$navli.attr("id").indexOf("mlbtv");			
			if(ismlbtv){
				$activeContent.load(					
					"/"+_club+"/components/homepage/y2010/mlbtvtab.jsp",
					function(){
						$navli.removeAttr("id");
						_videoModule.rotateAds();
					}				
				);
			}			
		},				
		rotateAds: function(){		
			var elems = $(".vm_rotate"),
				next = $(".vm_rotate:visible").next();			
			if(next.length===0) next = $(".vm_rotate:eq(0)");					
			var idx = $(".vm_rotate").index(next);								
			_videoModule.heartbeat = setInterval(
				function(){
					$(".vm_rotate:eq("+idx+")").hide();
					idx++;
					if(idx > elems.length-1)idx=0;				
					var $theElem = $(".vm_rotate:eq("+idx+")");
					if($.browser.safari)$theElem.show("fast");
					else $theElem.fadeIn("slow");	
				}			
			,15000);
		}
	},
	
	
	
	
	
	/**
	@
	@
	@
	@ UPCOMING HOMESTAND
	@
	@
	@
	**/	
	
	_homestand = (function() {
		
		var series2, isPopped=false, isActive, popID="", isInit=true,		
		
		toDate = function(dObj){
			var d = dObj.replace(/T/gi,"-");
				d = d.replace(/:/gi,"-");
				d = d.split("-");
			var out = new Date(d[0],d[1]-1,d[2].substr(0,2),d[3],d[4]);
			return out;
		},			
			
		// writes out the next three series	
		writeSeriesContainer = function(game,tp) {		
			var gID = game.game_id,
				gIDs = gID.substr(0,gID.lastIndexOf("/")).split("/"),
				id = 'series_' + gIDs[0] + '_' + gIDs[1] + '_' + gIDs[2],			
				$container = $("<div>").addClass("seriesContainer").attr("id",id),		
				htmlStr = enddate = '';
			htmlStr += '<img height="56" border="0" width="57" src="/images/logos/50x50/' + game.away_file_code + '.gif" class="seriesLogo">';
			htmlStr += '<div class="seriesOpponent">vs. ' + game.away_name_short + '</div>';					
			for(i=game.game_index+1; i<tp.length; i++){						
				if(tp[i].away_name_short !== game.away_name_short) {	
					var lastgame = tp[i-1],
						gamedate = toDate(lastgame.game_time_local_str),
						last_gID = lastgame.game_id;														
					if(gID !== last_gID) {
						if(gID.substr(0,7) === last_gID.substr(0,7)) {					
							enddate = " - " + gamedate.getDate();
						} else {
							enddate = " - " + bam.datetime.getMonthFullName(gamedate.getMonth()+1) + " " + gamedate.getDate();		
						}	
					}									
					break;
				}			
			}				
			htmlStr += '<div class="seriesDates">' + game.displayDate + enddate + '</div>';
			htmlStr += '<div class="seriesTickets"><a>Tickets &amp; Promotions</a></div>';
			htmlStr += '<div class="seriesGlance more"><a href="/schedule/sortable.jsp?c_id=' + game.home_file_code + '">Season Series Glance</a></div>';
			htmlStr += '<div align="center" class="seriesDivider"><img height="15" width="188" src="/images/homepage/y2008/divider.jpg"></div>';
			$container.html(htmlStr).insertBefore("#homestandContainer .seriesloge:first");
		},
		
		loadSeries = function(){
			_log("loadSeries");		
			var seriesPopHTML="",
				seriesCount=0,
				props = bam.clubhome.get("clubprops")[_club],
				tixpromos = bam.clubhome.get("tixpromos"),
				tp = $.grep(tixpromos,function(obj,idx){			
					// massage the cached tix/promos data			
					var out = (_club === obj.home_file_code) ? true : false,				
						curdate = sysdate.substr(0,8), // yyyymmdd
						gamedate = obj.game_id.substr(0,10).replace(/\//g,""), // yyyymmdd
						seriesnum = obj.series_home_number,
						nextseriesnum = (!!tixpromos[idx+1]) ? tixpromos[idx+1].series_home_number : 0;		
					// if yesterday's game was the last game in the series don't show the game
					// this is a hack to get around the daystart that's used for the tix/promos query	
					if (gamedate < curdate && seriesnum !== nextseriesnum) out = false;		
					return out;							
				});						
			$.each(tp,function(n){				
				if(seriesCount<3){		
					var gamedate = toDate(this.game_time_local_str);
					var gID = this.game_id;
					var gIDs = gID.substr(0,gID.lastIndexOf("/")).split("/");
					var tlink = (!!this.ticket_link) ? this.ticket_link.tlink : "";																	
					var dayOfWeek = bam.datetime.getDayName(gamedate.getDay()+1);
					var displayDate = bam.datetime.getMonthFullName(gamedate.getMonth()+1) + " " + gamedate.getDate();		
					var timeLocal = bam.datetime.DateTime(gamedate).formatDate("h:mm");							
						timeLocal += (gamedate.getHours() >11)?"pm":"am";							
					var homePitcher = this.home_probable_pitcher_name || "Pitcher TBA";
						if ( ~homePitcher.indexOf(",") ) {
							homePitcher=homePitcher.substr(0,homePitcher.indexOf(","));
						}							
					var homePitcherRecord = "";							
						if (this.home_probable_win && this.home_probable_loss) {
							homePitcherRecord = this.home_probable_win + "-" + this.home_probable_loss;
						}
					var awayPitcher = this.away_probable_pitcher_name || "Pitcher TBA";
						if ( ~awayPitcher.indexOf(",") ) {
							awayPitcher=awayPitcher.substr(0,awayPitcher.indexOf(","));
						}							
					var awayPitcherRecord = "";							
						if (this.away_probable_win && this.away_probable_loss) {
							awayPitcherRecord = this.away_probable_win + "-" + this.away_probable_loss;
						}			
					var curOpp = this.away_name_short;
					var prev = tp[n-1] || {};
					var prevOpp = prev.away_name_short || "";
					var next = tp[n+1] || {};
					var nextOpp = next.away_name_short || "";																		
					if(n===0 || curOpp !== prevOpp) {
						$.extend(this,{"game_index":n, "displayDate":displayDate});
						writeSeriesContainer(this,tp);
						seriesPopHTML+='<div class="series"><div class="seriesPop">';		
					}			
					seriesPopHTML+="<div id='game_" + gIDs[0] + "_" + gIDs[1] + "_" + gIDs[2] + "_" + gID.charAt(gID.length-1) + "'>";						
					seriesPopHTML+= '<div class="seriesGameHdr primary">';
					if(tlink!==""){
						tlink = "javascript:void(openNonTIXXWindow('" + tlink + "','home', ['homeseries','B2']));";		
						seriesPopHTML+= '<a href="'+tlink+'"><img class="tixImg" src="/images/schedule/icon_ticket.gif"></a>';														
					}		
					seriesPopHTML+= dayOfWeek + '., ' + displayDate.substr(0,3) + (displayDate.substr(0,3)=="May"?" ":". "); 					
					seriesPopHTML+= displayDate.substr(displayDate.indexOf(" ")) + ' @ ' + timeLocal + '</div>';
					seriesPopHTML+='<div class="seriesGameContent"><div class="seriesGameContentPad"><div class="homeStarter">';				
					seriesPopHTML+=(homePitcher=="Pitcher TBA")?homePitcher:homePitcher+' ('+homePitcherRecord+')';				
					seriesPopHTML+='</div><div class="awayStarter">vs. ';
					seriesPopHTML+=(awayPitcher=="Pitcher TBA")?awayPitcher:awayPitcher+' ('+awayPitcherRecord+')';			
					seriesPopHTML+='</div></div></div></div>';					
					if(curOpp !== nextOpp) {
						seriesPopHTML+='</div><div class="textXs seriesLegend"><div class="moreArrows"><div class="moreArrowTop"></div><div class="moreArrowBottom"></div></div><div class="tixPurchase"><img src="http://mlb.mlb.com/images/schedule/icon_ticket.gif" align="absmiddle" style="padding-bottom:2px" /> = Purchase Tickets</div><div class="closePop">[ close ]</div></div></div>';
						seriesCount++;
					}									
				}	
			});	
			$("#seriesPopData").html(seriesPopHTML);	
			loadSeriesPromos(tp);	
			assignEvents();
		},	
		
		
		loadSeriesPromos = function(tp){	
			_log("loadSeriesPromos tp");	
			$.each(tp,function(){
				var game = this,
					promo = bam.util.ensureArray(game.promotion);
				if(promo.length>0) {
					$.each(promo,function(n){	
						var gID=game.game_id,				
							puid = gID.replace(/-/g,"_").replace(/\//g,"_"),		
							gIDs=gID.split("/"),			
							$gameContainer = $("#game_" + gIDs[0] + "_" + gIDs[1] + "_" + gIDs[2] + "_" + gID.charAt(gID.length-1));			
						oID = this.offer_id;					
						// sorting?					
						if($gameContainer.find("#"+oID).length === 0){					
							$("<div class='seriesGameContent' id='"+oID+"'><div class='seriesGameContentPad seriesGamePromo' puid='"+puid+"'>" + this.offer_name + "</div></div>")
							.insertAfter($gameContainer.find(".seriesGameContent:last"));						
						}									
					});
				}			
			});					
		},		
		
		showSeriesPop = function(series){
			_log("showSeriesPop");		
			var setDisplay="block",popOffSet=135;			
			if($("#seriesPopContainer").css("display")==="block")setDisplay="none";		
			if(series!==series2)setDisplay="block";	
			series2=series;			
			$("#seriesPopContainer").css("display",setDisplay);				
			// hide past games			
			var current = bam.datetime.toYMD(bam.datetime.parseYMDHM(sysdate,6));			
			$(".series div[id^=game_]").each(function(){
				var gameDate=this.id.substr(5).replace(/_/g,"");				
				if(current>gameDate) $(this).hide();	
			});			
			$("#seriesPopContainer .series").hide();		
			var thisSeries = $("#seriesPopContainer .series:eq("+series+")");
			thisSeries.fadeIn();				
			if(thisSeries.height()>262)addSeriesScrolling(series);			
			var linkPosition=bam.dom.getPosition($(".seriesTickets")[series]);	
			//reposition popup
			$(".popright").parent().css({top:linkPosition.Top-popOffSet,left:linkPosition.Left+176});	
			$(".popleft").parent().css({top:linkPosition.Top-popOffSet,left:linkPosition.Left-179});	
			$(".closePop").css("cursor","pointer").click(function() {hideSeriesPopup();});
			isPopped=true;
			popID=series;	
		},
		
		hideSeriesPopup = function(series){
			_log("hideSeriesPopup");	
			if(!!isPopped){ 
				$("#seriesPopContainer").fadeOut(function(){
					$(this).css("top","-1000px");		
					popID=""; isPopped=false; isActive=false;		
				});				
			}	
		},		
		
		addSeriesScrolling = function(series){
			_log("addSeriesScrolling");	
			var thisSeries = $(".seriesPop:eq("+series+")"),
			thisLegend = thisSeries.next();
			thisSeries.css({height: "262px", overflow: "hidden"});							
			thisLegend.find(".moreArrows").show();								
			thisLegend.find(".moreArrowBottom").hover(
				function () {$(this).addClass("moreArrowBottomHover");},
				function () {$(this).removeClass("moreArrowBottomHover");}					
			)
			.click(function() {$('.seriesPop').animate({scrollTop: '+=262px'}, 1000);});			
			thisLegend.find(".moreArrowTop").hover(
				function () {$(this).addClass("moreArrowTopHover");},
				function () {$(this).removeClass("moreArrowTopHover");}					
			)
			.click(function() {$('.seriesPop').animate({scrollTop: '-=262px'}, 1000);});				
			$('.tixPurchase').width(120);		
		},		
		
		assignEvents = function(){
			_log("assignEvents");						
			$(".seriesTickets a").hover(function(){ 		
				var idx=$(".seriesTickets a").index($(this));		
				if(idx!==popID)showSeriesPop(idx);	
				clearTimeout(isActive);		
			}, function() {
				isActive=setTimeout(function(){ hideSeriesPopup(); },3000);	
			}).click(function(){
				var idx=$(".seriesTickets a").index($(this));	
				if(!!isPopped)	hideSeriesPopup();
				else showSeriesPop(idx);	
			});	
			$("#seriesPopData").hover(
				function(){ clearTimeout(isActive); },
				function(){ isActive=setTimeout(function(){ hideSeriesPopup(); },3000);	 }
			);	
			// assign "series at a glance" and promotion schedule links	
			$(".seriesGlance a").each(function(){$(this).attr("href","/schedule/sortable.jsp?c_id="+_club);});		
			// promo links in overlay div
			$doc.selector = ".seriesGamePromo";
			$doc.live("click", function(e) {
				window.open(
						'/schedule/promotions_popup.jsp?c_id='+_club+'&puid='+$(this).attr("puid"), 
						'mlb_promo', 
						'width=316,height=300,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=yes'
					);	
			});						
			// this hides a bug in FF3. Bugzilla.mozilla.org #442542
			$(window).resize( hideSeriesPopup );				
		},
		
		self = {
			init: function(){
				_log("init homestand");													
				$("#seriesPopContainer").remove().insertAfter("#metaWrap");		
				loadSeries();
			}
		};
	
		return self;
	})(),


	
	

	
	/**
	@
	@
	@
	@ CREATE CAROUSEL 
	@
	@
	@
	**/		
	_createCarousel = function(){			
		var $clip = $("#vertical_container .carousel_container"),
			clipwidth = $clip.width(),	
			$content,
			numPages,
			start,				
			indicators = "#vertical_container .carousel_pag li a",		
			controls = "#carousel_next, #carousel_prev",					
			$container = $clip.find("div:first"),			
			liStr = "",	
			ON = "pagOn",	
			$firstClone, 
			$lastClone,		
			newPos,				
			switchContent = function(idx,cb){	
				idx++;	
				newPos = -(clipwidth*idx);
				$(indicators).removeClass(ON);					
				// @TODO: add stop() to handle multiple fast clicks?
				$container.animate({ left: newPos }, 500, "linear",function(){						
					if(idx>numPages){
						// reset to first panel
						$container.css({ left: -clipwidth });						
						$(indicators + ":eq(0)").addClass(ON);						
					}else if(idx<=0){
						// reset to last panel
						$container.css({ left: -(clipwidth * numPages) });						
						$(indicators + ":eq("+(numPages-1)+")").addClass(ON);
					}else{
						idx--;
						$(indicators + ":eq("+idx+")").addClass(ON);					
					}
					if($.isFunction(cb)) { cb(); }
				});						
			};		
		
		// clones the first and last panels to support "circular" scrolling	
		$firstClone = $clip.find("ul:first").clone().addClass("isClone");
		$lastClone = $clip.find("ul:last").clone().addClass("isClone");				
		$firstClone.appendTo($clip.find("div:first"));
		$lastClone.prependTo($clip.find("div:first"));			
		$content = $clip.find("ul");
		numPages = $content.length-2; // subtract the clones			
		start = (!!bam.clubhome.randomizePromotions) ? Math.floor(Math.random()*(numPages)) : 0;			
		// sets the width of the entire scrolling area	
		$container.width((numPages+2) * clipwidth);		
		// shows the indicator icons
		$("#vertical_container .carousel_pag ul li:lt("+numPages+")").css("display","inline");				
		
		// Events
		// @TODO: figure out why binding this with live() isn't working		
		$(indicators).click(function() {				
			var items = $(this).closest("ul").find("a"),
				idx = items.index($(this));		
			switchContent(idx);
		});			
		$doc.selector = controls;		
		$doc.live("click", function(e) {				
			var activeItem = $("."+ON),
				curPos = $(indicators).index(activeItem),
				theID = $(e.target).attr("id"),
				newPos = (~theID.indexOf("prev")) ? curPos-1 : curPos+1;							
		//	if(newPos >= numPages || newPos < 0) newPos = curPos;
			switchContent(newPos);
        });		
		$(controls).hover(
			function(){ $(this).addClass("on"); },
			function(){ $(this).removeClass("on"); }
		);			
		// this kicks it off		
		switchContent(start,function(){
			$content.show();
		});			
	},
	

	
	
	
	/**
	@
	@
	@
	@ TAB NAV BUTTONS
	@
	@
	@
	**/	
	_navbuttons = function(){	
		var isfirstclick=true;	
		var setContent = function(e,idx){
			var $target = $(e.target);	
			var tabtext = $target.closest("li").find(".tb_mid").text();
			var $container = $target.closest(".h_module");
			var $activeContent = $container.find(".h_module_content:eq("+idx+")");		
			var compName = 	$container.find(".navbuttons").attr("compName");
			if(!compName)compName = _CLUB + " Tab Navigation";		
			$activeContent.siblings(".h_module_content").hide();
			$activeContent.fadeIn();
			if(!isfirstclick) {			
				bam.tracking.track({
					async:{
						isDynamic: true,
						compName: ((compName === "series_standings") ? _CLUB + " Homepage " + bam.string.trim($target.text()) : bam.string.trim(compName)),
						compActivity: _CLUB + " " + bam.string.trim(tabtext) + " Tab Click",
						actionGen:true
					}
				}, $target);					
			}		
		};		
		// add custom functions here. the property name must equal the id of the container ul	
		var actions = {		
			"v_nav"		: _videoModule.setTab,
			"hl_nav"	: _headlines.setTab			
		};				
		$doc.selector = "ul.navbuttons li";		
		$doc.live("click", function(e) {	
			var $li = $(this);			
			if($li.parent().children().length > 1) {
				var idx = $li.parent().children("li").index($li);								
				$li.find("div").andSelf().addClass("tb_on");
				$li.siblings().removeClass("tb_on").find("li,div").removeClass("tb_on");	
				setContent(e,idx);	
				var key = $li.parent().attr("id");
				var action = actions[key];
				if(!!action)action(e,idx);				
			}	
        });
		$("ul.navbuttons li").each(function(){				
			var old_html = $(this).html();
			var new_html = "<div class='tb_left'></div><div class='tb_mid'>" + old_html + "</div><div class='tb_right'></div>";					
			$(this).html(new_html).show();				
		});
		$("ul.navbuttons").each(function(){		
			isfirstclick=true;
			var $container = $(this),
				$items = $container.find("li"),
				totalwidth = 0;		
			$items.each(function(){ totalwidth+=$(this).width(); });
			$container.width(totalwidth);			
			if ($items.length > 1) {				
				var $default_tab = $container.find("li.h_module_nav_default");								
				if($default_tab.length>0) {
					$container.find("li").css("cursor","pointer");
					$default_tab.find("div.tb_mid").click();
					isfirstclick=false;
				}else{					
					var rand = Math.floor(Math.random() * $items.length);
					$container.find("li").css("cursor","pointer").end()
					.find("li:eq("+rand+")").find("div.tb_mid").click();
					isfirstclick=false;
				}
			} else {
				$(this).closest(".h_module").find(".h_module_content").fadeIn();	
			}			
		});			
	},
	
	
	
	/**
	@
	@
	@
	@ TRACKING
	@
	@
	@
	**/		
	_track = function(){	
		
		_log("_track");
		
		function cap(d){
			return d.charAt(0).toUpperCase() + d.slice(1);
		}

		//matchup
		$doc.selector = ".m_gamestate a";
		$doc.live("click", function(e) {
			var $target = $(e.target);	
			var gamestate = $("#m_gameon").attr("class");						
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Matchup",
					compActivity: _CLUB + " Matchup: " + cap(gamestate) + " - " + $target.text() + " Click",
					actionGen:true
				}
			}, $(this)[0]);		
		});	
		
		// 3 day sked
		$doc.selector = "#m_schedule .m_sked_tix";
		$doc.live("click", function(e) {
			var $target = $(e.target);	
			var $li = $target.closest("li");
			var dates = $("#m_schedule li");
			var idx = dates.index($li);
			++idx;
			bam.tracking.track({
				async:{
					isDynamic:true,
					compName: _CLUB + " Homepage Matchup",
					compActivity: _CLUB + " Matchup: Calendar - Day " + idx + " Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		
		// headlines
		$doc.selector = "#headlines_container .hl_list dd";
		$doc.selector = "#hl_list dd a:not(.pulseicon)";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Headline Stack",
					compActivity: _CLUB + " Headline Stack: Team Headline Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#headlines_container .more a";
		$doc.live("click", function(e) {
			var $target = $(e.target);	
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Headline Stack",
					compActivity: _CLUB + " Headline Stack: Team More Headlines Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#headlines_container a.hl_rss";
		$doc.live("click", function(e) {
			var $target = $(e.target);	
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Headline Stack",
					compActivity: _CLUB + " Headline Stack: Team RSS Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#h_local h4 a";
		$doc.live("click", function(e) {
			var $target = $(e.target);	
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Other Sports",
					compActivity: _CLUB + " Other Sports: Headline Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#local_teams a";
		$doc.live("click", function(e) {
			var $target = $(e.target);	
			var $container = $target.closest(".local_container");
			var team = $container.find("h5:eq(0)").text();
			var linklabel = (e.target.tagName==="A") ? $target.text() : "Logo";			
			var thestatsurl = $target.closest("a").attr("href");
			var str = unescape(thestatsurl);
				str = str.substr(str.indexOf("stats.com/")+10);				
			var finish = str.indexOf("/");
			var league = str.substr(0,finish).toUpperCase();
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Other Sports",
					compActivity: _CLUB + " Other Sports: " + league + " - " + team + ": " + linklabel + " Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		
		
		
		// video module		
		$doc.selector = "#video_container .vm_slide a";
		$doc.live("click", function(e) {
			var $target = $(e.target);				
			var $container = $target.closest(".h_module_content");
			var containers = $("#video_container div.h_module_content");
			_log("containers.length="+containers.length);
			var idx = containers.index($container);
			_log(idx);
			var tabtext = $("#video_container .navbuttons li:eq("+idx+") .tb_mid").text();			
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Video Content Module",
					compActivity: _CLUB + " VC: "+tabtext+" Video Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		
		// news and notes
		$doc.selector = "#news_notes_container #news_1 .bullet_round_black a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage News & Notes",
					compActivity: _CLUB + " News & Notes: MLB Headline Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#news_notes_container #news_1 .more a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage News & Notes",
					compActivity: _CLUB + " News & Notes: More MLB Headlines Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#news_notes_container #news_2 .bullet_round_black a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage News & Notes",
					compActivity: _CLUB + " News & Notes: Release Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#news_notes_container #news_2 .more a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage News & Notes",
					compActivity: _CLUB + " News & Notes: More Releases Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#news_notes_container #news_3 a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage News & Notes",
					compActivity: _CLUB + " News & Notes: Feature Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		
		// leaders
		$doc.selector = "#leaders_container .leaders a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Stats",
					compActivity: _CLUB + " Stats: Player Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		$doc.selector = "#leaders_container .more a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Stats",
					compActivity: _CLUB + " Stats: View All Stats Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		
		//vertical carousel		
		$("#vertical_container #carousel_prev").click(function(e) {
			_log("track carousel nav");	
			bam.tracking.track({
				async:{
					isDynamic:true,
					compName: _CLUB + " Homepage Promotions",
					compActivity: _CLUB + " Promotions: Previous Click",
					actionGen:true
				}
			}, $(this)[0]);
		});			
		$("#vertical_container #carousel_next").click(function(e) {
			_log("track carousel nav");	
			bam.tracking.track({
				async:{
					isDynamic:true,
					compName: _CLUB + " Homepage Promotions",
					compActivity: _CLUB + " Promotions: Next Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		$("#vertical_container .carousel_pag li").click(function() {	
			_log("track carousel nav");	
			var items = $(this).closest("ul").find("li");
			var idx = items.index($(this));		
			++idx;		
			bam.tracking.track({
				async:{
					isDynamic:true,
					compName: _CLUB + " Homepage Promotions",
					compActivity: _CLUB + " Promotions: Circle " + idx + " Click",
					actionGen:true
				}
			}, $(this)[0]);
			return false;
		});	
		$doc.selector = "#vertical_container .vert_item a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Promotions",
					// TO DO: add panel index
					compActivity: _CLUB + " Promotions: Panel Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		
		// more from		
		$doc.selector = "#more_from_container li a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage More From",
					// TO DO: add panel index
					compActivity: _CLUB + " More From: Panel Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		
		// photos
		$doc.selector = "#photo_container #galleryLinkPrev a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Photos",
					compActivity: _CLUB + " Photos: Previous Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#photo_container #galleryLinkNext a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Photos",
					compActivity: _CLUB + " Photos: Next Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#photo_container #galleryLink";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Photos",
					compActivity: _CLUB + " Photos: Gallery Click",
					actionGen:true
				}
			}, $(this)[0]);
		});		
		$doc.selector = "#photo_container #photos_links .left";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Photos",
					compActivity: _CLUB + " Photos: Photo Store Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		$doc.selector = "#photo_container #photos_links .right";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Photos",
					compActivity: _CLUB + " Photos: More Galleries Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		
		// Blogs
		$doc.selector = "#blogs_container .blogs_content a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Blogs",
					compActivity: _CLUB + " Homepage Blogs: Blog Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		
		// Mobile
		$doc.selector = "#mobile_container a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Mobile",
					compActivity: _CLUB + " Homepage Mobile: Content Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
		
		// Initiatives
		$doc.selector = "#initiatives_container a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Initiatives",
					compActivity: _CLUB + " Homepage Initiatives: Content Click",
					actionGen:true
				}
			}, $(this)[0]);
		});
	},
	
	
	_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 _writeSchedule: " + xhr.status + " " + xhr.statusText); 				
			},						
			data		: { 
				team_id: props.team_id, 
				sport_id: 1,
				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(); }
			}	
		});				
	},
	

	
	_writeschedule = function() {		
		_log("_writeschedule");
		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, M/d");		
			$next.text("Next Game: "+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 = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];				
			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='/images/trans.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) {	
						_log("!!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
	@
	@
	@
	**/	
	_self = {
		debug: !!bam.env.host["isQA"] || !!bam.env.host["isDev"],
		
		playerObj: null,

		init: function(){		
			setTimeout(function(){document.location.reload(true);},1800000); // 30 minute refresh				
			_self.loadprops();					
			_loadtixpromos(function(){
				_writeschedule();
				_homestand.init();			
			});
			_navbuttons();			
			_videocorner.init();			
			_headlines.init();
			_track();
			_videoModule.init();	
			_createCarousel();		

							
		},
				
		// 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().end().find("#m_schedule").show();
			}else{
				/*
				// get list of probables
				$container.find(".m_stub_bio:not(:has(.m_stub_name))").each(function(){				
					var $bio = $(this),
						cid = $bio.closest(".m_stub").attr("cid"),
						xmlsource = "/mlb/components/home/config/pitchers_"+cid+".xml";					
					// t21 and t31 are DB flags for unknown
					if(cid === "t21" || cid === "t31") {
						$bio.html("<div class='m_stub_name'>TBA</div>");
					} else {						
						$.ajax({
							url:		xmlsource,
							dataType:	"xml",
							type:		"get",
							timeout: 	5000,						
							error: 		function(xhr) {_log("Error getting probables XML")},							
							success: 	function(xml) {
								var tempStr="";
								$("pitcher[active='true']",xml).each(function(){							
									tempStr += "<a class='m_stub_name' href='/team/player.jsp?player_id=" + $(this).attr("id") + "'>" + $(this).attr("displayname") + "</a>";								
								});				
								$bio.html(tempStr).closest(".m_stub").addClass("unknownProbable");															
							}	
						});					
					}
					// update CSS here					
				});
				*/
				$container.find(game).hide().end().find(nogame).fadeIn();
				
			}			
		},
		
		
		/**
		* 
		* 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("2. 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;	
							// for springtraining 2011 listen links should not use atbat
							isatbat = 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
					
					//http://newyork.yankees.mlb.com/team/player.jsp?player_id=429985
					
					// 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("Probable Pitcher: " + c.away_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("Probable Pitcher: " + c.home_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;	
						// for springtraining 2011 listen links should not use atbat
						isatbat = 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("Now Pitching")
					.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("Now Batting")
					.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") ? "Probable Pitcher" : "Winning Pitcher";						
						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") ? "Probable Pitcher" : "Losing Pitcher";
						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(){}
		});
	});
};


$(bam.clubhome.init);



