nbcu.util.common.loadClass("Nbcu.Template");

Namespace("Nbcu.Sn.Comment");
Nbcu.Sn.Comment = function(){ this.constructor(); }
Nbcu.Sn.Comment.inherits(Nbcu);

cTemplate = new Nbcu.Template("Sn.Comment.Default");

// Set defaults for params not defined
Nbcu.Sn.Comment.method('init', function(commentObj, commentObjName, commentSelector, commentFormSelector, commentPagerSelector)
{
	this.commentObj = commentObj || nbcu.sn.comment;
	this.commentObjName = commentObjName || "nbcu.sn.comment";
	this.commentSelector = commentSelector || ".sn_comment_div";
	this.commentFormSelector = commentFormSelector || ".sn_comment_form_div";
	this.commentPagerSelector = commentPagerSelector || ".sn_comment_pager_div";
	
	this.contentId = this.commentObj.getParam("contentId") || null;
	this.contentUrl = this.commentObj.getParam("contentUrl") || null;
	this.contentSSUniqueKey = this.commentObj.getParam("contentSSUniqueKey") || null;
	this.contentType = this.commentObj.getParam("contentType") || null;
	this.orderBy = this.commentObj.getParam("orderBy") || null;

	this.currentPage = this.commentObj.getParam("currentPage") || 1;
	this.maxPages = this.commentObj.getParam("maxPages") || 10;
	this.maxRecordsPerPage = this.commentObj.getParam("maxRecordsPerPage") || 10;
	this.isFirstRun = this.commentObj.getParam("isFirstRun");

	this.template = cTemplate;

	// Prevent flicker on pageview less pages
	if (this.isFirstRun || typeof(this.isFirstRun) == 'undefined')
	{
		this.renderForm();
	}
	
	this.renderComments();
});

Nbcu.Sn.Comment.method('renderForm', function()
{
	var session = new Nbcu.Sn.Session();
	
	if (!session.isLoggedIn())
	{
		template = new Nbcu.Template("Sn.Account.Default");
		template.assign("legend", "Log in to post a comment.");
		template.assign("callback", "jqN('" + this.commentFormSelector + "').fadeOut('fast', function() { " + this.commentObjName + ".template.display('form', '" + this.commentFormSelector + "'); }); jqN('" + this.commentFormSelector + "').fadeIn('fast');" + nbcu.sn.comment.getParam("extraLoginCallback"));
		template.display("login_horz", this.commentFormSelector);
	}
	else
	{
		this.template.display("form", this.commentFormSelector);
	}
});

Nbcu.Sn.Comment.method('renderComments', function(currentPage)
{
	if (currentPage)
	{
		this.currentPage = currentPage;
	}

	fromRow = this.maxRecordsPerPage * (this.currentPage - 1) + 1;
	toRow = fromRow + this.maxRecordsPerPage - 1;
	this.getCommentByContent(this.commentObjName + '.renderCommentsCallback(%data%);', this.contentSSUniqueKey, this.contentId, this.contentUrl, this.contentType, fromRow, toRow, null, null, this.orderBy);
});

Nbcu.Sn.Comment.method('renderCommentsCallback', function(data)
{
	this.totalRecords = jqN(data).find("commentByContent").attr("recordCount");
	
	// If this is nbc.com we need to call refreshXFBML so that if any of the comments have FB users their info
	// will be rendered correctly.
	var refreshFacebookXFBML = "";
	if (nbcu.config.getParam("facebookConnectEnabled") == "true") {
		refreshFacebookXFBML = 'refreshXFBML();';
	}
	
	this.template.assign("data", data);	
	this.template.assign("currentPage", this.currentPage);	
	this.template.assign("maxPages", this.maxPages);	
	this.template.assign("maxRecordsPerPage", this.maxRecordsPerPage);
	this.template.assign("totalRecords", this.totalRecords);
	this.template.assign("href", "javascript:;");
	this.template.assign("onclick", this.commentObjName + ".renderComments(%page%);");
	this.template.display("comments", this.commentSelector, refreshFacebookXFBML);
	this.template.display("pager", this.commentPagerSelector);


	//"location.hash = 'sn_comment_top'"
});

Nbcu.Sn.Comment.method('isValid', function(formObj)
{
	if (!nbcu.util.common.trim(formObj.message.value))
	{
		alert("Comment text is required.");
		return false;
	}
	
	return true;
});

Nbcu.Sn.Comment.method('post', function(formObj, formContainerSelector)
{
	var THIS = this;

	var contentId = this.commentObj.getParam("contentId") || null;
	var contentUrl = this.commentObj.getParam("contentUrl") || null;
	var contentSSUniqueKey = this.commentObj.getParam("contentSSUniqueKey") || null;
	var contentType = this.commentObj.getParam("contentType") || null;

	var tagXml = this.commentObj.getParam("systemTags") || null;
	var tagFlag=0;
	var tagParamRequired="NO";
	var tagXmlComplete='<?xml version="1.0" encoding="UTF-8" standalone="yes"?><systemTag><person><personUUID>'+nbcu.sn.session.getUuid()+'</personUUID></person><tags>';

	if (tagXml != null )
	{
		tagFlag=1;
		var tagXmlString=tagXml;
		var tagXmlArray=tagXmlString.split(",");
		var noOfTags=tagXmlArray.length;
		var innerTagContent="";
		for(var i=0;i<noOfTags;i++)
		{
			innerTagContent=tagXmlArray[i];
			innerTagContentArray=innerTagContent.split(":");
			tagXmlComplete=tagXmlComplete+"<tag><classifier>"+innerTagContentArray[0]+"</classifier><tagText>"+innerTagContentArray[1]+"</tagText><type>SYSTEM</type></tag>";
		
		}

	  
	}
	if (typeof(showId) != "undefined")
	{
		tagFlag=1;
		tagXmlComplete=tagXmlComplete+"<tag><classifier>siteId</classifier><tagText>"+showId+"</tagText><type>SYSTEM</type></tag>";
	} 
	tagXmlComplete=tagXmlComplete+"</tags></systemTag>";

	
	if(tagFlag==1)
	{
		tagParamRequired=tagXmlComplete;
	}
	var submitButton = jqN(formObj).find("input[type='submit']");
	var btnText = jqN(submitButton).attr("value");

	jqN(submitButton).attr("value", "Posting comment..");
	jqN(submitButton).attr("disabled", "true");

	formContainerSelector = formContainerSelector || this.commentFormSelector;
	
	if (this.isValid(formObj) || this.isSaving == false)
	{
		this.isSaving = true;
		
		thanks = function(data)
		{
			if (jqN(data).find("status").text() != "" && jqN(data).find("status").text() == false)
			{
				if(msg = jqN(data).find("msg").text())
				{
					alert(msg);
				}

				jqN(submitButton).removeAttr('disabled');
				jqN(submitButton).attr("value", btnText);
				this.isSaving = false;
			}
			else
			{	
				jqN(formContainerSelector).fadeOut("fast", function()
				{
					THIS.template.display("thanks", THIS.commentFormSelector);
					jqN(formContainerSelector).fadeIn("fast");
					THIS.commentObj.renderComments();
					if (nbcu.sn.comment.getParam("commentCallback"))
					{
						eval(nbcu.sn.comment.getParam("commentCallback"));
					}
				});
			}
		}
		
		nbcu.sn.comment.setParam("commentText", formObj.message.value);  
		
		this.saveComment(thanks, contentSSUniqueKey, contentId, contentUrl, this.commentObj.getParam("contentType") || "", formObj.message.value, this.commentObj.getParam("siteId"),tagParamRequired);
	}
	else
	{			
		jqN(submitButton).removeAttr('disabled');
		jqN(submitButton).attr("value", btnText);
		this.isSaving = false;
	}
	
	return false;
});

Nbcu.Sn.Comment.method('getCommentByContent', function(callback, contentSSUniqueKey, contentID, contentURL, contentType, fromRow, toRow, startDate, endDate, orderBy)
{
	params = new Object();
	params.contentSSUniqueKey = contentSSUniqueKey || "";
	params.contentID = contentID || "";
	params.contentURL = contentURL || "";
	params.contentTypeCode = contentType || "";
	params.fromRow = fromRow || "";
	params.toRow = toRow || "";
	params.startDate = startDate || "";
	params.endDate = endDate || "";
	params.orderBy = orderBy || "";
	
	if (nbcu.config.getParam("facebookConnectEnabled") == "true") {
		params.commentSourceSystemType = 'facebook';
	}
	
	return nbcu.api.call("getCommentByContent", params, "sn", "snas", "DIRECT", "GET", callback);
});

Nbcu.Sn.Comment.method('saveComment', function(callback, contentSSUniqueKey, contentID, contentURL, contentType, commentText, siteId,tagParamRequired)
{
	params = new Object();
	params.contentSSUniqueKey = contentSSUniqueKey || "";
	params.contentID = contentID || "";
	//params.contentURL = contentURL || nbcu.util.common.getUrl();   SNAS TICKET # 8061
	params.contentURL = contentURL || "";
	params.contentType = contentType || "";
	params.commentText = commentText || "";
	params.siteId = siteId || "";
	
	if(tagParamRequired !="NO")
	{
		params.tagXML = tagParamRequired;
	}
	
	if (nbcu.config.getParam("facebookConnectEnabled") == "true" && nbcu.sn.session.isLoggedInToExternalPlatform('facebook'))
	{
		var videoWidgetEmbedSource = nbcu.app.scet.video.getWidgetEmbedSource();
		
		var videoURL = nbcu.util.common.encodeHtml(window.document.location);
		var videoTitle = unescape(nbcu.app.scet.video.getParam("assetTitle"));
		var commentBody = nbcu.sn.comment.getParam("commentText");
		var videoDesc = unescape(nbcu.app.scet.video.getParam("assetDescription"));
		var videoThumb = nbcu.app.scet.video.getParam('assetThumbnailUrl');
		var userInfo = readCookie("external_platform_user_info");
		var userInfoArray = new Array();
		userInfoArray = userInfo.split("%7C");
		var userName = escape(userInfoArray[2]);
		userName = userName.replace("+"," ");


		
		var attachment = 
			{
				"name" : userName+' commented on '+videoTitle,
				"href" : videoURL,
				"description" : videoDesc,
				"media" : 
					[{"type" : "video", 
						"video_src" : nbcu.util.common.encodeHtml(videoWidgetEmbedSource),
						"preview_img" : videoThumb,
						"video_link" : videoURL,
						"video_title" : videoTitle}]
			}
			
		var action_links = [{"text" : "Browse More Videos", "href" : "http://www.nbc.com/video/"}];
	
		embeddedPlayerManager.getPlayer(videoplayerDiv).hidePlayer();
		var callbackFunction = function() {
				embeddedPlayerManager.getPlayer(videoplayerDiv).unHidePlayer();
		};
		facebook_stream_publish(commentBody, attachment, action_links, '', null, callbackFunction, false);
		
	}
	
	return nbcu.api.call("addComment", params, "sn", "comment", "PROXY", "POST", callback);
});

Namespace("nbcu.sn.comment");
nbcu.sn.comment = new Nbcu.Sn.Comment();