
// @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("clubhome: "+msg);
			else if (typeof msg === "object") console.dir(msg);
			else console.log(msg);			
		}	
	},
	
	_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;
	},	
	
	_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 (see videocorner.jsp).
			var contentid, path, props={}, that=this, compName = _CLUB + " Video Corner";				
			if(bam.gameticker && bam.gameticker.getGroupedStatus() == "Live" && false) {
				//contentid=this.gameTimeClips[_club];			
			} else {
				contentid=$("#vc_flash").data("contentid")+"";
			}										
			
			curClipData = bam.media.getMetaData(contentid);			
			if (curClipData && typeof curClipData.urls!=="undefined"){						
				$.each(curClipData.urls, function(i, url){ 				
				ps = url.getAttribute("playback_scenario");
					if(ps === "FLASH_300K_256X144") path=url.firstChild.nodeValue;	
					else if(ps === "FLASH_300K_256X144_SD") path=url.firstChild.nodeValue;					
				});						
				$.extend(this.settings,{
					contentid	: contentid,
					path		: path,
					duration 	: bam.media.getDurationInSeconds(curClipData.duration),
					caption		: curClipData.blurb,
					thumb		: curClipData.imagesByType["10"] || "",
					thumb2		: curClipData.thumb,
					clubname	: _self.get("clubprops")[_club].club_full_name.toLowerCase().replace(" ",""),			
					compname	: compName
				});	
				this.handleautoplay(compName);
				this.createPlayer();			
			}else {
				_log("CVC: Meta data is not available or bad.");
			}				
		},		
		
		
		disableautoplay: function(){			
			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);
			$(this.AUTOPLAY).html("Enable Autoplay");
		},

		handleautoplay: function(compName){				
			var that = this;
			if(!!bam.cookies.get("clubhome.autoplay.disable")) {
				this.autoplay = false;
				$(this.AUTOPLAY).text("Enable Autoplay");
			} else {
				this.autoplay = true;
				$(this.AUTOPLAY).text("Disable Autoplay");
			}					 
			$doc.selector = this.AUTOPLAY;	
			$doc.live("click", function(e) {	
				var $target = $(e.target), cookie = bam.cookies.get("clubhome.autoplay.disable");			
				bam.tracking.track({
					async:{
						isDynamic:false,
						compName: _CLUB + " Video Corner",
						compActivity: _CLUB + " Video Corner: " + $target.text(),
						actionGen:true
					}
				});								
				if(!!cookie){	
					bam.cookies.remove({
						"name": "clubhome.autoplay.disable", 
						"domain": "mlb.com"
					});	
					$(that.AUTOPLAY).text("Disable Autoplay");		
				}else{
					that.disableautoplay();
				}								
        	});			
		},
		
		drawleavebehind: function(){				
			var that=this,
				props=this.settings,
				create = this.createPlayer;
			$("#vc_flash, #vc_caption").hide();
			bam.clubhome.playerObj = null;						
			$("#vc_leavebehind_top img").attr("src",props.thumb2);
			$("#vc_recap").html(props.caption);					
			$("#vc_leavebehind").fadeIn();					
			$("#vc_replay").unbind().click(function(){
				$("#vc_leavebehind").hide();
				$("#vc_caption").html(props.caption).add("#vc_flash").show();				
				create.apply(that,[props,true]);							
				bam.tracking.track({
					async:{
						isDynamic: false,
						compName: _CLUB + " Video Corner",
						compActivity: "Video Corner Replay Link Click",
						actionGen:true
					}
				});
			});			
			// tracking callback: the carousel flash uses this
			bam.clubhome.trackVideoCarouselClicks=function(clickedArea){
				// Ex arg: NYY MORE VIDEOS: 3993637 
				// @TODO: get the swf updated to call this function when carousel nav arrows are clicked
				bam.tracking.track({
					async:{
						isDynamic: false,
						compName: _CLUB + " Video Corner",
						compActivity: "Video Corner Video Link Click",
						actionGen:true
					}
				});
			};				
			// 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");		
		},
		
		gameTimeClips : {
			"ari":"13118009", "atl":"13118011", "bal":"13118017", "bos":"13118013", "chc":"13118019", "cin":"13118015", "cle":"13118027", "col":"13118663", "cws":"13118025", "det":"13118075", "fla":"13118023", "hou":"13118021", "kc":"13118031", "ana":"13118039", "la":"13118033", "mil":"13118043", "min":"13118035", "nym":"13118041", "nyy":"13118047", "oak":"13118037", "phi":"13118045", "pit":"13118125", "sd":"13118089", "sea":"13118051", "sf":"13118049", "stl":"13118055", "tb":"13118053", "tex":"13118147", "tor":"13118177", "was":"13118077"
		},		
	
		createPlayer: function(isreplay) {		
			_log("creating CVC player");
			var that   = this,
				props  = this.settings,
				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({
				skin           : "mlb_mini_2010",
				autoHideSkin   : true,
				skinFadeDelay  : 2,
				self           : "bam.clubhome.playerObj",
				elemId         : "ClubHomeFlashPlayer",
				height         : 144,
				width          : 256,
				containerId    : "vc_flash",
				volume  : 0,
				debugMode      : false,
				autoRewind	   : true,
				pageComponent  : "video_corner",
				onPlayerLoaded : function(){	
					$("#vc_caption").hide().html(props.caption).fadeIn();
					var pObj = bam.clubhome.playerObj;						
					var clip = {type:"video", videoPath:props.path};										
					var clipProps = [{type:"video", videoPath:props.path, content_id:props.contentid, 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 + ".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.path,
							content_id : props.contentid,
							duration   : props.duration
						};
						clipProps = [clip];
					}									
					if(!!isreplay) {
						pObj.startPlaylist([clip]);	
					}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.contentid + "|FLASH_300K_256X144",
							playerType     : "Flash",
							playerContext  : props.compname,
							contextVersion : "2.0",
							streamType     : "Progressive Download",
							bitRate        : "300K",
							actionGen	   : false
						}
					});
				},
				onPlaylistComplete: function() {
					bam.tracking.track({videoComplete:{playerContext:props.compname}});
					if (!isIPad && !isXoom){
						that.drawleavebehind();
					}
				}
			});		
		}	
	},
	
	
	
	/**
	*
	*
	*
	* HEADLINE STACKS
	*
	* components:
	* createStack,  setTab
	*
	*	
	**/		
	_headlines = {		
		init : function(){		
		
			
			// Main headline stack
			_headlines.createStack({
				url			:	"/gen/"+_club+"/news/headlines.json",
				container	:	"#headline_container dl.hl_list",
				endAt		:	7,
				callback	: function(){
					$("#headline_container .more").show();
				}
			});						
			/*
		
		
					
			// 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]
		*
		*/		
		createStack : function(p) {				
			var tpl = "/mlb/components/home/y2011/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 out="", $headlines, arr = bam.util.ensureArray(json.members);
					$.each(arr,function(){						
						var t      		= this.type, 
							headline	= this.headline,
							althead		= this.althead,
  							displaytext	= (window.club && club !== "mlb") ? headline : althead,		
      						u      		= this.url, 
      						state  		= this.state, 
      						gameid 		= this.gameid, 
      						gamepk 		= this.gamepk, 		
							isIpad 		= bam.env.client.isIPad,
							isXoom		= bam.env.client.isXoom,
							keywords 	= this.keywords,
							ddclass		= "",
      						str    		= "",
							homeObj 	= bam.clubhome,
							i			= 0,	
							keyword, openTags, closeTags;							
						for (; i<keywords.length; i++) { 
							keyword = keywords[i]; 
							if(keyword.key === "piped_link") { 
								ddclass = " class='hl_float'";		
							}else if(~keyword.key.indexOf("columnist_")) { 
								displaytext = althead;		
							}	
 						}			   
						if (t === "articles") {
							str = "<a href='" + u + "'>" + displaytext + "</a>";									
						} else if (t === "content_short") {		
							openTags = headline.split("<").length;
							closeTags = headline.split(">").length;		
							if(openTags-closeTags===0 && openTags+closeTags>2){
								str = headline;
							}else{
								str = "<a href='" + u + "'>" + headline + "</a>";
							}				
						}									
						out += "<dd" + ddclass + ">" + str + "</dd>";					
					});								
					$headlines = $("<div>").html(out).find("dd:even").addClass("odd").end().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();	
					}
				}
			});	
		},
		
		/*
		*
		* @setTab
		* this function gets called every time there's a tab click
		* it's defined in _navbuttons in an object call "actions"
		*
		*/
		setTab : function(e, idx){
			_log("_headlines.setTab. idx=" + idx);
		}
	},

	
	/**
	@
	@
	@
	@ 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(".module_nav");			
			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);
		}
	},
	
	/**
	@
	@
	@
	@ 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(){
		$('#homepage_container ul.navbuttons li:first-child').addClass('first');
		$('#homepage_container ul.navbuttons li:last-child').addClass('last');	
		var isfirstclick=true;	
		var setContent = function(e,idx){
			var $target = $(e.target);	
			var tabtext = $target.closest("li").find("h3").text();
			var $container = $target.closest(".module_nav");
			var $activeContent = $container.find(".h_module_content:eq("+idx+")");		
			var compName = 	$container.find(".navbuttons").attr("compName");
			if(!compName)compName = _CLUB + " Tab Navigation";			
			if(compName === "series_standings") compName = _CLUB + " Homepage " + bam.string.trim($target.text());
			else compName = bam.string.trim(compName);			
			$activeContent.siblings(".h_module_content").hide();
			$activeContent.fadeIn();
			if(!isfirstclick) {			
				bam.tracking.track({
					async:{
						isDynamic: true,
						compName: compName,
						compActivity: compName + ": " + 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,
			"standings_nav"	: _loadMilestones
		};				
		$doc.selector = "ul.navbuttons h3, ul.navbuttons li";		
		$doc.live("click", function(e) {	
			var $li = $(e.target).closest("li");			
			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").show();			
		$("ul.navbuttons").each(function(){		
			isfirstclick=true;
			var $container = $(this),
				$items = $container.find("li"),
				totalwidth = 0;		
			$items.each(function(){ totalwidth+=$(this).width(); });	
			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("h3").click();
					isfirstclick=false;
				}else{					
					var rand = Math.floor(Math.random() * $items.length);
					$container.find("li").css("cursor","pointer").end()
					.find("li:eq("+rand+")").find("h3").click();
					isfirstclick=false;
				}
			} else {
				$(this).closest(".module").find(".h_module_content").fadeIn();	
			}			
		});			
	},
	
	_classInSession = function(){
		$(".links_stack").find("li:even").addClass("odd");
		$(".standings_data_table").find("tr:even").addClass("odd");
		$(".blurb:last-child").addClass("last");
		$(".twitter").find("dl:first").addClass("first");
		$(".twitter").find("dl:gt(5)").addClass("over_flow");
		$("#adverts100").find(".row:last-child").addClass("last");
	},
	
	
	/**
	@
	@
	@
	@ TRACKING
	@
	@ TODO: clean this up with delegation!
	@
	**/		
	_track = function(){	
		
		function cap(d){
			return d.charAt(0).toUpperCase() + d.slice(1);
		}
		
		// headlines
		$doc.selector = "#headline_container a.hl_rss";
		$doc.live("click", function(e) {
			var compname = _CLUB + " Homepage Headline Stack";
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: compname,
					compActivity: compname + ": RSS Click",
					actionGen:true
				}
			});
		});	
		
		$doc.selector = "#headline_container li a, #headline_container dd a";
		$doc.live("click", function(e) {
			var compname = _CLUB + " Homepage Headline Stack";
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: compname,
					compActivity: compname + ": Headline Click",
					actionGen:true
				}
			});
		});	
		
		$doc.selector = "#headline_container .more a";
		$doc.live("click", function(e) {
			var compname = _CLUB + " Homepage Headline Stack";
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: compname,
					compActivity: compname + ": More Headlines Click",
					actionGen:true
				}
			});
		});			
		
		// 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");
			var idx = containers.index($container);
			var tabtext = $("#video_container .navbuttons li:eq("+idx+") h3").text();		
			var compname = _CLUB + " Homepage Video Content Module";
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: compname,
					compActivity: compname + ": "+tabtext+" Video Click",
					actionGen:true
				}
			});
		});		
		
		// video module		
		$doc.selector = "#video_container .more a";
		$doc.live("click", function(e) {
			var linktext = $(e.target).text(),
				compname = _CLUB + " Homepage Video Content Module";
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: compname,
					compActivity: compname + ": "+ linktext +" Click",
					actionGen:true
				}
			});
		});
	
	
		// releases	
		$doc.selector = "#news_notes_container ul.links_stack li a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Releases",
					compActivity: _CLUB + " Homepage Releases: Press Release Click",
					actionGen:true
				}
			});
		});		
		$doc.selector = "#news_notes_container ul.hp_related_links li a:contains('Game Notes')";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Releases",
					compActivity: _CLUB + " Homepage Releases: Game Notes Click",
					actionGen:true
				}
			});
		});		
		$doc.selector = "#news_notes_container ul.hp_related_links li a:contains('More Releases')";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Releases",
					compActivity: _CLUB + " Homepage Releases: More Releases Click",
					actionGen:true
				}
			});
		});
		
		
		// standings
		$doc.selector = "#standings_container td.first a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Standings",
					compActivity: _CLUB + " Standings: Club Click",
					actionGen:true
				}
			});
		});
		
		$doc.selector = "#standings_container #standings_link_all";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Standings",
					compActivity: _CLUB + " Standings: Expanded Standings Click",
					actionGen:true
				}
			});
		});
		
		// 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
				}
			});
		});
		$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
				}
			});
		});
		
		//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
				}
			});
		});			
		$("#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
				}
			});
		});
		$("#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
				}
			});
			return false;
		});	
		$doc.selector = "#vertical_container li a";
		$doc.live("click", function(e) {
			var $target = $(e.target).closest("li"),
				items = $target.closest(".carousel_container").find("ul").not(".isClone").find("li"),
				idx = items.index($target);
			idx++;			
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Promotions",
					compActivity: _CLUB + " Promotions: Panel " + idx + " Click",
					actionGen:true
				}
			});
		});		
		
		// 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
				}
			});
		});
		
		// photos
		$doc.selector = "#photo_container #photo_blurbs li a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Photos",
					compActivity: _CLUB + " Homepage Photos: Gallery Click",
					actionGen:true
				}
			});
		});	
		
		$doc.selector = "#photo_container #photo_store a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Photos",
					compActivity: _CLUB + " Homepage Photos: Photo Store Click",
					actionGen:true
				}
			});
		});	
		
		$doc.selector = "#photo_container .more a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Photos",
					compActivity: _CLUB + " Homepage Photos: More Photos Click",
					actionGen:true
				}
			});
		});		
		
		// connect
		$doc.selector = "#connect_container .connect_content .mobile a:contains('Download now')";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Connect",
					compActivity: _CLUB + " Homepage Connect: Mobile Download Click",
					actionGen:true
				}
			});
		});
		
		$doc.selector = "#connect_container .connect_content .mobile .middle a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Connect",
					compActivity: _CLUB + " Homepage Connect: Mobile Link Click",
					actionGen:true
				}
			});
		});
		
		$doc.selector = "#connect_container .connect_content .mobile a.bam-button-mobile";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Connect",
					compActivity: _CLUB + " Homepage Connect: Mobile Alert Sign Up",
					actionGen:true
				}
			});
		});			
		
		$doc.selector = "#connect_container .connect_content .facebook a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Connect",
					compActivity: _CLUB + " Homepage Connect: Facebook Link Click",
					actionGen:true
				}
			});
		});		
		
		$doc.selector = "#connect_container .connect_content .twitter #main_feed a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Connect",
					compActivity: _CLUB + " Homepage Connect: Twitter Link Click",
					actionGen:true
				}
			});
		});		
		
		$doc.selector = "#connect_container .connect_content .twitter dd a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Connect",
					compActivity: _CLUB + " Homepage Connect: Twitter Follow Click",
					actionGen:true
				}
			});
		});
		
		$doc.selector = "#connect_container .connect_content .twitter .more a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Connect",
					compActivity: _CLUB + " Homepage Connect: Twitter View All Click",
					actionGen:true
				}
			});
		});
		
		$doc.selector = "#connect_container .connect_content .twitter .last a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Connect",
					compActivity: _CLUB + " Homepage Connect: Twitter Social Media Click",
					actionGen:true
				}
			});
		});
		
		// homestand
		$doc.selector = "#homestand_items .tickets a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Next Homestand",
					compActivity: _CLUB + " Homepage Next Homestand: T Link Click",
					actionGen:true
				}
			});
		});
		
		$doc.selector = "#homestand_items .promotions a";
		$doc.live("click", function(e) {
			bam.tracking.track({
				async:{
					isDynamic:false,
					compName: _CLUB + " Homepage Next Homestand",
					compActivity: _CLUB + " Homepage Next Homestand: Promotions Click",
					actionGen:true
				}
			});
		});

		

	},
	
	
	_loadtixpromos = function(cb){
		var props = _self.get("clubprops")[_club],	
			flip = bam.getFlipDisplayDate(_club),
			begin = bam.datetime.formatDate(flip, "yyyyMMdd"),				
			end = bam.datetime.toYMD(bam.datetime.DateTime(flip).incrementMonth(2));
		$.ajax({
			url			: (bam.env.host.isQA) ? "/test/data/ds_tix_5games.json": "/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,
				begin_date: begin, 
				end_date: end
			},		
			success: 	function(response) {									
				var game_arr = bam.util.ensureArray(response.events.game);		
				_self.set("tixpromos",game_arr);
				if($.isFunction(cb)) { cb(); }
			}	
		});				
	},
	
	
	
	
	

	/**
	* 
	*
	* _leaders
	* 
	*
	*/		
	_leaders = (function(){
		var $doc = $(document),
			// _pitchingStats = ["w","sv","so","era","whip"],	
			// _battingStats = ["avg","r","hr","rbi","sb"],				
			_pitchingStats = (_club === "bal" || _club === "min") ? ["w","sv","so"] : ["w","sv","so","era","whip"],				
			_battingStats = (_club === "sea" || _club === "sf" || _club === "hou") ? ["h","r","hr","rbi","sb"] : ["avg","r","hr","rbi","sb"],									
			_season = 2011,
			_isSpringTraining = false,
			_isRegularSeason = true,
			_isPostseason = false,
			_isOffseason = false, 	
			_gameType = (_isPostseason) ? ["'D'","'L'","'W'"] : (_isSpringTraining) ? "'S'" : "'R'",
			_numResults = 3,
			_cache = {},
			_$container,
			_$batters,
			_$pitchers,
		
		_wrapArrValuesWithQuotes = function(arr){
			return $.map(arr, function(n){return "'"+n+"'"; });	
		},

	
		_getRowsHTML = function(stat){			
			var players = _cache[stat],		
				rLen = players.length,	
				loops = (rLen < _numResults) ? _numResults : rLen,	
				side = (~$.inArray(stat,_battingStats)) ? "batting" : "pitching",
				$headshot = $("#leaders_content").find(".leaders_"+side).find(".leaders .headshot"),
				player,
				previousPlayer = players[0], 
				i=0,
				place=1,
				rowHTML = "<div class='leader odd main_leader'>No players qualify</div>",
				tieValue, 
				tieText="players", 
				numTies=0, 
				statValue;
				statsLink = "/stats/individual_stats_player.jsp?c_id=" + _club + "&playerID=";				
			if(rLen) {
				rowHTML="";
				$headshot.show();
			}	
			if(loops > _numResults) {				
				tieValue = players[_numResults][stat];	
				_log("Invoking tie logic. tieValue=" + tieValue);		
				if(players[_numResults-1][stat] === players[_numResults-2][stat]) tieText = "others";			
			}						
			for(;i<loops;i++){									
				if(!(player = players[i])) {
					rowHTML += "<div class='leader leader_none'>";
					rowHTML += (i+1)+". ";
					rowHTML += "No additional qualifiers</div>";
					break;
				}										
				statValue = player[stat];			
				if(statValue === tieValue) numTies++;			
				if(statValue !== previousPlayer[stat]) place = i+1;							
				if(i<_numResults){
					rowHTML += "<div class='leader'>";
					rowHTML += "<div class='leader_name'>";
					rowHTML += place + ". ";					
					if(i===(_numResults-1) && !!numTies) {
						rowHTML += (rLen - (_numResults-1)) + " " + tieText + " tied";		
					} else {				
						rowHTML += players[i].name_last.link(statsLink + players[i].player_id);		
					}			
					rowHTML += "</div><div class='leader_num'>";
					rowHTML += players[i][stat];
					rowHTML += "</div></div>";	
				}
				previousPlayer = player;
			}
			return rowHTML;
		},
	
	
		_write = function(stat){
			_log("_write. stat="+stat);
			var side = (~$.inArray(stat,_battingStats)) ? "batting" : "pitching",
				rows = _cache[stat],
				$c = $("#leaders_content").find(".leaders_"+side).find(".leaders"),
				leader = rows[0],
				i=0,
				//hack to remove player images for NYM only
				//imgSrc = (_club === "nym")? "/images/homepage/team/y2011/logos/nym.png":"/images/players/assets/68_"+leader.player_id+".png" ,
				imgSrc = "/images/players/assets/68_"+leader.player_id+".png" ,
				statsLink = "/stats/individual_stats_player.jsp?c_id=" + _club + "&playerID=";						
						
			$c
				.hide()
				.find("div").remove()
				.end()
				.find(".headshot")
				.hide()
				.attr("href","/team/player.jsp?player_id="+leader.player_id)
				.find("img")
				.attr({
					"src" : imgSrc,
					"alt" : leader.name_last					
				})
				.end().end()
				.append(_getRowsHTML(stat))
				.find(".leader:even").addClass("odd")
				.end()
				.find(".leader:first").addClass("main_leader")
				.end()
				.fadeIn();
				
					
		},

	
	
		_getData = function(stat, callback){
			_log("_getData. stat="+stat);		
			var serviceURL="/lookup/json/named.",						
				serviceParams = {
					"results" : _numResults,
					"season" : _season,
					"game_type" : _gameType,
					"team_id" : bam.clubhome.get("clubprops")[_club].team_id,
					"sort_column" : "'" + stat + "'",
					"sport_code"  : "'mlb'",
					"active_sw"   : "'Y'"
				},
				side = (~$.inArray(stat,_battingStats)) ? "batting" : (~$.inArray(stat,_pitchingStats)) ? "pitching" : "",
				pitching_repeater = (_isSpringTraining) ? "leader_spring_pitching_rptr" : "leader_pitching_repeater",
				batting_repeater = (_isSpringTraining) ? "leader_spring_hitting_rptr" : "leader_hitting_repeater",
				player_info = ["name_last", "player_id"];	
				
			if (side==="batting") {
				serviceURL += batting_repeater + ".bam";
				repeater_columns = (_isSpringTraining) ? {"leader_spring_hitting_rptr.col_in" : _battingStats.concat(player_info)} : {"leader_hitting_repeater.col_in" : _battingStats.concat(player_info)};	
				sort_columns = {"sort_column" : _wrapArrValuesWithQuotes(_battingStats)};
			} else {
				serviceURL += pitching_repeater + ".bam";
				repeater_columns = (_isSpringTraining) ? {"leader_spring_pitching_rptr.col_in" : _pitchingStats.concat(player_info)} : {"leader_pitching_repeater.col_in" : _pitchingStats.concat(player_info)};	
				sort_columns = {"sort_column" : _wrapArrValuesWithQuotes(_pitchingStats)};
			}	
			$.extend( serviceParams, repeater_columns, sort_columns);			
			
			// http://sanfrancisco.giants.mlb.com/lookup/named.leader_hitting_repeater.bam?results=3&season=2011&game_type=%27R%27&team_id=137&sort_column=%27avg%27&sort_column=%27r%27&sort_column=%27hr%27&sort_column=%27rbi%27&sort_column=%27sb%27&sport_code=%27mlb%27&active_sw=%27Y%27&leader_hitting_repeater.col_in=avg&leader_hitting_repeater.col_in=r&leader_hitting_repeater.col_in=hr&leader_hitting_repeater.col_in=rbi&leader_hitting_repeater.col_in=sb&leader_hitting_repeater.col_in=name_last&leader_hitting_repeater.col_in=player_id
			
			$.ajax({
				url: serviceURL,
				data: serviceParams,
    			dataType: "json",
    			error: function(data,status,e){
					_log("error loading stats");
    			},
    			success: function(json){												
					var i=0, statName, curr, 
						parentObj = (side==="batting") ? json[batting_repeater].leader_hitting_mux : json[pitching_repeater].leader_pitching_mux;		
					for(;i<parentObj.length;i++){
						curr = parentObj[i];
						statName = curr.sort_column.replace(/\'/g,"");											
						_cache[statName] = bam.util.ensureArray(curr.queryResults.row);					
					}					
					_log("Data loaded. Stat = " + stat + ". Displaying cache below");
					_log(_cache);
					if($.isFunction(callback))callback();				
				} 
			});	
		},
	
	
		
		
		_writeNav = function(bRand, pRand){
			var b=0, p=0, liStr="", stat="";		
			for(;b < _battingStats.length; b++){		
				stat=_battingStats[b];	
				liStr += "<li data-stat='"+stat+"'>"+stat+"</li>";						
			}
			_$batters.find("ul").append(liStr).end().find("li:eq("+bRand+")").addClass("active");			
			liStr="";
			for(;p < _pitchingStats.length; p++){
				stat=_pitchingStats[p];
				liStr += "<li data-stat='"+stat+"'>"+stat+"</li>";				
			}
			_$pitchers.find("ul").append(liStr).end().find("li:eq("+pRand+")").addClass("active");		
		},
		
		
		
	 
		_self = {
			init: function(cfg){				
				var bRand = Math.floor(Math.random() * _battingStats.length),
					pRand = Math.floor(Math.random() * _pitchingStats.length);				
				_$container = $("#leaders_container");
				_$batters = _$container.find(".leaders_batting"); 
				_$pitchers = _$container.find(".leaders_pitching");					
				_writeNav(bRand, pRand);								
				_self.load(_battingStats[bRand]);
				_self.load(_pitchingStats[pRand]);
			},
			load: function(stat){		
				_log("_self.load: " + stat);
				if(_cache[stat]) {
					_write(stat);
				} else {
					_getData(stat, function(){						
						_write(stat);
					});
				}
			}	
		};
	
	
		// Events
		$doc.selector = "#leaders_content .top_container ul li";
		$doc.live("click", function(e) {		
			var stat = $(this).data("stat");
			$(this).siblings().removeClass("active").end().addClass("active");
			_self.load(stat);
		});

	           
		return _self; 
	
	})(),   // end _leaders
	
	
	
	
	
	
	/*
	* 
	* _loadMilestones = invoked when the Milestones tab is clicked
	*
	*/	
	_loadMilestones = function(e,idx){		
		var $h3 = $(e.target).closest("h3"),
			$container = $(e.target).closest("#standings_container"),	
			//isMilestones = ($h3.text().toLowerCase() === "milestones");
			isMilestones = ( $h3.hasClass("ms") );
			_log("isMilestones:" + isMilestones);
		if(!isMilestones) return;	// if it's the wrong tab, return	
		_log("_milestones.load.");		
		$container.find(".milestone-container").each(function(n){
			_log("processing milestone " + n);
			var name = $(this).data("name"),
				side = $(this).data("side"),
				id = $(this).data("id"),
				stat = $(this).data("stat"),
				milestone = $(this).data("milestone")*1,
				units = $(this).data("units"),
				$difference = $(this).find(".milestone-difference"), 
				$cd = $(this).find(".milestone-countdown ul"),				
				lookup = "/lookup/json/named.mlb_individual_" + side + "_career.bam?mlb_individual_" + side + "_career.col_in=" + stat + "&player_id=" + id + "&game_type=%27R%27",
				isPopulated = !!$cd.find("li").length;					
			// if it's already populated, return
			if(isPopulated) return;						
			$.getJSON(lookup, function(json) {
				_log(json);
				var currentstat= json["mlb_individual_"+side+"_career"].queryResults.row[stat],
					difference = milestone - ~~currentstat,
					htmlStr = "",
					i=0;					
				for(;i<currentstat.length;i++){
					htmlStr += "<li><span>"+currentstat.charAt(i)+"</span></li>";				
				}
				$cd.html(htmlStr).find("li:last").addClass("last");
				if (difference > 1) {
			   	 	$difference.html(difference + " " + units +" to go");
				} else if (difference == 1) {
					$difference.html("1 " + units.slice(0,-1) + " to go");
				}
			});				
		});	
	},
	

	
	/**
	@
	@
	@
	@ ROOT LEVEL OBJECT
	@
	@
	@
	**/	
	_self = {
		debug: _setDebugging("clubhome"),
		
		playerObj: null,

		init: function(){	
			setTimeout(function(){document.location.reload(true);},1800000); // 30 minute refresh				
			_self.loadprops(function(){
				_videocorner.init.call(_videocorner);
				_leaders.init();
			});							
			_loadtixpromos();
			_navbuttons();							
			_headlines.init();
			_track();
			_videoModule.init();				
			_createCarousel();
			_classInSession();
			
			if( _club === "cle" ){
				//_loadMilestones;
			}
			
												
		},
				
		// setter/getter
		set: function(key,value){
			if(key && typeof(value)!=="undefined") {
				_properties[key]=value;
			}
			_self.trigger("dataLoaded",[key]);
		},
		
		get: function(key) {		
			if(key==="clubprops" && !_properties["clubprops"]) {
				_self.loadprops();
			}		
			return (key && key in _properties)?_properties[key]:null;
		},
		
		/*
		@TODO:
		run loadprops as the page loads
		when dataLoaded fires, init clubhome and gameticker
		dont wait for $.ready
		use $available to init each component		
		*/
		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);}	
			});
		}

			
	};	
	
	$.bindable(_self, "dataLoaded");

	return _self;

})(jQuery);



$(bam.clubhome.init);


