
;(function(){

	bam.loadSync(bam.homePath + "bam.datetime.js");

	var 
	debug = !!bam.url.Location( window.location ).getParam( "debug" ),
	currentShow = bam.url.Location( window.location ).getParam( "content" ),
	//allShows = ["glenn_beck_program", "fourth_hour", "radio_show"],
	searchURL = "/ws/search/MediaSearchService",
	$clipsUL1,
	$clipsUL2,
	_totalPages1,
	_totalPages2,
	_curPage1 = 1,
	_curPage2 = 2,
	_curList,
	searchData = {
		query : currentShow,
		sort : "desc",
		sort_type : "date",
		hitsPerPage : 200,
		src : "vpp"		
	},
	
	
	_log=function(msg){		
		if (debug && typeof console !== "undefined" && !!console.log && !!console.dir) {
			if (typeof msg === "string") console.log("loadShows: "+msg);
			else if (typeof msg === "object") console.dir(msg);
			else console.log(msg);			
		}	
	},
	
	
	
	_handleEmpty = function(){	},
	
	
	
	
	
	
	_renderClips =function(clips/*array*/){
		var 
		i=0, 
		clip,
		episodesHTML = "",
		highlightsHTML = "",
		eventDateStr = "",
		isEpisode,
		calendarEventID = "",
		launchLink = "",
		featureContext = "",
		numEpisodes = 0,
		numHighlights = 0,
		isCollapsed,
		clipsPerPage = 8,					
		thumb,			
		getThumb = function(thumbs){
			var i=0, arr = $.ensureArray(thumbs);
			for(;i<arr.length;i++){
				if(arr[i].type === "7") return arr[i].src;
			}
		};

		$clipsUL1        = $("#episodes_container ul.clips");
		$clipsUL2        = $("#highlights_container ul.clips");				
					
		_log(clips);
		
							
		for(;i<clips.length;i++){
			clip = clips[i];
			isCollapsed = false;
			isEpisode = false;
			eventDateStr = "";
			featureContext = clip.featureContext && clip.featureContext.replace(/\./g, '_' );
			thumb = getThumb(clip.thumbnails);
			/*						
			Episodes will have tags of event_category=show or event_category=special.  All other clips should be considered highlights.						
			Basic pay content will have featureContext=GBTV.DEFAULT. Premium content will have featureContext=GBTV.EXTREME.  
			Any content on the web with a featureContext should launch the Media Player.  All other content plays in the VPP.
			*/						
			// find out if the current clip is an episode or a highlight
			$.each(clip.keywords || [], function(){
				if (this.type === "event_category" && (this.keyword === "show" || this.keyword === "special")) {
					isEpisode = true;
				}							
				if(this.type === "calendar_event_id") {calendarEventID = this.keyword; }	
				if(this.type === "event_date") {eventDateStr = this.keyword; }								
				// grab values for additional keywords here								
			});			
					
			
			
			// filter out events whose air date is in the future (because video doesn't exist for these yet!)
			// @TODO: we need a more dependable way to do this, since there's no guarantee video exists for past dates
			// why are future dated clips showing up in search?		
			var EASTERN_OFFSET = -400,
				EASTERN_TIME = bam.getDateByOffset(EASTERN_OFFSET),
				eventDate = (!!eventDateStr) ? bam.datetime.parseISODate(eventDateStr.substr(0,19)) : 0,						
				airDate = (!!eventDate) ? bam.datetime.formatDate(eventDate,"MM/dd/yy") : clip.date_added;	
				
			if(eventDate > EASTERN_TIME) continue;						
						
			if(featureContext === "GBTV_DEFAULT" || featureContext === "GBTV_EXTREME") {
				launchLink = "javascript:bam.media.launchPlayer({ calendar_event_id : '" + calendarEventID + "', source : 'GBTV', content_id: '" + clip.contentId + "', sponsor : 'GBTV' , media_type : 'video' });";	
			}else{
				launchLink = '/media/video.jsp?content_id='+clip.contentId;						
			}									
									
			_log("isEpisode="+isEpisode);						
									
																
			if(isEpisode){ 						
				numEpisodes++;							
				if(numEpisodes > 8) isCollapsed = true;								
				episodesHTML += ''+
					'<li data-index="'+numEpisodes+'" ' + (isCollapsed ? 'class="collapsed"' : '' ) + '>'+
						'<a href="' + launchLink + '" rel="'+clip.contentId+'">'+		
							//'<img src="'+(!isCollapsed?thumb:'/images/trans.gif')+'"' + (!isCollapsed?'':' data-src="'+thumb+'" class="lazy"') + ' />' +			
							'<img src="'+thumb+'" />' + 					
							'<div class="thumbOverlay ' + featureContext + '"></div>'+							
							'<p>'+clip.kicker+'</p>'+
							'<div class="dateAdded">Air Date: '+airDate+'</div>'+							
							(!!clip.duration?'<div class="duration">Duration: '+clip.duration+'</div>':'')+
						'</a>'+
					'</li>';				
			}else{  
				numHighlights++;							
				if(numHighlights > 4) isCollapsed = true;
				highlightsHTML += ''+
					'<li data-index="'+numHighlights+'" ' + (isCollapsed ? 'class="collapsed"' : '' ) + '>'+									
						'<a href="' + launchLink + '" rel="'+clip.contentId+'">'+									
							// '<img src="'+(!isCollapsed?thumb:'/images/trans.gif')+'"' + (!isCollapsed?'':' data-src="'+thumb+'" class="lazy"') + ' />' +
							'<img src="'+thumb+'" />' + 
							'<div class="thumbOverlay ' + featureContext + '"></div>'+
							'<p>'+clip.kicker+'</p>'+
							'<div class="dateAdded">Air Date: '+airDate+'</div>'+
							'<div class="duration">Duration: '+(clip.duration || 'n/a')+'</div>'+
						'</a>'+
					'</li>';
			}
			
			
			
			

			
		} // end of for loop
		
		
			
		if(!!episodesHTML) {
			$clipsUL1
				.html(episodesHTML)
				.closest(".clips_container")
				.show();
		}else{		
			$clipsUL1
				.closest(".clips_container")
				.hide();
		}
		
		
		if(!!highlightsHTML) {
			$clipsUL2
				.html(highlightsHTML)
				.closest(".clips_container")
				.show();
		}else{		
			$clipsUL2
				.closest(".clips_container")
				.hide();
		}			
					
							
		_totalPages1 = Math.ceil($clipsUL1.find("li").length / clipsPerPage);
		_totalPages2 = Math.ceil($clipsUL2.find("li").length / clipsPerPage);					
		
		// @TODO: turn pagination back on once there are more clips laoded
		// renderPagination();
	
	},
		
		
		
		
		
		
	renderPagination = function(){
		_log("_totalPages1="+_totalPages1+", _totalPages2="+_totalPages2);		
		var p=1,
			episodesHTML = "",
			highlightsHTML = "";										
		if (_totalPages1 > 1){
			episodesHTML += "<button class='dir disabled prev'>prev</button>";
			for (; p<=_totalPages1; p++){
				episodesHTML += "<button class='num " + ((p===1)?"current":"") + "'>"+p+"</button>";
			}
			episodesHTML += "<button class='dir next'>next</button>";			
			$("<div>").addClass("pagination").html(episodesHTML).appendTo($clipsUL1.closest(".clips_container"));
		}			
		if (_totalPages2 > 1){
			highlightsHTML += "<button class='dir disabled prev'>prev</button>";
			for (p=1; p<=_totalPages2; p++){
				highlightsHTML += "<button class='num " + ((p===1)?"current":"") + "'>"+p+"</button>";
			}
			highlightsHTML += "<button class='dir next'>next</button>";
			$("<div>").addClass("pagination").html(episodesHTML).appendTo($clipsUL2.closest(".clips_container"));
		}	
	},	
	
	
	
	showPage = function(p){
		var totalPages = (_curList === 1) ? _totalPages1 : _totalPages2,
			clipsPerPage = (_curList === 1) ? 8 : 4;
		p = parseInt(p,10);			
		if (p<0 || p>totalPages){
			return;
		}	
		$(".clips_container:eq("+(_curList-1)+")")
			// hide current page
			.find("li:not(.collapsed)")
			.addClass("collapsed")
			.end()
			.find( (p>1) ? "li:gt(" + ((p-1)*clipsPerPage-1) + ")" : "*")
			.filter("li:lt("+clipsPerPage+")")
			.removeClass("collapsed")
			.find("img.lazy").each(function(){
				$(this)
					.attr("src", $(this).attr("data-src"))
					.removeClass("lazy");
			});
			if(_curList === 1){
				_curPage1 = p;
			}else{
				_curPage2 = p;
			}	
	},
	
	
	
	updatePagination = function(){
		_log("update pagination. _curList="+_curList+", _curPage1="+_curPage1+", _curPage2="+_curPage2);
		var $dirButtons1 = $(".pagination:eq(0)").find("button.dir"),
			$numButtons1 = $(".pagination:eq(0)").find("button.num"),
			$dirButtons2 = $(".pagination:eq(1)").find("button.dir"),
			$numButtons2 = $(".pagination:eq(2)").find("button.num");
			
			if(_curList === 1){
				$dirButtons1.addClass("disabled");
				if (_curPage1 > 1){
					$dirButtons1.filter(".prev").removeClass("disabled");
				}
				if (_curPage1 < _totalPages1){
					$dirButtons1.filter(".next").removeClass("disabled");
				}
				// update number nav
				$numButtons1
					.removeClass("current")
					.filter(":eq("+(_curPage1-1)+")")
					.addClass("current");
			}else{
				$dirButtons2.addClass("disabled");
				if (_curPage2 > 1){
					$dirButtons2.filter(".prev").removeClass("disabled");
				}
				if (_curPage2 < _totalPages2){
					$dirButtons2.filter(".next").removeClass("disabled");
				}
				// update number nav
				$numButtons2
					.removeClass("current")
					.filter(":eq("+(_curPage2-1)+")")
					.addClass("current");
			}
	
	},
	
	
		
	endOfvarDeclarations;
	
	
	
	
	
	/*
	if(!~$.inArray( currentShow, allShows )){
		_log("currentShow '" + currentShow + "' is not in the allShows array. Exiting.");
		return;
	}
	*/
	

	$(".pagination button.num").live("click", function(){			
		if ($(this).hasClass("current")) return;			
		var p = $(this).siblings(".num").andSelf().index(this);
		_curList = $(".clips_container").index($(this).closest(".clips_container"));				
		p++;	
		_curList++;	
		showPage(p);
		updatePagination();		
	});
			
	$(".pagination button.dir").live("click", function(){
		if ($(this).hasClass("disabled")) return;
		var isPrev    = $(this).hasClass("prev"),
			direction = isPrev ? "Previous" : "Next",
			p;
		_curList = $(".clips_container").index($(this).closest(".clips_container"));
		_curList++;
		if(_curList === 1){
			p   = isPrev ? _curPage1-1 : _curPage1+1;
		}else{
			p   = isPrev ? _curPage2-1 : _curPage2+1;
		}				
		_log("button.dir 2. p="+p+", _curList="+_curList);
		showPage(p);
		updatePagination();
	});

	
	
	

	$.ajax({
		url:		searchURL,
		timeout: 	5000,						
		error: 		function(xhr) {},						
		data:		searchData,	
		dataType: 	"json",
		success: 	function(response) {
			var arr = $.ensureArray(response.mediaContent);
			$(function() {				
				_renderClips(arr);		
			});
		}	
	});
	
	
	
	
	
	
	
	
})();




