var Vevo = window.Vevo || {};

Vevo.PlaylistWatch = (function() {
	var $nowPlaying, $toggle, $flyout, $scroller, $trackList, $tracks, $firstTrack, $lastTrack, $newTrack; // set on init
	var playlist = [];
	var playlistLength = 0;
	var vIndex = 0;
	//var playerAvailable = false;
	var inFullScreen = false;
	var autoAdvance = true;

	// set the "Now Playing" HTML to the current video
	function setNowPlaying() {
		if (!Vevo.VideoPlayer.isFullscreen) {
//			var favVideo = $('#fav-video').removeClass('fav').attr('title','favorite this video');
			vIndex = parseInt(window.location.hash.split("#")[1]); 
			vIndex = isNaN(vIndex)?0:vIndex;
			playPosition = vIndex;
			var c_isrc = Vevo.pageData.videos[vIndex];
			Vevo.pageData.isrc = c_isrc;
//			var favSuccess = function(data){
//				if (data.length>0 && data[0].IsFavorite && data[0].IsFavorite==true){
//					favVideo.addClass('fav').attr('title','unfavorite this video');
//				}
//			};
//			$.post('/Proxy/User/Favorite/IsFavorite.ashx?_='+Vevo.playbar.playList.salt(), { t : 'Video', q : c_isrc} ,favSuccess, 'json');
			var writeVideoInfo = function(data) {
				Vevo.pageData.videosHash = data;
				var vid = data[c_isrc], artistsInfo = $('div.playlist-title div.currently-playing span.artists').html('').attr('title',''), videsInfo = $('div.playlist-title div.currently-playing span.video-title').html(vid.video_name);
				if (vid.byline_links){
					$(vid.byline_links).appendTo(artistsInfo);
				}
				else{
					$.each(vid.artists, function(i, artist){
						if (i>0){ 
							if (i + 1 == vid.artists.length){ $('<span>&nbsp;and&nbsp;</span>').appendTo(artistsInfo) }
							else{ $('<span>,&nbsp;</span>').appendTo(artistsInfo); }
						}
						$('<a href="'+artist.artist_url+'">'+artist.artist_name+'</a>').appendTo(artistsInfo);
					});
				}
				$('.currently-playing .video-title').vevoEllipsis({type: 'txtWidth', max: 500});
				$('.currently-playing .artists').vevoEllipsis({type: 'domHeight', context: '.currently-playing', max: 18});
				Vevo.PlaylistWatch.setupMoreFromThisArtist(vid);
				Vevo.PlaylistWatch.playlistTab.updateGrid();
				// credits
				var au = vid.artists[0].artist_url, u = vid.video_url, cu = vid.canonical_url, $crd = $('#Credits');
				$crd.load(u+' ul.videoCredits');
				// Facebook Like
				Vevo.Facebook.renderLikeButton('FacebookLikeButton', document.location.protocol + '//' + document.location.host + cu);
				Vevo.Facebook.renderCommentWidget('Comments', document.location.protocol + '//' + document.location.host + cu, c_isrc, vid.og_title);
				$('.social-area .view-count .number').text(vid.view_count);
			}
			if (Vevo.pageData.videosHash!=null){ writeVideoInfo(Vevo.pageData.videosHash); }
			else{ $.getJSON('/Proxy/Video/GetData.ashx', { isrc: Vevo.pageData.videos.toString() }, writeVideoInfo); }
			if (vIndex==0){ $('#prevInList').css('opacity',0); }
			else{ $('#prevInList').css('opacity',0.66); }
			if (vIndex==(Vevo.pageData.videos.length-1)){ $('#nextInList').css('opacity',0); }
			else{ $('#nextInList').css('opacity',0.66); }
			if ($('#dialog-create-new-playlist').dialog('isOpen')){
				$('#dialog-create-new-playlist').dialog('close'); 
			}
			
		}
	} // PlaylistWatch.setNowPlaying

	function setupWatchListAgain(){
			$('div.scrollable-wrapper ul.items li').remove();
			$.each(Vevo.PlaylistWatch.nowplaying, function(i,t){
				t.appendTo($('div.scrollable-wrapper ul.items'));
			});
			var api = $("#playbar div.scrollable").scrollable(); api.reload(); api.seekTo(0);
			$("#playbar div.scrollable ul").css('left',0);
			Vevo.PlaylistWatch.nowplaying = null;
			$('a.now-playing',Vevo.playbar.$pbar).trigger('click');
	}

	function nextHandler(ev, param) {
		//window.console && console.log && console.log(param);
		/* Called by click, so no need to check autoAdvance */
		if (param == null) {
			ev.preventDefault();
			$(this).trigger('blur');
		} else { if (!autoAdvance) { return; } }
		if (Vevo.PlaylistWatch.nowplaying!=null){ setupWatchListAgain(); }
		try { if (Vevo.VideoPlayer.isAvailable()) { $('#Playlist div.playlist-grid li.now-playing').next().trigger('click'); } }
		catch (ex) { /* Player API not available */ }
	}

	function prevHandler(e) {
		/* Called by click, so no need to check autoAdvance */
		if (e) {
			e.preventDefault();
			$(this).trigger('blur');
		} else { if (!autoAdvance) { return; } }
		try { if (Vevo.VideoPlayer.isAvailable()) { $('#Playlist div.playlist-grid li.now-playing').prev().trigger('click'); } }
		catch (ex) { /* Player API not available */ }
	}


	function initTrackList(data, startIndex) {
		playlist = data.videos;
		playlistLength = playlist.length;

		if (isNaN(parseInt(startIndex))) { vIndex = 0; }
		else { vIndex = parseInt(startIndex); }

		// Sets the starting video
		window.location.hash = vIndex;
		
		setNowPlaying();
	} // PlaylistWatch.initTrackList
	
	return {
		init: function(e, data, startIndex) {

			initTrackList(data, startIndex);

			$('#nextInList').bind('click', nextHandler);
			$('#prevInList').bind('click', prevHandler);
			
//			$(Vevo).bind('favorite-change', function(ev, type, fav){
//				if (type=="fav-playlist"){
//					if (fav){ Vevo.PlaylistWatch.setPlaylistFavorite(); $('#'+type).attr('title','unfavorite this playlist'); }
//					else { Vevo.PlaylistWatch.removePlaylistFavorite(); $('#'+type).attr('title','favorite this playlist'); }
//				}
//				else if (type == "fav-channel") {
//					if (fav) { Vevo.PlaylistWatch.setChannelFavorite(); $('#' + type).attr('title', 'unfavorite this channel'); }
//					else { Vevo.PlaylistWatch.removeChannelFavorite(); $('#' + type).attr('title', 'favorite this channel'); }
//				}
//				else if (type == "fav-video") {
//					vIndex = parseInt(window.location.hash.split("#")[1]);
//					var c_isrc = Vevo.pageData.videos[vIndex];
//					if (fav){ Vevo.PlaylistWatch.setVideoFavorite(c_isrc); $('#'+type).attr('title','unfavorite this video'); }
//					else { Vevo.PlaylistWatch.removeVideoFavorite(c_isrc); $('#'+type).attr('title','favorite this video'); }
//				}
//			});
			Vevo.PlaylistWatch.nowPlayingInit();
		},
		setupMoreFromThisArtist:function(v){
			var cont = $('#MoreVideos'), vIndex = parseInt(window.location.hash.split("#")[1]), v = v || Vevo.pageData.videosHash[Vevo.pageData.videos[vIndex]];
			$('div.more-from-this-artist',cont).remove();
			$.each(v.artists, function(i,a){
				$('<div class="more-from-this-artist ui-hide"><h2>More from '+a.artist_name+'</h2><span class="ui-hide id">'+a.artist+'</span><div class="more-wrapper"><ul class="list videoSmall"></ul></div></div>').prependTo(cont)
			});
			Vevo.watch.moreFromThisArtist.init();
		},
		setVideoFavorite: function (c_isrc){
			$.post('/Proxy/User/Favorite/Add.ashx', { t : 'Video', id : c_isrc }, Vevo.FBHelper.doFbFavPublish, 'json');
		},
		removeVideoFavorite: function (c_isrc){
			$.post('/Proxy/User/Favorite/Remove.ashx', { t : 'Video', id : c_isrc});
		},
		setChannelFavorite: function(c_isrc) {
			$.post('/Proxy/User/Favorite/Add.ashx', { t: 'Channel', id: Vevo.pageData.channelID }, Vevo.FBHelper.doFbFavPublish, 'json');
		},
		removeChannelFavorite: function(c_isrc) {
			$.post('/Proxy/User/Favorite/Remove.ashx', { t: 'Channel', id: Vevo.pageData.channelID });
		},
		setPlaylistFavorite: function() {
			$.post('/Proxy/User/Favorite/Add.ashx', { t : 'Playlist', id : Vevo.pageData.playlistID }, Vevo.FBHelper.doFbFavPublish, 'json');
		},
		removePlaylistFavorite: function (){
			$.post('/Proxy/User/Favorite/Remove.ashx', { t : 'Playlist', id : Vevo.pageData.playlistID });
		},
		nowPlayingClickHandler: function(ev,endf){
			$('div.scrollable-wrapper div.empty',Vevo.playbar.$pbar).addClass('ui-hide');
			ev.preventDefault();
			if ($('#dialog-create-new-playlist').dialog('isOpen')){
				$('#dialog-create-new-playlist').dialog('close'); 
			}
			var t = $(this);
			if (!t.hasClass('active')){
				if ($.isArray(Vevo.PlaylistWatch.nowplaying)){ Vevo.PlaylistWatch.setupWatchListAgain(); } 
				t.addClass('active');
				$('a.your-quicklist', Vevo.playbar.$pbar).removeClass('active').one('click',Vevo.PlaylistWatch.myQlclickhandler);
				$('div.bar-wrapper div.ad, div.bar-wrapper div.lists, div.bar-wrapper div.play', Vevo.playbar.$pbar).addClass('ui-hide');
				$("div.scrollable ul", Vevo.playbar.$pbar).sortable('disable').removeClass('ui-state-disabled');
				Vevo.playbar.windowResizeHandler();
			}
			if ($.isFunction(endf)){ endf(); }
		},
		nowPlayingInit: function(){
			var header=$('div.header div.clearfix', Vevo.playbar.$pbar);
			var yourql = $('a.your-quicklist', Vevo.playbar.$pbar).removeClass('active').unbind('click',Vevo.playbar.header.clickHandlers.yourQL).one('click',Vevo.PlaylistWatch.myQlclickhandler).one('click',Vevo.playbar.logImpression);
			var np = $('<a class="now-playing ui-f-left" href="#">Now Playing : '+Vevo.pageData.playListTitle+'</a>').bind('click',this.nowPlayingClickHandler).appendTo(header).trigger('click');
		},
		makePlayerAvailable: function() { 
			playerAvailable = true;
			return playerAvailable; 
		},
		disableAutoAdvance: function() { 
			autoAdvance = false; 
			return autoAdvance;
		},
		enableAutoAdvance: function(shouldAdvanceIfNotPlaying) {
			autoAdvance = true;
			if (shouldAdvanceIfNotPlaying && !Vevo.VideoPlayer.isPlaying()) { return this.next(); }
		},
		setupWatchListAgain: setupWatchListAgain,
		next: nextHandler,
		prev: prevHandler,
		nowplaying:null,
		
		myQlclickhandler: function(ev){
			ev.preventDefault(); 
			$("div.scrollable ul", Vevo.playbar.$pbar).sortable('enable').removeClass('ui-state-disabled');
			$('div.bar-wrapper div.ad, div.bar-wrapper div.lists, div.bar-wrapper div.play', Vevo.playbar.$pbar).removeClass('ui-hide');
			Vevo.PlaylistWatch.nowplaying = [];
			$('div.scrollable-wrapper ul.items li',Vevo.playbar.$pbar).each(function(i,ta){
				ta = $(ta);
				Vevo.PlaylistWatch.nowplaying.push(ta.clone(true).data('playlistId',Vevo.pageData.playlistID).data('video', ta.data('video')));
			});
			Vevo.playbar.header.clickHandlers.yourQL.apply(this,[ev]);
			Vevo.playbar.windowResizeHandler();
		},
		
		
		setPageElements: function(e, isrc, isPlaylist) {
			if (!Vevo.VideoPlayer.isFullscreen) {
				vIndex = parseInt(window.location.hash.split("#")[1]);
				setNowPlaying();
			}
		},
		hideCommentsIterator:function(i,a){
			var t = $(a).attr('href');
			$(t).addClass('ui-hide');
		},
		showCommentsClickHandler:function(ev){
			ev.preventDefault();
			var t = $(this).addClass('on');
			t.siblings().filter('a').removeClass('on').each(Vevo.PlaylistWatch.hideCommentsIterator);
			$(t.attr('href')).removeClass('ui-hide');
		},
		playlistTab:{
			tab:null, ol:null, grid:null,
			init:function(){
				this.tab = $('div.tabs a[href="#Playlist"]').one('click',this.tabClickHandler);
				this.grid = $('.playlist-grid','#Playlist');
				this.ol = $('ol',this.grid);
			},
			tabClickHandler:function(){ /* prolly dont need this extra func atm */
				Vevo.PlaylistWatch.playlistTab.updateGrid();
			},
			liHoverOn: function(ev) { $(this).addClass('hover'); },
			liHoverOff: function(ev) { $(this).removeClass('hover'); },
			liClickHandler: function(ev) { 
				$('.now-playing',Vevo.PlaylistWatch.playlistTab.ol).removeClass('now-playing');
				var i = $(this).addClass('now-playing').data('index'), f = function(){
					$('div.scrollable-wrapper ul.items li:eq('+i+')',Vevo.playbar.$pbar).trigger('click');
				};
				$('a.now-playing', Vevo.playbar.$pbar).trigger('click',[f]);
			},
			/*NO_NOWPLAYING_liClickHandler: function(ev) { 
				$('.now-playing',Vevo.PlaylistWatch.playlistTab.ol).removeClass('now-playing');
				var i = $(this).addClass('now-playing').data('index'),
					isrc = $(this).addClass('now-playing').data('isrc');
				window.location.hash = i;
				$(Vevo).trigger('loadVideo', [isrc, true]);
			},*/
			updateGrid:function(){
				$('li', Vevo.PlaylistWatch.playlistTab.ol).remove();
				$('span.n', Vevo.PlaylistWatch.playlistTab.gird).text(Vevo.pageData.videos.length)
				$.each(Vevo.pageData.videos,function(i,v){
					var vid = Vevo.pageData.videosHash[v], artist = [];
					$.each(vid.artists, function(j,a){ artist.push('<a href="'+a.artist_url+'">'+a.artist_name+'</a>'); });
					artist = artist.join(',&nbsp;');
					var li = $('<li class="ui-pointy"><div class="clearfix">'+
							/*'<span class="duration ui-hide ui-f-left">99:88</span>'+*/
							'<span class="num ui-f-left">'+(i+1)+'</span>'+
							'<span class="status ui-f-left">...</span>'+
							'<span class="song-title ui-f-left">'+vid.video_name+'</span>'+
							'<span class="artist-name ui-f-left">'+(vid.byline_links || artist)+'</span>'+
						'</div></li>').data('isrc',v).hover(Vevo.PlaylistWatch.playlistTab.liHoverOn, Vevo.PlaylistWatch.playlistTab.liHoverOff).bind('click',Vevo.PlaylistWatch.playlistTab.liClickHandler).appendTo(Vevo.PlaylistWatch.playlistTab.ol).data('index',i);
					if (i==playPosition){ li.addClass('now-playing'); } 
				});
				$('li:odd', Vevo.PlaylistWatch.playlistTab.ol).addClass('alt');
			}
		}
	};
})();

$(document).ready(function() {
	if (parseInt(Vevo.pageData.playlistID) === 0)
		$('#toggle-comment-view').hide();
	$('textarea.limited').maxlength({ feedback: '.charsLeft' });
	$('#show-video-comments,#show-playlist-comments').bind('click',Vevo.PlaylistWatch.showCommentsClickHandler);
	$('#show-video-comments').trigger('click');
	$(Vevo).bind('tracklistAvailable', Vevo.PlaylistWatch.init)
		//.bind('playerAvailable', Vevo.PlaylistWatch.makePlayerAvailable)
		.bind('videoComplete', Vevo.PlaylistWatch.next)
		.bind('loadVideo videoFullscreenChange', Vevo.PlaylistWatch.setPageElements)
		.trigger('tracklistAvailable', [{'videos': Vevo.pageData.videos }, playPosition]);
//	$('#favoriting a').bind('click', function(ev) {
//		ev.preventDefault();
//		if (!Vevo.user.isLoggedIn) {
//			Vevo.messageButNotLoggedIn.show("Favorites and Recommendations", "You will need to be signed in to favorite or get recommendations.");
//		}
//		else {
//			var t = $(this).toggleClass('fav');
//			$(Vevo).trigger('favorite-change', [t.attr('id'), t.hasClass('fav')]);
//		}
//	});
	Vevo.PlaylistWatch.playlistTab.init();
//	if (window.location.href.indexOf('?custom=true') != -1 || Vevo.pageData.playlistID == "0") {
//		$('#fav-playlist').parent().addClass('ui-hide');
//	}
//	$.post('/Proxy/User/Favorite/IsFavorite.ashx?_=' + Vevo.playbar.playList.salt(), { t: 'Playlist', q: Vevo.pageData.playlistID }, function(data) {
//		if (data.length > 0 && data[0].IsFavorite && data[0].IsFavorite == true) { $('#fav-playlist').addClass('fav').attr('title', 'unfavorite this playlist'); }
//		else { $('#fav-playlist').removeClass('fav').attr('title', 'favorite this playlist'); }
//	}, 'json');

//	if (Vevo.pageData.channelID != null) {
//		$.post('/Proxy/User/Favorite/IsFavorite.ashx?_=' + Vevo.playbar.playList.salt(), { t: 'Channel', q: Vevo.pageData.channelID }, function(data) {
//			if (data.length > 0 && data[0].IsFavorite && data[0].IsFavorite == true) { $('#fav-channel').addClass('fav').attr('title', 'unfavorite this channel'); }
//			else { $('#fav-channel').removeClass('fav').attr('title', 'favorite this channel'); }
//		}, 'json');
//	}
});
