if ( window.console == undefined || window.console.log == undefined ) {	window.console = { log:function(msg){ /* msg */ } } }
if ( typeof(window.billboard)=="undefined"){ billboard={}; }
billboard.video = new ( function($) {
    var me = this;
	var brightCoveURL="http://www.billboard.com/3rdparty/data/brightcove/services/library?command=";
	me.videoTitle = "";
	me.init = function(){
		billboard.broadcaster.addListener( "pageLoaded", function() { me.onPageLoaded(); } );
		
			
    };
    me.onPageLoaded = function(){
		
		
		// For Billboard Archive
		if(billboard.subsection=='archive-search') {
			billboard.log('Only for Archive Search Page');
			search();	
			
		}
		if(billboard.subsection=='archive-read') {
		 initialize();			
		}
		
		
		
		// End Archive
		
		billboard.log("Video.init");
		$('.video-sub a').click(function(){
			
		$(this).parents('ul').find('li').each(function(){
		
			var classBefore=$(this).attr('class');			
			if(classBefore.indexOf('-hover')>-1){						
			$(this).removeClass(classBefore);
			$(this).addClass(classBefore.replace('-hover',''));

			}
		});
		
		var classNow=$(this).parent().attr('class');		
		$(this).parent().removeClass(classNow).addClass(classNow+'-hover');
		
		var checkVideoType=$(this).html();
		 if(checkVideoType=='Most Popular')
		    me.getMostPopularVideo();
		 else if (checkVideoType=='Most Recent')
		     me.getAllVideo();
		 else if (checkVideoType=='Mashup Mondays')
		     me.getMashUpMondayVideo();
		 else if (checkVideoType.search('BBMA')>=0)
		     me.getBBMAVideo();
		/* else if (checkVideoType=='Daily Noise')
		     me.getDailyNoiseVideo(); */
		 else if (checkVideoType.search('Artist Q')>=0)
		     me.getArtistQAVideo();
		 else if (checkVideoType=='Live')
		     me.getLiveVideo();

		 $(".video-list .result").hide();
		 $("#video-list-container").empty();
		  $(".video .list-container .loading-results").show();
		
		return false;
		
		
		});
		
		
		
		//Video search
		$("#video-search-input").focus( function() {
			if($(this).val() == 'Find Videos') $(this).val('');
			$("#video-search-box .search-field-container").css({backgroundPosition:"0 -29px"});
		});

		$("#video-search-input").blur( function() {
			$("#video-search-box .search-field-container").css({backgroundPosition:"0 0"});
		});

		$("#video-search-form").submit( function() { 
			  var keyword = $("#video-search-input").val();
			  if(keyword!="" && keyword!= "Find Videos") {
				  newKeyord = keyword.replace(/[\/]/g, " "); 
				  hash = "/video/search/"+newKeyord;
				  billboard.navigateToUrl( hash );				  
				  googleA.trackEvent(5, "Video Search", keyword);
			  }
			  
			  return false;
		 });

		$("#video-search-input").keypress(function(e){
			if (e.which == 13){
				$("#video-search-form").submit();
				return false;
			}
	
		});	
			
			$("#archive-search-input").focus( function() {
			if($(this).val() == 'Search Magazine Archives') $(this).val('');
			$("#archive-search-box .search-field-container").css({backgroundPosition:"0 -29px"});
		});

		$("#archive-search-input").blur( function() {
			$("#archive-search-box .search-field-container").css({backgroundPosition:"0 0"});
		});
			$("#archive-search-form").submit( function() { 
			  var keyword = $("#archive-search-input").val();
			  if(keyword!="" && keyword!= "Search Magazine Archives") {
				  newKeyord = keyword.replace(/[\/]/g, " "); 
				  hash = "/archive/search/"+newKeyord;
				  billboard.navigateToUrl( hash );				  
				  googleA.trackEvent(5, "Archive Search", keyword);
			  }
			  
			  return false;
		 });

		$("#archive-search-input").keypress(function(e){
			if (e.which == 13){
				$("#archive-search-form").submit();
				return false;
			}
	
		});	
		//End video search
		
		
		$('.play-video').live('click', function() {
			if($(this).find('p.video-id').html()!=null && $(this).find('p.video-id').html()!="") {
				hash = "/video/id/"+$(this).find('p.video-id').html();
				billboard.navigateToUrl( hash );
			}
			return false;
		});
		$("#video-list-container .play-video, #rc-video .most-container .play-video").live("mouseover", function(event) {
				$(this).addClass("video-hover");
		});
		$("#video-list-container .play-video, #rc-video .most-container .play-video").live("mouseout", function(event) {
				$(this).removeClass("video-hover");
		});
		
		
		$('.video-rc-popular').click(function(){
			$('#video-recent-container').hide();
			$('#video-popular-container').show();
			$(this).parent().find(".active").removeClass("active");
			$(this).addClass("active");
		});
		
		$('.video-rc-recent').click(function(){
		    $('#video-popular-container').hide();
			$('#video-recent-container').show();
			$(this).parent().find(".active").removeClass("active");
			$(this).addClass("active");
					
		});

		
		if(billboard.subsection=='video-landing') {
			me.getFeauturedVideo('featuredVideo1');
			me.getFeauturedVideo('featuredVideo2');
			me.getFeauturedVideo('featuredVideo3');
			me.getFeauturedVideo('featuredVideo4');
			me.getFeauturedVideo('featuredVideo5');		
			
			me.getAllVideo();
					
		}
		
		if(billboard.subsection=='video-search'){
			
			$('.video-sub li.most-recent-hover').removeClass('most-recent-hover').addClass('most-recent');
			document.title=($('#video-search-term').html()).replace(/%20/g," ")+" - Video Search Results | Billboard.com"; 
			
			var VideoSearchTerm=$('#video-search-term').html();
			VideoSearchTerm=VideoSearchTerm.replace(/\s+/g,"+");
			VideoSearchTerm=VideoSearchTerm.replace(/%20/g,"+");
			
			var isTagSearch=$('#video-search-tag').html();
			
			if(isTagSearch=true && isTagSearch!=null)
				me.getVideoByTag(VideoSearchTerm);
			else				
				me.getVideoBySearch(VideoSearchTerm);			
		}
		
		if(billboard.subsection=='video-play'){
			var id=$('#id-video').html();
			var videoURL = "";

			if($("#fb-share-video object").attr("data"))
				videoURL = $("#fb-share-video object").attr("data");
			else{
				$("#fb-share-video object param").each(function(){
					if($(this).attr("name").toUpperCase() == 'MOVIE')
						videoURL = $(this).attr("value");
				});
			}

			me.getVideoByID(id, function(imgURL){
				$("#fb-share-video").append('<meta name="medium" content="video" />');
				$("#fb-share-video").append('<link rel="image_src" href="'+ imgURL +'" />');
				$("#fb-share-video").append('<link rel="video_src" href="'+ videoURL +'" />');
				$("#fb-share-video").append(' <meta name="video_height" content="336" />');
				$("#fb-share-video").append(' <meta name="video_width" content="385" />');
				$("#fb-share-video").append(' <meta name="video_type" content="application/x-shockwave-flash" />');
			});	
			me.getRelatedVideo(id);
			me.getMostPopularRC();
			me.getMostRecentRC();
			
			$('.video-tag-link').live("click",function(event) {
				var tagSearchUrl=$(this).attr('href');				
				tagSearchUrl=tagSearchUrl.substring(tagSearchUrl.indexOf('/bbcom'),tagSearchUrl.length);
				billboard.navigateToUrl(tagSearchUrl);
				return false;
				
		    });
			
			
		}
		
     }

	

    me.getFeauturedVideo=function (featuredVideo) {
		
		$.getJSON( brightCoveURL+"find_videos_by_tags&or_tags="+featuredVideo+"&page_size=1&sort_by=CREATION_DATE&sort_order=DESC&callback=?", function(data,status) {
					
					var name,desc;
					if(data["items"].length>0) {
						name = (data.items[0].name.length > 30) ? (data.items[0].name.substring(0,30) + "...") : data.items[0].name ;
						desc = (data.items[0].shortDescription.length > 75) ? (data.items[0].shortDescription.substring(0,75) + "...") : data.items[0].shortDescription ;
						$('#'+featuredVideo).find('img').attr('src',data.items[0].videoStillURL);
						$('#'+featuredVideo+' p.video-title').html(name);
						$('#'+featuredVideo+' p.video-description').html(desc);				
						$('#'+featuredVideo+' p.video-id').html(data.items[0].id);
					
					}
			/*		else {
					$('#'+featuredVideo).hide();
					
					
					}
			*/		
							
					
				});

	}
	
	me.getAllVideo=function () {

		$.getJSON( brightCoveURL+"find_all_videos&page_size=30&sort_by=publish_date&callback=?", function(data,status) {
					
				me.updateVideoContainer(data);
					
				});

	}
	
	me.getMostPopularVideo=function () {
		
		$.getJSON( brightCoveURL+"find_all_videos&page_size=30&sort_by=PLAYS_TRAILING_WEEK&sort_order=DESC&callback=?", function(data,status) {
					
				me.updateVideoContainer(data);
					
				});

	}
	
	me.getMashUpMondayVideo=function () {
	
			
		$.getJSON( brightCoveURL+"find_videos_by_tags&or_tags=Mashup+Mondays&page_size=30&sort_by=publish_date&callback=?", function(data,status) {
					
				me.updateVideoContainer(data);
					
				});

	}

	me.getBBMAVideo=function () {
	
			
		$.getJSON( brightCoveURL+"find_videos_by_tags&or_tags=bbma&page_size=30&sort_by=publish_date&callback=?", function(data,status) {
					
				me.updateVideoContainer(data);
					
				});

	}
	
/*	me.getDailyNoiseVideo=function () {

		
		$.getJSON( brightCoveURL+"find_videos_by_tags&or_tags=The+Daily+Noise&page_size=30&sort_by=publish_date&callback=?", function(data,status) {
					
				me.updateVideoContainer(data);
					
				});

	}
*/
	
	me.getArtistQAVideo=function () {

		
		$.getJSON( brightCoveURL+"find_videos_by_tags&or_tags=Interview&page_size=30&sort_by=publish_date&callback=?", function(data,status) {
								
				me.updateVideoContainer(data);
					
				});

	}
	
	me.getLiveVideo=function () {

		$.getJSON( brightCoveURL+"find_videos_by_tags&or_tags=performance&page_size=30&sort_by=publish_date&callback=?", function(data,status) {
					
				me.updateVideoContainer(data);
					
				});

	}
	
	me.getVideoBySearch=function (searchTerm) {
		var recentDate=true;
		$.getJSON( brightCoveURL+"find_videos_by_text&text="+searchTerm+"&page_size=30&sort_by=creation_date&sort_order=DESC&callback=?", function(data,status) {
		me.updateVideoContainer(data,recentDate); //by deafult results shown by publish date, so pass recentDate true
					
				});

	}
	
	me.getVideoByTag=function (searchTerm) {
		
		$.getJSON( brightCoveURL+"find_videos_by_tags&or_tags="+searchTerm+"&page_size=30&sort_by=publish_date&sort_order=DESC&callback=?", function(data,status) {
		me.updateVideoContainer(data);
					
				});

	}
	
	me.getVideoByID=function (id, callback) {
		
		$.getJSON( brightCoveURL+"find_video_by_id&video_id="+id+"&callback=?", function(data,status) {
			me.updateVideoInfo(data);
			if(callback) callback(data.thumbnailURL);
					
				});

	}
	
	me.getRelatedVideo=function (id) {
		
		$.getJSON( brightCoveURL+"find_related_videos&video_id="+id+"&page_size=4&callback=?", function(data,status) {
			me.updateRelatedVideo(data);
					
		});

	}
	
	me.getMostPopularRC=function () {
		
		$.getJSON( brightCoveURL+"find_all_videos&page_size=10&sort_by=plays_total&sort_order=DESC&callback=?", function(data,status) {
					
				me.updateMostPopularRC(data);
					
		});

	}
	
	me.getMostRecentRC=function () {
		
		$.getJSON( brightCoveURL+"find_all_videos&page_size=10&sort_by=publish_date&callback=?", function(data,status) {
					
				me.updateMostRecentRC(data);
					
		});

	}
	
	
	
	me.updateVideoContainer=function(data,recentDate){
		$(".video .list-container .loading-results").hide();

		if((data.items).length<1) {
		$("#video-list-container").html('<p class="sorry">Sorry No matching videos found !</p>');
		$("#video-list-container").css('display','block');
		return;
		}
		
		if(recentDate){
			
			var sortFunc = function( a, b ) { 
					return (a.creationDate>b.creationDate)?(-1):(b.creationDate>a.creationDate)?(1):(0); 
				}
			
			data.items.sort( sortFunc );		
		
		} //to sort by creation date
		
		var name,imgSrc,desc,elem;
			for (var i=0; i<data["items"].length; i++) {
				 name = (data.items[i].name.length > 30) ? (data.items[i].name.substring(0,30) + "...") : data.items[i].name ;
				 imgSrc = data.items[i].videoStillURL ;
				 desc = (data.items[i].shortDescription.length > 41) ? (data.items[i].shortDescription.substring(0,41) + "...") : data.items[i].shortDescription;
				 elem=$('#video-list-temp').clone();
			     elem.removeAttr("id");
				 elem.find('img').attr('src',imgSrc);
				 elem.find("p.video-title").html(name);
				 elem.find("p.video-description").html(desc);
				 elem.find("p.video-id").html(data.items[i].id);							 
				 elem.show();
				 $("#video-list-container").append( elem );
			}
		$("#video-list-container").css('display','block');
		
	
	}
	
	me.updateVideoInfo=function(data){
	
		var name,desc,elem;
		var tags=new Array();
		var reducedTagArray=new Array();
		
			 name = data.name;
			 document.title=name+" | Billboard.com";		
			 me.videoTitle = name;
			 desc = data.shortDescription;
			 tags = data.tags;
			 
			 $("h1.video-title-header").html(name+" | Video");
			 elem=$('#video-info-temp').clone();
			 elem.removeAttr("id");			 
			 elem.find("p.video-info-title").html(name);
			 elem.find("p.video-info-desc").html(desc);
			
			
			 if(typeof tags!='undefined' && tags.length>0) {

       /* for(count in tags){ */
			  for (var count=0; count<tags.length; count++) {	
          if(tags[count].indexOf('featuredVideo')<0){
            reducedTagArray.push(tags[count]);
          }
			  }
			  reducedTagArray= reducedTagArray.length>5?reducedTagArray.slice(0,5):reducedTagArray;
			  var tagHtmlBefore='',tagHtml='';
			 
				/* for(i in reducedTagArray){ */
        for (var i=0; i<reducedTagArray.length; i++) {	
						 tagHtmlBefore="<span class='lbl'>Tags: </span><span class='tags-list'>" ;
						 tagHtml+='<a class="video-tag-link" href="/video/search/'+reducedTagArray[i]+'?tagSearch=true">'+reducedTagArray[i]+'</a>';
						 if(i<reducedTagArray.length-1 )
						  tagHtml+=", ";
				}
				if(reducedTagArray.length > 0)
					tagHtml += "</span>";
				elem.find(".video-info-tags").html(tagHtmlBefore+tagHtml);	
			 }
			
			 elem.show();
			 $("#video-info-container").append( elem );
			
		$("#video-info-container").css('display','block');
		
	
	}
	
	me.updateRelatedVideo=function(data){
	
		var name,imgSrc,desc,elem;		
			for (var i=0; i<data["items"].length; i++) {
				 name = (data.items[i].name.length > 35) ? (data.items[i].name.substring(0,35) + "...") : data.items[i].name ;
				 imgSrc = data.items[i].videoStillURL ;
				 desc = (data.items[i].shortDescription.length > 44) ? (data.items[i].shortDescription.substring(0,44) + "...") : data.items[i].shortDescription;
				 elem=$('#related-video-temp').clone();
			     elem.removeAttr("id");
				 elem.find('img').attr('src',imgSrc);
				 elem.find("p.video-title").html(name);
				 elem.find("p.video-description").html(desc);
				 elem.find("p.video-id").html(data.items[i].id);							 
				 elem.show();
				 if( i+1 == data["items"].length) elem.css({'margin-right': '0'});
				 $("#related-video-container").append( elem );
			}
		$("#related-video-container").css('display','block');
	
	}
	
	me.updateMostPopularRC=function(data){
	
		var name,imgSrc,desc,elem;		
			for (var i=0; i<data["items"].length; i++) {				 
				 name = (data.items[i].name.length > 35) ? (data.items[i].name.substring(0,35) + "...") : data.items[i].name ;
				 imgSrc = data.items[i].videoStillURL ;
				 desc = (data.items[i].shortDescription.length > 44) ? (data.items[i].shortDescription.substring(0,44) + "...") : data.items[i].shortDescription;
				 elem=$('#popular-rc-temp').clone();
			     elem.removeAttr("id");
				 elem.find('img').attr('src',imgSrc);
				 elem.find("p.video-title").html(name);
				 elem.find("p.video-description").html(desc);
				 elem.find("p.video-id").html(data.items[i].id);							 
				 elem.show();
				 $("#video-popular-container").append( elem );
			}
		$("#video-popular-container").css('display','block');
	
	}
	
	me.updateMostRecentRC=function(data){
	
		var name,imgSrc,desc,elem;		
			for (var i=0; i<data["items"].length; i++) {				 
				 name = (data.items[i].name.length > 35) ? (data.items[i].name.substring(0,35) + "...") : data.items[i].name ;
				 imgSrc = data.items[i].videoStillURL ;
				 desc = (data.items[i].shortDescription.length > 44) ? (data.items[i].shortDescription.substring(0,44) + "...") : data.items[i].shortDescription;
				 elem=$('#recent-rc-temp').clone();
			     elem.removeAttr("id");
				 elem.find('img').attr('src',imgSrc);
				 elem.find("p.video-title").html(name);
				 elem.find("p.video-description").html(desc);
				 elem.find("p.video-id").html(data.items[i].id);							 
				 elem.show();
				 $("#video-recent-container").append( elem );
			}
	
	
	}
	
	
})(jQuery);


