<%@ Reference VirtualPath="~/bitrix/components/bitrix/blog.post.comments/component.ascx" %>
<%@ Control Language="C#" Inherits="Bitrix.Blog.Components.BlogPostCommentsTemplate" EnableViewState="false" %>
<%@ Register TagPrefix="bx" TagName="CommentForm" Src="~/bitrix/controls/Blog/CommentForm.ascx" %>
<%@ Register TagPrefix="bx" Assembly="CommunicationUtility"  Namespace="Bitrix.CommunicationUtility" %>
<%@ Import Namespace="Bitrix.Services" %>
<%@ Import Namespace="Bitrix.Security" %>
<%@ Import Namespace="Bitrix.Blog" %>
<%@ Import Namespace="Bitrix.UI" %>

<%@ Import Namespace="Bitrix.Blog.Components" %>
<% if (Component.FatalError != BlogPostCommentsComponent.ErrorCode.None) { %>
	<div class="blog-content">
		<div class="blog-note-box blog-note-error">
			<div class="blog-note-box-text">
				<%= Component.GetErrorHtml(Component.FatalError) %>
			</div>
		</div>
	</div>
	<% return; %>
<% } %>
<script type="text/javascript">
	function <%= ClientID %>_ShowForm(div, commentId)
	{
		var d = div.nextSibling;
		while (d != null)
		{
			if (d.tagName == "DIV" && d.className == "blog-comment-form")
			{
				<%= Comment.GetAllocateScript("d", "commentId", true) %>
				<%= Comment.GetFocusScript() %>
				break;
			}
			d = d.nextSibling;
		}
	}
</script>

<div class="blog-content">
<div class="blog-comments" id="comments">
	<%if (Component.Paging.IsTopPosition) {%>
	<div class="blog-navigation-box blog-navigation-top">
		<div class="blog-page-navigation">
			<bx:IncludeComponent runat="server" ID="HeaderPager" ComponentName="bitrix:system.pager" Template="<%$ Parameters:PagingTemplate %>" CurrentPosition="top" CssClassPrefix="blog-" />
		</div>
	</div>
	<%} %>
	
	<% if (Component.Auth.CanCommentThisPost) { %>
	<div class="blog-add-comment">
		<a onclick="<%= ClientID %>_ShowForm(this.parentNode, 0);" href="javascript:void(0)"><b><%= GetMessage("AddComment") %></b></a>
	</div>
	<div class="blog-comment-form"></div>
	<% } %>
	
	<%
	float padding = 2.5f;
	bool hasComments = false;
	foreach (BlogPostCommentsComponent.CommentInfo comment in Component.Comments) 
	{
		if (!comment.BranchIsDeleted)
		{
			hasComments = true;
	%>
		<div id="comment<%= comment.Comment.Id %>" class="blog-comment" style="padding-left: <%= ((comment.Comment.DepthLevel - 1) * padding).ToString(".##", System.Globalization.NumberFormatInfo.InvariantInfo) %>em;">
	<%
			if (!comment.Comment.MarkedForDelete)
			{
	%>
			<div class="blog-comment-cont">
				<div class="blog-comment-cont-white">
					<div class="blog-comment-info">
						<div class="blog-author">
							<% if (comment.UserProfileHref != null) { %>
							<a class="blog-author-icon" href="<%= comment.UserProfileHref %>"></a><a href="<%= comment.BlogHref ?? comment.UserProfileHref %>"><%= comment.AuthorNameHtml %></a>
							<% } else { %>
							<span class="blog-author-icon" ></span><%= comment.AuthorNameHtml %>
							<% } %>
						</div>
						<div class="blog-comment-date" title="<%= comment.Comment.DateCreated %>"><%= comment.Comment.DateCreated.ToString("g") %></div>
						<% if (Component.Auth.CanViewIP) { %>
						<div class="blog-comment-author-ip">
							<a href="http://whois.domaintools.com/<%= Encode(UrlEncode(comment.Comment.AuthorIP)) %>"><%= Encode(comment.Comment.AuthorIP)%></a>
						</div>
						<% } %>
					</div>
					<div class="blog-comment-content">
						<% if (comment.Comment.Author != null && comment.Comment.Author.User != null && comment.Comment.Author.User.Image != null) { %>
						<div class="blog-comment-avatar"><img alt="" src="<%= comment.Comment.Author.User.Image.FilePath %>"  width="<%= comment.Comment.Author.User.Image.Width %>px"  height="<%= comment.Comment.Author.User.Image.Height %>px" /></div>
						<% } %>
						<%= comment.GetPostContent() %>
						<div class="blog-comment-meta">
							<% if (Component.Auth.CanCommentThisPost) { %>
							<span class="blog-comment-answer"><a href="javascript:void(0)" onclick="<%= ClientID %>_ShowForm(window.document.getElementById('comment<%= comment.Comment.Id %>'), <%= comment.Comment.Id %>);"><%= GetMessage("Reply") %></a></span>
							<span class="blog-vert-separator">|</span> 
							<% } %>
							<% if (comment.Parent != null) { %>
							<span class="blog-comment-parent"><a href="#comment<%= comment.Parent.Comment.Id %>"><%= GetMessage("Parent") %></a></span> 
							<span class="blog-vert-separator">|</span>
							<% } %>
							<span class="blog-comment-link"><a href="<%= comment.CommentHref %>" onclick="prompt('<%= JSEncode(GetMessageRaw("Confirm.Link")) %>', this.href); return false;" ><%= GetMessage("Link") %></a></span>
							<% if (comment.Auth.CanDeleteThisComment) { %>
							<span class="blog-vert-separator">|</span>
							<span class="blog-comment-delete"><a href="<%= GetOperationHref(DeleteOperation, comment.Comment.Id) %>" onclick="return confirm('<%= Encode(JSEncode(GetMessageRaw("Confirm.Delete"))) %>')"><%= GetMessage("Kernel.Delete") %></a></span>
							<% } %>
						</div>
					</div>
				</div>
			</div>
			
	<%
			} 
			else 
			{
	%>		<div class="blog-comment-cont">
				<div class="blog-comment-cont-white">
					<div class="blog-comment-content">
					<%= GetMessage("CommentDeleted") %>
					</div>
				</div>
			</div>
	<%
			}
	%>
			<div class="blog-clear-float">
			</div>
		</div>
		<% if (preview && Comment.ParentCommentId == comment.Comment.Id) { %>
		<div class="blog-comment-preview">
			<div id="commentPreview" class="blog-comment" style="padding-left: <%= (comment.Comment.DepthLevel * padding).ToString(".##", System.Globalization.NumberFormatInfo.InvariantInfo) %>em;">
				<div class="blog-comment-cont">
					<div class="blog-comment-cont-white">
						<div class="blog-comment-info">
							<div class="blog-author"><div class="blog-author-icon"></div><%= Encode(GetDisplayName()) %></div>
							<div class="blog-comment-date" title="<%= Encode(DateTime.Now.ToString()) %>"><%= Encode(DateTime.Now.ToString("g")) %></div>
						</div>
						<div class="blog-comment-content">
							<% Component.Preview(Comment.Text, CurrentWriter); %>
							<div class="blog-comment-meta">
								<span class="blog-comment-answer"><a href="javascript:void(0)"><%= GetMessage("Reply") %></a></span>
								<span class="blog-vert-separator">|</span>
								<span class="blog-comment-link"><a href="#commentPreview"><%= GetMessage("Link") %></a></span>
							</div>
						</div>
					</div>
				</div>
				<div class="blog-clear-float" ></div>
			</div>
		</div>
		<% } %>
		<% //if (!comment.Comment.MarkedForDelete && Component.Auth.CanCommentThisPost) { %>
		<div class="blog-comment-form"></div>
		<% //} %>
	<%
		}
	}
	%> 
	
	<% if ( Component.Auth.CanCommentThisPost) { %>
	
		<% if (hasComments) {%>
		<div class="blog-add-comment">
			<a onclick="<%= ClientID %>_ShowForm(this.parentNode, 0);" href="javascript:void(0)"><b><%= GetMessage("AddComment") %></b></a>
		</div>
		<%} %>
		
		<% if (preview && Comment.ParentCommentId == 0) { %>
		<div class="blog-comment-preview">
			<div id="commentPreview" class="blog-comment" style="padding-left: <%= (0 * padding).ToString(".##", System.Globalization.NumberFormatInfo.InvariantInfo) %>em;">
				<div class="blog-comment-cont">
					<div class="blog-comment-cont-white">
						<div class="blog-comment-info">
							<div class="blog-author"><div class="blog-author-icon"></div><%= Encode(GetDisplayName()) %></div>
							<div class="blog-comment-date" title="<%= Encode(DateTime.Now.ToString()) %>"><%= Encode(DateTime.Now.ToString("g")) %></div>
						</div>
						<div class="blog-comment-content">
							<% Component.Preview(Comment.Text, CurrentWriter); %>
							<div class="blog-comment-meta">
								<span class="blog-comment-answer"><a href="javascript:void(0)"><%= GetMessage("Reply") %></a></span>
								<span class="blog-vert-separator">|</span>
								<span class="blog-comment-link"><a href="#commentPreview"><%= GetMessage("Link") %></a></span>
							</div>
						</div>
					</div>
				</div>
				<div class="blog-clear-float" ></div>
			</div>
		</div>
		<% } %>
	<div class="blog-comment-form"></div>
	<% } %>
	
	<%if (Component.Paging.IsBottomPosition) { %>
	<div class="blog-navigation-box blog-navigation-bottom">
		<div class="blog-page-navigation">
			<bx:IncludeComponent runat="server" ID="FooterPager" ComponentName="bitrix:system.pager" Template="<%$ Parameters:PagingTemplate %>" CurrentPosition="bottom" CssClassPrefix="blog-" />
		</div>
	</div>
	<%} %>
</div>
	<% if (Component.Auth.CanCommentThisPost) { %>
	<bx:CommentForm runat="server" ID="Comment" Hidden="true" OnSubmit="Comment_Submit" OnPreview="Comment_Preview" />
	<% } %>
</div>

<script runat="server">
	private const string OperationParameter = "_action";
	private const string CsrfParameter = "_token";
	private const string SourceParameter = "_source";
	private const string IdParameter = "_id";
	private const string DeleteOperation = "delete-comment";
	private bool preview;
	

	string GetOperationHref(string operation, int id)
	{
		NameValueCollection query = HttpUtility.ParseQueryString(BXSefUrlManager.CurrentUrl.Query);
		query.Set(SourceParameter, ClientID.GetHashCode().ToString());
		query.Set(OperationParameter, operation);
		query.Set(IdParameter, id.ToString());
		query.Set(CsrfParameter, BXCsrfToken.GenerateToken());
		

		UriBuilder uri = new UriBuilder(BXSefUrlManager.CurrentUrl);
		uri.Query = query.ToString();
		return Encode(uri.Uri.ToString());
	}
	protected override void OnLoad(EventArgs e)
	{
		base.OnLoad(e);

		if (Component.FatalError != BlogPostCommentsComponent.ErrorCode.None)
		{
			Comment.Enabled = false;
			return;
		}
		if (!Component.Auth.CanCommentThisPost)
		{
			Comment.Enabled = false;	
		}
		else if (Component.IsGuest)
		{
			Comment.RequireUserName = CommentForm.FieldMode.Require;
			Comment.RequireUserEmail = Component.ShowGuestEmail ? (Component.RequireGuestEmail ? CommentForm.FieldMode.Require : CommentForm.FieldMode.Show) : CommentForm.FieldMode.Hide;
			Comment.RequireCaptcha = Component.RequireGuestCaptcha;
		}

		if (Request == null)
			return;
		if (Request.QueryString[OperationParameter] != DeleteOperation)
			return;
		if (Request.QueryString[SourceParameter] != ClientID.GetHashCode().ToString())
			return;
		if (!BXCsrfToken.CheckToken(Request.QueryString[CsrfParameter]))
			return;

		int id;
		if (!int.TryParse(Request.QueryString[IdParameter], out id) || id <= 0)
			return;
		
		Component.Hide(id);
	}
	private void Comment_Submit(object sender, CommentForm.SubmitEventArgs e)
	{
		if (!e.Success)
		{
			Comment.Hidden = false;
			string script =
				Comment.ParentCommentId != 0
				? ClientID + "_ShowForm(document.getElementById('comment" + Comment.ParentCommentId + "'), " + Comment.ParentCommentId + ");"
				: ClientID + "_ShowForm(document.getElementById('commentPreview').parentNode, 0);";
		
			ScriptManager.RegisterStartupScript(
				this, 
				GetType(), 
				"CommentError",
				script,
				true
			);
			return;
		}
		
		BlogPostCommentsComponent.CommentData data = new BlogPostCommentsComponent.CommentData();
		if (Comment.RequireUserName != CommentForm.FieldMode.Hide)
			data.UserName = Comment.UserName;
		if (Comment.RequireUserEmail != CommentForm.FieldMode.Hide)
			data.UserEmail = Comment.UserEmail;
		
		Component.AddComment(Comment.ParentCommentId, Comment.Text, data);
	}
	private void Comment_Preview(object sender, EventArgs e)
	{
		Comment.Hidden = false;
		string script = 
			Comment.ParentCommentId != 0
			? ClientID + "_ShowForm(document.getElementById('comment" + Comment.ParentCommentId + "'), " + Comment.ParentCommentId + ");"
			: ClientID + "_ShowForm(document.getElementById('commentPreview').parentNode, 0);";
		
		ScriptManager.RegisterStartupScript(
			this,
			GetType(),
			"CommentPreview",
			script,
			true
		);
		preview = true;
	}
	private string GetDisplayName()
	{
		if (Comment.RequireUserName != CommentForm.FieldMode.Hide)
			return Comment.UserName;
		return BXIdentity.Current.User.GetDisplayName();
	}
</script>