// JS for Video Gallery Channel

function createCommentToggle() {

	$("div.trigger").toggle(function(){
		$(this).addClass("active"); 
		}, function () {
		$(this).removeClass("active");
	});

	$("div.trigger").click(function(){
		$(this).next(".commentBlock").slideToggle("slow,");
	});

}


/* for window reload function - start */
//var sURL = unescape(window.location.pathname);
//var pURL = unescape(window.opener.location.href);
//alert(window.top.location.pathname);
//var sURL = window.top.location.pathname;
function refresh()
	{
		//alert(sURL);
		//alert(sURL);
		//window.parent.location.href = sURL;
		//window.opener.location.reload(true);
	}

/* for window reload function - end */

function retrieveVideoRating(contentId) {

    var myDate=new Date();

    var url = '/content/addContentDataCall.do?dataContentId='+contentId + '&noViews=true&dt='+escape(myDate);

    $.getJSON(url,
	function(data){

		var returnUrl=contentUrl;

		populateRating(data.contentData.contentId,returnUrl,data.contentData.averageRating,data.contentData.userRating, data.contentData.votes);
	});
}

var bplayer;
var video, exp,con;
var menu,admodule;
var videoPlayed=false;

// called when template loads, this function stores a reference to the player and modules.
function onTemplateLoaded(experienceID) {

	 // Get a reference to the player
	 bplayer = bcPlayer.getPlayer(experienceID);

	 // Get references to the player modules
	 video = bplayer.getModule(APIModules.VIDEO_PLAYER);
	 exp = bplayer.getModule(APIModules.EXPERIENCE);
	 con = bplayer.getModule(APIModules.CONTENT);
	 admodule = bplayer.getModule(APIModules.ADVERTISING);

	addSocialLinksToPlayer(videoLink,videoTitle,exp);

	//admodule.enableOverrideAds(true);
	admodule.addEventListener(BCAdvertisingEvent.EXTERNAL_AD, onExternalAd);
	
	 // Register event listeners
	 exp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);

	menu = bplayer.getModule(APIModules.MENU);
	video.addEventListener('mediaPlay', onMediaPlay);

	if (typeof adid != "undefined" && adid!=null) {
		var adPolicy={};
		adPolicy.playerAdKeys ='comp='+adid;
		admodule.setAdPolicy(adPolicy);
	}
}

function onExternalAd(e) {
	//do nothing
}

function addSocialLinksToPlayer(link,title,exp){

	var b1=exp.getElementByID('socialDigg');
	if (b1!=null) {
		b1.setURL('http://digg.com/submit?phase=2&url='+link+'&title='+title);
	}

	var b2=exp.getElementByID('socialFacebook');
	if (b2!=null) {
		b2.setURL('http://www.facebook.com/sharer.php?u='+link+'&t='+title);
	}

	var b3=exp.getElementByID('socialTwitter');
	if (b3!=null) {
		b3.setURL('http://twitter.com?status='+link);
	}

	var b4=exp.getElementByID('socialStumbleUpon');
	if (b4!=null) {
		b4.setURL('http://www.stumbleupon.com/submit?url='+link+'&title='+title);
	}

	var b5=exp.getElementByID('socialMySpace');
	if (b5!=null) {
		b5.setURL('http://www.myspace.com/index.cfm?fuseaction=postto&t='+title+'&u='+link+'&l=Location');
	}
}

function onTemplateReady(e) {
	menu.addEventListener('videoRequest', onElementClick);
	if (videoId!=null) {
		if (typeof s!="undefined") {
			s.tl(true,'o','videoload'+videoId);
		}
	}
}

function onMediaPlay(e) {
	if (!videoPlayed) {
		s.tl(this,'o','videoplay'+e.media.id);
		videoPlayed=true;
	}
}

function onElementClick(e) {
	
     // Event Object contains the VideoDTO for the clicked video
     var selectedVideo = e.args;
     var urlPath = "/open-video.do"; 

     admodule.enableOverrideAds(true);

     // Refresh the page adding the current playlist and video to the URL
     document.location = urlPath + "?bctid=" + selectedVideo.id;
}

var COMMENT_LENGTH_LIMIT = 500;
function textLimit(field,cntfield,maxlimit) {
	var matches = field.value.match(/\n/g);
	var count = 0;
	
	if (matches != null) {
		count = matches.length;
	}
	
	var textLength = field.value.length + count;

	if (textLength > maxlimit)
		field.value = field.value.substring(0, maxlimit - count);
	else
		cntfield.value = maxlimit - textLength;
}

function pageClick(pageNo,pageUrl) {

	var myDate=new Date();
	
	$("#commentblock").load("/content/videoCommentsPageCall.do?commentContentId="+contentId+"&page="+pageNo+"&paginationUrl="+pageUrl + "&dt="+escape(myDate));

	return false;
}

function validateCommentForm(pageUrl) {

	if ($('#commentBody').val()=='') {
		alert('Please enter your comment');
		$('#commentBody').focus();
	}
	else if ($('#authorName').val()=='') {
		alert('Please enter your name');
		$('#authorName').focus();
	}
	else {

		$.post("/postComment.do", $('#commentForm').serialize(), function (data) {

			if (data.commentPost.status=='success') {		
		    
				pageClick('',pageUrl);
				//$('#authorName').val('');
				$('#commentBody').val('');
				$('#authorName').focus();
				$('#remainingChars').val(COMMENT_LENGTH_LIMIT);
				$("#commentTrigger").click();
				commentSuccessOmniture();
				publishCommentsonFacebook();
			}
			else if (data.commentPost.status=='spam') {
				$('#authorName').val('');
				$('#commentBody').val('');
				$('#authorName').focus();
				$('#remainingChars').val(COMMENT_LENGTH_LIMIT);
				$("#commentTrigger").click();	
				alert('Your comment will show up once reviewed');
			}
			else {
				alert('There was an error posting your comment, please try again later');
			}

			return false;
		},"json");
	}
	
	return false;
}


function commentSuccessOmniture() {

	 if (typeof s!="undefined") {
		 s.eVar5="videoCommentsForm";
		 s.events="event28";
		 s.eVar23=contentId;
		void(s.t());
	 }
}

function publishCommentsonFacebook() {					
  var template_data;
  var template_key = $('#template_key').val();
  var app_key = $('#api_key').val();
    
  FB_RequireFeatures(["Api"], function(){
		FB.init(app_key, "/html/xd_receiver.htm");
	  var uid = FB.Facebook.apiClient.get_session().uid;    
	  var comment_text = $('#contenttitleText').val();
	  var rdServerName=$('#rdServerName').val();
	  rdServerName = "http://"+rdServerName + "?trkid=fb_vidcmt";
	  var fContentType = $('#fContentType').val();
		var thumbNail = $('#contentThumbnail').val();
		var urlName = videoLink;//"http://test.rd.com"+urlName;
		urlName = urlName + "?trkid=fb_vidcmt";
		comment_text = fContentType+" <a href='"+urlName+"' title='"+comment_text+"'>"+comment_text+"</a> on <a href='"+rdServerName+"' title='ReadersDigest.com'> ReadersDigest.com </a>";									
		if((urlName != null && thumbNail != null) &&
				(urlName.indexOf("http://") != -1) && (thumbNail.indexOf("http://") != -1))				
		{
			template_data = {"images":[{"src":thumbNail,"href":urlName}], "comment-text": comment_text};
		}
		else
		{
			template_data = {"comment-text": comment_text};
		}						
		FB.Connect.showFeedDialog(template_key, template_data);
 });
}

/* Video Gallery JS Code End */