/**
* 
* bam.clipstrip
* @author: Caleb Olin
* @created: 4.1.2011
* 
**/

bam.loadSync(bam.homePath + 'bam.gameId.js');

bam.clipstrip = (function($, context){      

	var _container = "#clipstrip",
		_heartbeat = null,
		_refreshInterval = 10000, // 10 seconds. should increase to 30 when this goes live
		$doc = $(document),
		_carouselIndex = 0,
		_autorefresh = true,	
		_expandedHeight = "140px",
		_minClips = 6,
		_compName = "MLB Homepage Video Drawer",		
		
	_log=function(msg){
		if (_self.debug && typeof console !== "undefined" && !!console.log && !!console.dir) {
			if (typeof msg === "string") console.log("ClipStrip: "+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;
	},

	
	_ajaxOptions = {
		type:		"get",
		dataType:	"json",
		timeout: 	5000,
		error: function(xhr) {
			_log("Load error:" + xhr.status);
			_destroy();
		}
	},	
	
	
	_loadRTH = function(){	
		var today = bam.datetime.toYMD(bam.getFlipDate()),
			y = today.substr(0,4),
			m = today.substr(4,2),
			d = today.substr(6,2),
			url = "/gdcross/components/game/mlb/year_"+y+"/month_"+m+"/day_"+d+"/media/highlights_light.json";	
			//url = "/test/data/mock/highlights.json";
		return $.ajax($.extend({url : url},_ajaxOptions));
	},

	
	_loadLLI = function(){
		var url = "/gen/multimedia/livelookin.json";
		return $.ajax($.extend({url : url},_ajaxOptions));
	},
	
	_getAgo = function(lastSave){
		return bam.datetime.DateDiff(bam.EASTERN_TIME, bam.datetime.parseISODate(lastSave));
	},
	
	_write = function(clips,livelookin){
		var i=n=0, str="", gameObj, thisClip, contentid, img, caption, away, home, lastSave, ago, newHTML="",
			lli = livelookin[0] || {},
			$ul = $("#cs_carousel_container ul"),  // @TODO _get these
			numCurrent = $ul.find("li").length,
			len = clips.length;		
		// Live Look In 			
		if(lli.content_id && lli.game_id) {
			gameObj = bam.gameId.game(lli.game_id);			
			str += "<li><a href='javascript:bam.clipstrip.zPlayer.play(";
			str += lli.content_id;
			str += ");' class='cs_llithumb'>LIVE LOOK IN<br />";			
			str += gameObj.awayTeam.display_code.toUpperCase();
			str += " @ "; 
			str += gameObj.homeTeam.display_code.toUpperCase();
			str += "</a>";
			len++;
		}			
		// Real Time Highlights
		for(;i<len && clips[i];i++){
			thisClip = clips[i];
			gameObj = bam.gameId.game(thisClip.game_id);	
			lastSave = thisClip.lastSave.substring(0,thisClip.lastSave.lastIndexOf("-"));					
			ago = _getAgo(lastSave);		
			str += "<li><a href='/mlb/gameday/index.jsp?gid=";
			str += thisClip.game_id.replace(/\//g,"_").replace(/-/g,"_");			
			str += "&highlight_content_id=";
			str += thisClip.contentid;					
			str += "'><img thumb='";
			str += thisClip.thumb;
			str += "'><div class='cs_caption_bg'></div><div class='cs_caption'><strong>"
			str += gameObj.awayTeam.display_code.toUpperCase();
			str += "@";
			str += gameObj.homeTeam.display_code.toUpperCase();
			if (gameObj.gameNum === "2") str += ", G2";
			str += ":</strong> ";
			str += thisClip.headline;
			str += " (";			
			if(ago.TotalMinutes() < 60){
				str += ((ago.TotalMinutes()<1)?"1":ago.TotalMinutes())+"m";
			}else if(ago.TotalHours() < 24){
				str += ago.TotalHours()+"h";					
			} else {
				str += ago.TotalDays()+"d";	
			}
			str += " ago)</div><div class='cs_video_play'></div></a></li>";			
		}	
		$ul.find(".cs_caption").removeClass("cs_notify");
		if(len !== numCurrent){	
			$.available("#cs_carousel_container ul", true, function(){					
				$(this).html(str);					
				var carouselStart = (numCurrent) ? len-numCurrent : 0;
				if(carouselStart<0)carouselStart=0;
				_createCarousel({
					start: carouselStart
				});				
			});		
		}	
	},
	

	
	_createCarousel = function(props){
		var LLIexists = false,
			btnNext = "#cs_arrow_right",
			btnPrev = "#cs_arrow_left";
		$("#cs_carousel").jCarouselLite = null;		
		$(btnNext).unbind("click");	
		$(btnPrev).unbind("click");		
		$("#cs_carousel")			
			.jCarouselLite({
	   			btnNext: btnNext,
	   			btnPrev: btnPrev,
				visible: 6,
				easing: "easeOutCirc",
				speed: (props.start>0) ? 1200 : 600,
				circular: false,
				scroll: 1,
				start: props.start || _carouselIndex,				
				afterEnd: function(elem){
					// preserve carousel index on refresh		
					_carouselIndex = elem.parent().children().index(elem);	
					_loadThumbs(elem);	
					if(props.start > 0){					
						LLIexists = (elem.find(".cs_llithumb").length)						
						if(LLIexists && props.start>=1){
							elem.eq(1).find(".cs_caption").addClass("cs_notify");
						} else if(!LLIexists) {
							elem.eq(0).find(".cs_caption").addClass("cs_notify");
						}						
						setTimeout(function(){$(btnPrev).trigger("click");},10);
						props.start--;
					}					
				},
				afterInit: function(elem){				
					_loadThumbs(elem);					
					// logic for post-init  animations
					if(props.start > 0) $(btnPrev).trigger("click");		
					// tracking for arrow clicks
					$(btnNext + ", " +btnPrev).click("click",function(){
						var theID = $(this).attr("id"),
							tracking = (theID == "cs_arrow_left") ? "Previous" : "Next";						
						bam.tracking.track({
							async:{
								isDynamic: 		true,
								compName: 		_compName,	
								compActivity:	_compName + ": " + tracking + " Click",
								actionGen: 		true
							}
						});								
					});
				}
			});				
	},
	
	/*
	* load clip thumbnails when they're visible (and not before!)
	*/
	_loadThumbs = function(elem){
		var imgsrc="";
		elem.find("img[thumb]").each(function(){
			imgsrc = $(this).attr("thumb");
			$(this).hide().attr("src",imgsrc).removeAttr("thumb").fadeIn();
		});
	},

	_destroy = function(){
		_log("_destroy");
		$("#clipstrip").animate( {height:"0"}, 2000); 
	},
	
	
	/*
	* show the clip strip if the following conditions are met:
	* 
	* number of highlights >= 6
	* number of games represented >= 2
	* most recent clip is < 1 hour old
	* 
	*/
	_testData = function(highlightsArr){
		var i=0, rLen = highlightsArr.length, minHighlights = 6, highlight, gameid, minGames=2,  gamesArr=[], isFresh=false, lastSave,		
			hasEnoughGames = function(){
				return gamesArr.length >= minGames;
			};		
		if(rLen < minHighlights) return false;	
		for(; i < rLen; i++){
			highlight = highlightsArr[i];
			gameid = highlight.game_id;		
			lastSave = highlight.lastSave.substring(0,highlight.lastSave.lastIndexOf("-"));
			if(isFresh && hasEnoughGames()) {
				_log("Data passes the test!");
				return true;
			} 			
			if(!isFresh && _getAgo(lastSave).TotalHours() < 1) {
				_log("Data is fresh enough.");
				isFresh=true;
			}	
			if(!hasEnoughGames() && !~$.inArray(gameid, gamesArr)){
				_log("Testing data: adding game id " + gameid);
				gamesArr.push(gameid);
			}
		}
	},
	
	_loadClips = function(cb){
		$.when(_loadRTH(),_loadLLI())
			.done(function(RTHResults, LLIResults){				
				var highlights = RTHResults[0].highlights.reverse(),
					LLI = LLIResults[0].media,
					totalClips = highlights.length + LLI.length,
					isValid = _testData(highlights);					
				if(isValid) {				
					$("#clipstrip").animate( {height:_expandedHeight}, 2000, "easeOutCirc", function(){
						_write(highlights, LLI);
						if(totalClips === _minClips) $("#clipstrip").find(".cs_arrow_left, .cs_arrow_right").hide();	
						_self.trigger("Launch");
					});					
				} else {
					_destroy();
				}				
			})
			.then(cb)
			.fail(_destroy)
	},
	
	// Custom zPlayer configuration (see bam.zPlayer.js for more)
	_zPlayer = {
    	containerId:          'LiveLookinPlayer',
		playerObjName:        'bam.widget.LiveLookIn.zPlayer.flashPlayer',
		pageComponent:        'liveLookinZPlayer', // custom name for FreeWheel targeting
		replayImgUrl:         '/images/000000.gif',
		bgImageUrl:           '/scripts/lookin/bg.png',
		cssUrl:               '/scripts/lookin/lookin.css',
		redirectBadBrowsers:  false
    },
	
	_self = {
		debug: _setDebugging("clipstrip"),
		init: function(props){		
			_log("initializing");							
			_loadClips(function(){
				if(_autorefresh) _heartbeat = setInterval( _loadClips, _refreshInterval );				
			});					
			// Initialize Live Look-In zPlayer 
        	_self.zPlayer = new bam.ZPlayer(_zPlayer);
		},
		stop: function(){
			clearInterval(_heartbeat);		
		},
		destroy: function(){
			_destroy();
		}		
	};
	
	
	// tracking	
	$doc.selector = "#cs_carousel li a";
	$doc.live("click", function(e) {		
		var $target = $(e.target).closest("a"),   ///make sure we have the right hook
			tracking = ($target.hasClass("cs_llithumb")) ? "LLI" : "Highlight";		
		bam.tracking.track({
			async:{
				isDynamic: 		false,
				compName: 		_compName,	
				compActivity:	_compName + ": " + tracking + " Click",
				actionGen: 		true
			}
		});		
	});
	
	$.bindable(_self, "Launch");
	
	_self.one("Launch",function(e){
		bam.tracking.track({
			async:{
				isDynamic: 		true,
				compName: 		_compName,	
				compActivity:	_compName + ": Launch",
				actionGen: 		false
			}
		});	
	});	
	
			
	return _self;	
	
	                          
})(jQuery, bam.mlbhome || bam.clubhome || {});


/*
**********************************
********** KILL SWITCH: **********
**********************************
*/
bam.clipstrip.DISPLAY_CLIPSTRIP = false;  // change this to false to turn off the clip strip



$(function() {
	if(!!bam.clipstrip.DISPLAY_CLIPSTRIP) setTimeout(bam.clipstrip.init,5000);
});

	





