var debugSCET = true;
var isLiked = false;

/*
jqN(document).ready(function() {	
	jqN('#search-field').focus(function(){searchField();});	
	
	jqN('.browse-nav a').click(function(){dumbTabs(this,'.browse-nav a','#more-videos .tab-content');});
	jqN('.share-list a').click(function(){dumbTabs(this,'.share-list a','#nbc-share-comments .tab-content');});
	dumbTabs(this,'.share-list a','#nbc-share-comments .tab-content');

	jqN.ajax({
		type: "GET",
		url: "/app/api/sn/snas/",
		data: {
			method: 'getContentDetails',
			contentSSUniqueKey: nbcu.content.object.getParam('contentSSUniqueKey'),
			contentType: nbcu.content.object.getParam('contentType'),
			siteName: nbcu.config.getParam("snasSiteName"),
			siteDomainName: nbcu.config.getParam("snasSiteDomainName")
		},
		dataType: "xml",
		success: function(data){
			if (commentCount = jqN(data).find("commentCount").text()) {
				jqN('.share-list .comments-trigger').text('(' + commentCount + ')');
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){}
	});

});
*/


/******** RECOMMENDATIONS **********/
/*
function loadFilterRec(video, type, page){
	var perPage;
	
	if (type == "more") {
		perPage = 7;
	} else {
		type = "less";
		perPage = 3;
	}
	page = page || 1;
	
	if (nbcu.app.scet.video.getParam("abGroup") == "nbceditorial" || isFullEpisode) {
		source = "editorial";	
	} else if (nbcu.app.scet.video.getParam("abGroup") == "thefilter") {
		source = "thefilter";
	}
	jqN.ajax({
		type: "GET",
		url: '/assets/esp/video/feed/getRecommendedVideo/.json',
		data: {perPage: perPage, page: page, videoId: video, source: source},
		dataType: "json",
		beforeSend: function(xhr){xhr.setRequestHeader("X-Framework-JSON-Request", "PLAINJSON");},
		success: function(data){displayFilter(data, type, page, perPage)},
		error: function(XMLHttpRequest, textStatus, errorThrown){}
	});
}

function newNBCPageview()
{
	window.ad728x90.location.reload();
	window.ad300x250.location.reload();
	s.t();
}

function displayFilter(data, type, page, perPage){
	jqN('#filter-recommendations div').remove();
	jqN('#filter-recommendations ul').remove();
	var html = "<ul>";
	var x = 0;
	var uriAppend = "";

	for (x = 0; x <data.pageRecords.length;x++ ) {
		var title = data.pageRecords[x].title;
		var description = data.pageRecords[x].shortDescription;
		var thumbnail = data.pageRecords[x].largeThumbnailUrl;
		var uri = data.pageRecords[x].fullUrl;
			if (nbcu.app.scet.video.getParam("abGroup") == "nbceditorial" && !isFullEpisode) {
			uriAppend = "__cid=nbceditorial";	
		} else if (nbcu.app.scet.video.getParam("abGroup") == "thefilter" && !isFullEpisode) {
			uriAppend = "__cid=thefilter";	
		}
		
		if (uriAppend) {
			uri = (uri.indexOf('?') >= 0) ? uri + '&' + uriAppend : uri + '?' + uriAppend;
		}
		
		if (!isFullEpisode) {
			onClick = "nbcu.app.scet.video.logEvent({ event: 'recClick', recId: " + nbcu.app.scet.video.getParam("assetId") + " });"
		} else
		{
			onClick = null;
		}

		html += listTemplate(title, description, uri, getMezzanine('http://video.nbc.com/' + thumbnail,'106','59'), "h5", onClick);
	}
	html += "</ul>";
	if (type == "more") {
		html += '<div style="text-align: center;" class="rec-pagination">';
		html += getPagination(data.totalRecords, page, perPage);
		html += '</div>';
	} else {
		html += '<div class="right"><a class="more" href="javascript:void(0);">MORE</a></div>';
	}
	jqN('#filter-recommendations').append(html);
	
	// bind MORE click
	jqN('#filter-recommendations .more').click(function() {
		var contentId = nbcu.content.object.getParam("contentId");
		loadFilterRec(contentId, "more");
	});
	
	// bind pagination clicks
	jqN('#filter-recommendations .paginatePrev').click(function() {
		var contentId = nbcu.content.object.getParam("contentId");
		loadFilterRec(contentId, "more", page - 1);
	});
	jqN('#filter-recommendations .paginateNext').click(function() {
		var contentId = nbcu.content.object.getParam("contentId");
		loadFilterRec(contentId, "more", page + 1);
	});	
	
	jqN('#filter-recommendations').slideDown();
}
*/
/******** END RECOMMENDATIONS **********/

/******** EPISODE GUIDE **********/
function loadEpisodeGuide(galleryId) {
	jqN.ajax({
		type: "GET",
		url: '/assets/esp/episodeguide/episode/feed/.json',
		data: {galleryId: galleryId},
//		data: {galleryId: 4342},
		dataType: "json",
		beforeSend: function(xhr){xhr.setRequestHeader("X-Framework-JSON-Request", "PLAINJSON");},
		success: function(data){
			displayEpisodeGuide(data);
			displayExclusiveContent(data);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){}
	});	
}

function displayEpisodeGuide(data) {
	var html = "";
	var x = 0;
	var episodeTitle = '';
	var episodeAirDate = '';
	var episodeDescription = '';
	var episodeRunningTime = '';
	var episodeHd = '';
	var episodeTvRating = '';
	var videoUri = '';
	var videoThumbnail = '';
	var expireDate = '';
	var isExpired = 'N';
	var videoClip = new Array();
	var communityUri = '';
	var galleryUri = '';
	var recapUri = '';
	
	jqN('#episode-guide').empty();
	
	if (typeof data.episode_info != 'undefined' && typeof data.episode_info[0] != 'undefined') {
		if (data.episode_info[0].video != null && typeof data.episode_info[0].video[0] != 'undefined') {
			episodeTitle = data.episode_info[0].video[0].episode_title;
			episodeAirDate = data.episode_info[0].video[0].original_airdate;
			episodeDescription = data.episode_info[0].video[0].synopsis;
			videoUri = data.episode_info[0].video[0].video_url;
			videoThumbnail = getMezzanine(data.episode_info[0].video[0].large_thumbnail_url,'106','59');
			isExpired = data.episode_info[0].video[0].expired;
			
			var clipLength = data.episode_info[0].video[0].cliplength.split('.');
			var clipLengthInMin = parseInt(clipLength[0] / 60);
			var clipLengthInSec = clipLength[0] - (clipLengthInMin * 60);
			episodeRunningTime = clipLengthInMin + ':' + clipLengthInSec;
			
			var expireDateTimeArray = data.episode_info[0].video[0].expire_date.split(' ');
			var expireDateArray = expireDateTimeArray[0].split('-');
			expireDate = expireDateArray[1] + '/' + expireDateArray[2] + '/' + expireDateArray[0];			
		} else {
			hideEpisodeGuide();
			return;
		}
		
		communityUri = data.episode_info[0].episode_info_community_url;
		galleryUri = data.episode_info[0].gallery.length > 0 ? data.episode_info[0].gallery[0].gallery_url : '';
		recapUri = data.episode_info[0].recap_url;
		
		try {
			// video clips in the episode_info node
			if (data.episode_info[0].shortform_video != null) {
				for (x in data.episode_info[0].shortform_video) {
					var clip = {
						title: data.episode_info[0].shortform_video[x][0].title,
						uri : data.episode_info[0].shortform_video[x][0].video_url,
						thumbnail: getMezzanine(data.episode_info[0].shortform_video[x][0].large_thumbnail_url,'106','59')
					}
					videoClip.push(clip);
				}			
			}
		} catch(err) {}
		try {
			// video clips in the guest_one node
			if (data.guest_one[0].video != null) {
				for (x in data.guest_one[0].video) {
					var clip = {
						title: data.guest_one[0].video[x][0].title,
						uri : data.guest_one[0].video[x][0].video_url,
						thumbnail: getMezzanine(data.guest_one[0].video[x][0].large_thumbnail_url,'106','59')
					}
					videoClip.push(clip);
				}			
			}			
		} catch(err) {}
		
	} else {
		hideEpisodeGuide();
		return;
	}
	
	html = '<h2>Episode Guide</h2>';
	
	html += '<ul class="show-info">';
	html += '<li><h4>' + episodeTitle + '</h4></li>';
	html += '<li class="show-air-date">Original Air Date: ' + episodeAirDate + '</li>';
	html += '<li class="show-running-time">Running Time: ' + episodeRunningTime + '</li>';
	html += '<li class="hd">HD</li>';
	html += '<li class="tv-rating">TV-14</li>';
	html += '</ul>';
	
	html += '<div class="guide-wrap">';
	// description
	html += '<div class="guide-show-desc guide-element"><p>' + episodeDescription + '</p></div>';
	// full episodes
	html += '<div class="guide-full-episode guide-element">';
	html += '<h4>Full Episode</h4>';
	html += '<a href="' + videoUri + '" class="border"><img src="' + videoThumbnail + '" /></a>';
	html += '<ul><li class="episodes-icon show-icon"><a href="' + videoUri + '">' + episodeTitle + '</a></li></ul>';
	if (isExpired == 'N') {
		html += '<p>Available Until:<br />' + expireDate + '</p>';
	} else {
		html += '<p>Expired</p>';
	}
	html += '</div>';
	// clips
	html += '<div class="guide-video-clips guide-element">';
	html += '<h4>Video Clips</h4>';
	if (videoClip.length > 0 ) {
		html += '<a href="' + videoClip[0].uri + '" class="border"><img src="' + videoClip[0].thumbnail + '" /></a>';
		html += '<ul>';
		for (x in videoClip) {
			html += '<li class="clips-icon show-icon"><a href="' + videoClip[x].uri + '">' + videoClip[x].title + '</a></li>';
		}
		html += '</ul>';
	} else {
		html += 'No Video Clips';
	}
	html += '</div>';
	// related content
	html += '<div class="guide-related-content guide-element">';
	html += '<h4>Related Content</h4>';
	html += '<ul>';
	if (communityUri) {
		html += '<li class="community-icon show-icon"><a href="' + communityUri + '">Community</a></li>';
	}
	if (recapUri) {
		html += '<li class="showsite-icon show-icon"><a href="' + recapUri + '">Recap</a></li>';
	}
	if (galleryUri) {
		html += '<li class="photos-icon show-icon"><a href="' + galleryUri + '">Photos</a></li>';
	}
	html += '</ul>';
	html += '</div>';
	html += '</div>';
	
	jqN('#episode-guide').html(html);
	jqN('#episode-guide').show();
}

function hideEpisodeGuide() {
	jqN('#episode-guide').hide();
}

function displayExclusiveContent(data) {
	if (typeof data.related != 'undefined') {
		jqN('#favorites-exclusive-content ul').hide().empty();
		jqN('#favorites-exclusive-content').show();
		
		var html = "";
		var x;
		for (x in data.related) {
			if (x > 3) {
				break;
			}
			
			var title = data.related[x].related_content_label;
			var description = '';
			var thumbnail = data.related[x].related_content_thumbnail;
			var uri = data.related[x].related_content_url;
			if(thumbnail)
			{
				html += listTemplate(title, description, uri, thumbnail, 'h4');
			}
		}
		if (html != '') {
			jqN('#favorites-exclusive-content ul').append(html);
			jqN('#favorites-exclusive-content li:last').addClass("last");
			jqN('#favorites-exclusive-content ul').show();				
			return;
		}
	}
	
	jqN('#favorites-exclusive-content').hide();
}
/******** END EPISODE GUIDE **********/

/******** LIKE IT **********/
function triggerLikeIt() {
	nbcu.util.common.loadClass("Nbcu.Content.Object");
	
	if (jqN("#like-it-content iframe").length > 0) {
		return;
	}
	
	isLiked = true;
	
	jqN("#like-it-content").empty().css("text-align", "center");

/*
	jqN('<iframe></iframe>').attr({
		src: '/app/modules/snas-like/frames/v4-login.php?hasChrome=false',
		frameborder: 0,
		scrolling: 0,
		id: "likeItFrame",
		name: "likeItFrame",
		width: 645,
		height: 280
	}).appendTo(jqN("#like-it-content"));
*/	
	
	jqN("#like-it-content").append('<iframe frameBorder="0" allowtransparency="true" scrolling="0" width="645" height="280" src="/app/modules/snas-like/frames/v4-login.php?hasChrome=false"></iframe>');
	jqN("#like-it-content").append('<a class="close-like-it right" href="javascript:void(0);">Close Like It</a>');
	jqN("#like-it-content .close-like-it").click(function() {
		isLiked = false;
		nbcu.content.object.registerUserAction("like", null, false);
		jqN("#like-it-content iframe").remove();
		closeLeftTabs();
	});
	
	if (jqN.browser.msie6 == true ) {
		jqN("#like-it-content iframe").attr('contentWindow').location.reload(true);
	}
	
	jqN(window).unload(function() {
		if (isLiked) {
			nbcu.content.object.registerUserAction("like", null, false);
		}
	});	
}
/******** END LIKE IT **********/

/******** TAGS **********/
function triggerTags() {
	nbcu.util.common.loadClass("Nbcu.Content.Object");
	
	if (jqN("#tags-content iframe").length > 0) {
		return;
	}
	
	jqN("#tags-content").empty().css("text-align", "center");
	
/*	
	jqN('<iframe></iframe>').attr({
		src: '/app/modules/snas-tag/frames/v4-login.php?hasChrome=false',
		frameborder: 0,
		scrolling: 0,
		id: "tagsFrame",
		name: "tagsFrame",
		width: 645,
		height: 285
	}).appendTo(jqN("#tags-content"));
*/	
	jqN("#tags-content").append('<iframe frameBorder="0" allowtransparency="true" scrolling="0" width="645" height="285" src="/app/modules/snas-tag/frames/v4-login.php?hasChrome=false"></iframe>');
	jqN("#tags-content").append('<a class="close-tags right" href="javascript:void(0);">Close Tags</a>');
	jqN("#tags-content .close-tags").click(function() {
		jqN("#tags-content iframe").remove();
		closeLeftTabs();
	});	
	
	if (jqN.browser.msie6 == true ) {
		jqN("#tags-content iframe").attr('contentWindow').location.reload(true);
	}	
}
/******** END TAGS **********/

/******** COMMENTS **********/
function triggerComments() {
	if (jqN("#comment-content").css('display') != 'none') {
		return;
	}
	
/* VERSION 2
	if (jqN("#comment-content").children().length < 1) {
		var html = '<h3>User Comments</h3>'
			+ '<a href="javascript:void(0);" class="post-comment right">Post a Comment</a>'
			+ '<div class="clear"></div>'
			+ '<div class="sn_comment_div"></div>'
			+ '<div class="sn_comment_pager_div"></div>'
			+ '<div class="sn_comment_form_div" style="display:none;"></div>'
			+ '<a href="javascript:void(0);" class="close-comments right">Close Comments</a>';
		jqN("#comment-content").append(html);
	}
	
	nbcu.sn.comment.init();
*/
	
	nbcu.sn.comment.renderComments(null, function() {
		getCommentsCount();
		if (jqN("#comment-content .close-comments").length < 1) {
			jqN("#comment-content").append('<a href="javascript:void(0);" class="close-comments right">Close Comments</a>');
			jqN("#comment-content .close-comments").click(function() {
				closeLeftTabs();
				jqN('#comment-content .sn_comment_div').show();
				jqN('#comment-content .sn_comment_pager_div').show();
				jqN('#comment-content .post-comment').show();
				jqN('#comment-content .sn_comment_form_div').hide();		
			});
		}
	});
	
	jqN("#comment-content .sn_comment_form_div").css('width', '634px');	
	
/* VERSION 2
	jqN("#comment-content .post-comment").click(function() {
		jqN('#comment-content .sn_comment_div').hide();
		jqN('#comment-content .sn_comment_pager_div').hide();
		jqN('#comment-content .post-comment').hide();
		jqN('#comment-content .sn_comment_form_div').show();
	});		
	jqN("#comment-content .close-comments").click(function() {
		closeLeftTabs();
		jqN('#comment-content .sn_comment_div').show();
		jqN('#comment-content .sn_comment_pager_div').show();
		jqN('#comment-content .post-comment').show();
		jqN('#comment-content .sn_comment_form_div').hide();		
	});
*/	

	jqN("#comment-content").show();
}

function getCommentsCount() {
	jqN('.share-list .comments-trigger').text('(' + nbcu.sn.comment.getParam('totalRecords') + ')');
}
/******** END COMMENTS **********/

/******** SHARE **********/
function triggerShare() {
	jqN("#share-it-content .share-embed").val(nbcu.content.object.getParam('embedCode'));
	jqN("#share-it-content .share-permalink").val(window.location.href);
	jqN("#share-it-content .close-share").click(function() {
		closeLeftTabs();
	});	
}
/******** END SHARE **********/

/************* UTILITIES *************/
function dumbTabs(element,trigger,target){
	if (jqN(element).hasClass('tag-it-trigger')) {
		triggerTags();
	} else if (jqN(element).hasClass('like-it-trigger')) {
		triggerLikeIt();
	} else if (jqN(element).hasClass('comments-trigger')) {
		triggerComments();
	} else if (jqN(element).hasClass('share-it-trigger')) {
		triggerShare();
	} else if (jqN(element).attr('id') == 'browse-tab') {
		jqN('#scet_browse_pager').hide();
	}

	if(!jqN(element).hasClass('active')){
		var index = jqN(trigger).index(element);
		jqN(trigger).removeClass('active');
		jqN(element).addClass('active');
		jqN(target).hide();
		jqN(target).eq(index).show();
	}
}

function closeLeftTabs(removeContent) {
	jqN('#comment-content').hide();
	jqN('#share-it-content').hide();
	jqN('#tags-content').hide();
	jqN('#like-it-content').hide();
	jqN('.share-list li a').removeClass('active');
	
	if (removeContent === true) {
		jqN("#tags-content iframe").remove();
		jqN("#like-it-content iframe").remove();
	}
}

function closeTabs() {
	jqN('.tab-content').hide();
	jqN('.share-list li a').removeClass('active');
}

function preloadImage(obj){
	try{
		var alt = obj.alt.replace(/\"/g,"&quot;");
		var img = jqN('<img/>')
		.attr({
			alt:alt,
			title:alt,
			src:obj.src
		});

	return img;
	}catch(e){/*fail*/}
}

function getResizedThumbnail(uri, w, h) {
	var pattern = /\/app2\/img\/95x88xC\/scet/;
	return uri.replace(pattern, '/app2/img/' + w + 'x' + h + 'xC/scet');
}

function getPagination(recordCount, page, perPage) {
	var html = "";
	
	// prev
	if (recordCount > perPage && page > 1) {
		html += '<a class="paginatePrev" href="javascript:void(0);">PREV</a>';
	} else {
		html += '';
	}

	// next
	if (recordCount > page * perPage) {
		html += (html) ? ' | ' : '';
		html += '<a class="paginateNext" href="javascript:void(0);">NEXT</a>';
	} else {
		html += '';
	}
	
	return html;
}
/*
function checkForSeoUri(redirectSeoUri, galleryId, galleryTitle) {
	if (redirectSeoUri == 0) {
		return;
	}
	
	var hashArray = window.location.hash.replace('#', '').split('=');

	if (galleryId != '' && galleryTitle != '') {
		var uri = window.baseUri + '/' + window.seo(galleryTitle) + '/' + galleryId + '/';
		if (hashArray.length > 1 && hashArray[0] == 'item') {
			uri += window.location.hash;
		}
		window.location.href = uri;
		return;
	}
	
	if (hashArray.length > 1) {
		if (hashArray[0] == 'gallery') {
			jqN.ajax({
				beforeSend: function(xhr){xhr.setRequestHeader("X-Framework-JSON-Request", "PLAINJSON");},
				url: '/app/esp/photo/feed/gallery/.json',
				data: {where: 'gallery_id=' + hashArray[1]},
				dataType: 'json',
				async: false,
				success: function(data) {
					if (data.totalRecords < 1) {
						window.location.href = window.baseUri;
						return;
					}
					
					var gallery = data.pageRecords[0];
					window.location.href = window.baseUri + '/' + window.seo(gallery.gallery_title) + '/' + gallery.gallery_id;
				}
			});
		} else if (hashArray[0] == 'item') {
			jqN.ajax({
				beforeSend: function(xhr){xhr.setRequestHeader("X-Framework-JSON-Request", "PLAINJSON");},
				url: '/app/esp/photo/feed/getPhoto/.json',
				data: {where: 'gallery_item_id=' + hashArray[1]},
				dataType: 'json',
				async: false,
				success: function(data) {
					if (data.totalRecords < 1) {
						window.location.href = window.baseUri;
						return;
					}
					
					var gallery = data.pageRecords[0];
					window.location.href = window.baseUri + '/' + window.seo(gallery.gallery_title) + '/' + gallery.gallery_id + '/' + window.location.hash;
				}
			});			
		}
	}
}
*/
/************* END UTILITIES *************/

