﻿
(function()
{
	BSC.UI.Comment = function()
	{
		var localcache = {};

		var load = function(p1, p2, p3)
		{
			var guid = p1;
			var id = p2;
			var type = p3;
			localcache[guid] = { id: id, type: type };

			var w = BSC.UI.Ws.Get(guid);
			var query = w.query ? "&" + w.query : "";

			var query = "?__guid=" + guid + "&type=" + type + query;
			$.ajax({
				type: "GET",
				url: "/Ajax/Content/CommentsList" + query,
				data: {},
				contentType: 'text/html; charset=utf-8',
				dataType: "html",
				beforeSend: (function(xml) { xml.setRequestHeader("Ajax", "true"); }),
				success: function(res)
				{
					// Html
					$("#" + guid + "_commentlist").removeClass().html(res);
					$("#" + guid + "_commentloader").hide();

					BSC.E.MapHrefs();
					$("#" + guid + " a.delete_comment").unbind().click(BSC.UI.Comment.Delete);
					
					var json = $("#" + guid + "_commentjson").getValue();
					var data = BSC.D.JSON.Parse(json);
					if (data)
					{
						// Paging: IsNextPage, IsPreviousPage, PageIndex, PageSize, TotalCount, TotalPage
						var options = { pagekey: "commentpage", prev: "_commentprev", next: "_commentnext", down: "_commentdowm", pageindex: "_commentpageindex", pagecount: "_commentpagecount", indexview: "_commentindexview" };
						BSC.UI.Paging.Add(guid, data, BSC.UI.Comment.ReRenderCurrent, options);
					}
					BSC.UI.HideStatus(guid, 200);
				}
			});
		};


		var reRenderCurrent = function(p1)
		{
			var guid = p1;
			var type = localcache[guid].type;

			var w = BSC.UI.Ws.Get(guid);
			var query = w.query ? "&" + w.query : "";

			var query = "?__guid=" + guid + "&type=" + type + query;
			$.ajax({
				type: "GET",
				url: "/Ajax/Content/CommentsList" + query,
				data: {},
				contentType: 'text/html; charset=utf-8',
				dataType: "html",
				beforeSend: (function(xml) { xml.setRequestHeader("Ajax", "true"); }),
				success: function(res)
				{
					// Html
					$("#" + guid + "_commentlist").removeClass().html(res);
					$("#" + guid + "_commentloader").hide();
					BSC.E.MapHrefs();
					$("#" + guid + " a.delete_comment").unbind().click(BSC.UI.Comment.Delete);
					BSC.UI.HideStatus(guid, 200);
				}
			});
		};

		var add = function(e)
		{
			var data = e.data;
			var comment = BSC.U.CleanHtml($("#" + data.guid + "_comment").getValue());
			if (!BSC.D.P.IsLoggedIn())
			{
				var w = BSC.UI.Ws.Get(data.guid);
				BSC.UI.AlertLogin(w.path);
				return;
			}
			if (comment.length == 0)
			{
			    alert(BSC.T.Get("JS.BSC.UI.Comment.add.Comment"));
				return false;
			}
			// Validating input data
			if (!BSC.R.TextField.test(comment))
			{
				//<object>(.*?)</object>
				//				var html = $(comment);
				//				var regex = new RegExp("<object(.*?)>(.*?)</object>", "g");
				//				var r = regex.exec(comment);
				//				do
				//				{
				//					if (!r) break;
				//					var ww = r;
				//					r = (new RegExp("<object>(.*?)</object>", "g")).exec(comment);
				//				}
				//				while (r != null);

				var p = new BSC.D.Param("BSC.WS.JS.Comment.Add");
				p.Add("id", data.id);
				p.Add("type", data.type);
				p.Add("comment", comment);
				BSC.D.Send(p, "Content.Comment", "Add", function(data)
				{
					var guid = this.d;
					var t = $("#" + guid + "_comment").val("");
					var c = data.d.comments[0];
					// må ikke nå hertil hvis comment ikke er added  
					if (!c)
					{
						if (!data.d.validlogin)
						{
							var w = BSC.UI.Ws.Get(data.guid);
							BSC.UI.AlertLogin(w.path);
						}
						return;
					}

					// TODO: remove from comments
					if (localcache[guid].comments.commentscount == 0)
						BSC.UI.Comment.RemoveComments(guid);

					if ($("#" + guid + "_commentlist div.nocomment"))
						BSC.UI.Comment.EnableCommentButtons(guid);

					localcache[guid].comments.commentscount += 1;

					var list = $("#" + guid + "_commentlist");
					var entry = BSC.D.Ts.Get("CommentEntry");
					entry = entry.replace(/\{comment\}/g, c.comment.replace(/\n/g, "<br/>"));
					entry = c.gender ? entry.replace(/\{gender\}/g, "male") : entry.replace(/\{gender\}/g, "female");
					entry = entry.replace(/\{commentid\}/g, c.id);
					entry = entry.replace(/\{pictureid\}/g, c.pictureid);
					entry = entry.replace(/\{profileid\}/g, c.profileid);
					entry = entry.replace(/\{name\}/g, c.name);
					entry = entry.replace(/\{alt\}/g, c.name);
					entry = entry.replace(/\{date\}/g, c.date);
					entry = entry.replace(/\{number\}/g, "#" + c.number);
					entry = entry.replace(/\{time\}/g, c.time);
					entry = entry.replace(/\{profileid\}/g, c.profileid);
					entry = (c.owner) ? entry.replace(/\{visible\}/g, "shown") : entry.replace(/\{visible\}/g, "hidden");
					entry = entry.replace(/\{border\}/g, "borderbottom");

					list.prepend(entry);
					if (c.owner)
					{
						$("#" + c.id + "_deletecomment").bind("click", { guid: guid }, BSC.UI.Comment.Delete);
					}

					$("#" + c.profileid + "_gotoprofile").click(BSC.UI.Comment.GO);
					$("#" + c.profileid + "_profilelink").click(BSC.UI.Comment.GO);
				}, null, data.guid);
			}
		};

		var bind = function(p1, p2, p3)
		{
			var guid = p1;
			var id = p2;
			var type = p3;
			localcache[guid] = { id: id, type: type };
			
			$("#" + guid + "_commentsnext").click(BSC.UI.Comment.OnCommentNextPageClick);
			$("#" + guid + "_commentsprev").click(BSC.UI.Comment.OnCommentPrevPageClick);

			$("#" + guid + "_pageviewbottom table").click(BSC.UI.Comment.GoToPageBottom);
			$("#" + guid + "_pageviewtop table").click(BSC.UI.Comment.GoToPageTop);

			var w = BSC.UI.Ws.Get(guid);
			if (w)
			{
				var jQ = BSC.U.ParseQuery(w.query, { id: '' });
				var id = null;
				if (jQ && jQ.id)
				{
					id = jQ.id;
				}

				if ($("#" + guid + "_addcomment"))
					$("#" + guid + "_addcomment").bind("click", { guid: guid, id: id, type: localcache[guid].type }, BSC.UI.Comment.Add);
            }

		};

		var unbind = function(p1)
		{
			var guid = p1;
			$("#" + guid + "_addcomment").unbind();
			$("#" + guid + "_commentsnext").unbind();
			$("#" + guid + "_commentsprev").unbind();
			$("#" + guid + "_content a.down").unbind();
			$("#" + guid + "_commentlist a.downright").unbind();
			$("#" + guid + "_pageviewbottom table").unbind();
			$("#" + guid + "_pageviewtop table").unbind();
		};

		return {
			Load: load,
			ReRenderCurrent: reRenderCurrent,
			/// <summary>Adds new comment</summary>
			/// <param name="e">Event information</param>
			Add: add,
			Bind: bind,
			Unbind: unbind,

			/// <summary>Retrieves the comments for the specific type and initialises caching</summary>
			/// <param name="guid">Unique identifier for selected window</param>
			/// <param name="fkeyid">Unique identifier for the type requesting comments</param>
			/// <param name="type">The type that request comments</param>
			LoadComments: function(guid, fkeyid, type, title, subtitle)
			{
				localcache[guid] = {};
				localcache[guid].comments = {};
				//Init page size and number
				// TODO: Make editable if necessary               
				var pagenumber = 0;
				var pagesize = 0;

				localcache[guid].comments.fkeyid = fkeyid;
				localcache[guid].comments.pagenumber = pagenumber;
				localcache[guid].comments.pagesize = pagesize;
				localcache[guid].comments.type = type;

				var p = new BSC.D.Param("BSC.WS.JS.Comment.Get");
				p.Add("FkeyID", fkeyid);
				p.Add("type", type);
				p.Add("pagesize", pagesize);
				p.Add("pagenumber", pagenumber);
				BSC.D.Send(p, "Content.Comment", "Get", function(data)
				{
					if (data)
					{
						var comments = data.d.comments;
						var commentscount = data.d.count;
						BSC.UI.Comment.Render(guid, comments, commentscount, title, subtitle);
					}
				}, null, guid);
			},
	
			/// <summary>Render the comments</summary>
			/// <param name="guid">Unique identifier for selected window</param>
			/// <param name="comments">The comments to render</param>
			/// <param name="commentscount">Number of comments</param>
//			Render: function(guid, comments, commentscount, title, subtitle)
//			{
//				// Init Comments paging
//				BSC.UI.Comment.RemoveComments(guid);

//				var pagemax = Math.max(Math.ceil(commentscount / cache[guid].comments.pagesize), 1);
//				cache[guid].comments.pagemax = pagemax;
//				cache[guid].comments.commentscount = commentscount;
//				if (cache[guid].comments.pagenumber > pagemax)
//				{
//					cache[guid].comments.pagenumber = pagemax;
//					//render den side som er pagemax
//					BSC.UI.Comment.CommentGoPage(guid, cache[guid].comments.pagenumber);
//				}
//				cache[guid].comments["page" + cache[guid].comments.pagenumber] = comments;
//				$("#" + guid + "_commentdescription").html("Page " + cache[guid].comments.pagenumber + " of " + pagemax);

//				$("#" + guid + "_commenttitle").html(title);
//				$("#" + guid + "_commentsubtitle").html(subtitle);
//				// Enable disable comment buttons       

//				if (commentscount == 0)
//				{
//					BSC.UI.Comment.DisableCommentButtons(guid);
//				}
//				else if ($("#" + guid + "_commentlist div.nocomment"))
//				{
//					BSC.UI.Comment.EnableCommentButtons(guid);
//					if (comments && comments.length > 0)
//					{
//						var list = $("#" + guid + "_commentlist");
//						var l = comments.length;
//						for (i = l - 1; i >= 0; i--)
//						{
//							var c = comments[i];
//							var entry = BSC.D.Ts.Get("CommentEntry");
//							entry = entry.replace(/\{comment\}/g, c.comment.replace(/\n/g, "<br/>"));
//							entry = c.gender ? entry.replace(/\{gender\}/g, "male") : entry.replace(/\{gender\}/g, "female");
//							entry = entry.replace(/\{commentid\}/g, c.id);
//							entry = entry.replace(/\{pictureid\}/g, c.pictureid);
//							entry = entry.replace(/\{profileid\}/g, c.profileid);
//							entry = entry.replace(/\{name\}/g, c.name);
//							entry = entry.replace(/\{alt\}/g, c.name);
//							entry = entry.replace(/\{date\}/g, c.date);
//							entry = entry.replace(/\{number\}/g, "#" + c.number);
//							entry = entry.replace(/\{time\}/g, c.time);
//							entry = (c.owner) ? entry.replace(/\{visible\}/g, "shown") : entry.replace(/\{visible\}/g, "hidden");
//							entry = (i == l - 1) ? entry.replace(/\{border\}/g, "") : entry.replace(/\{border\}/g, "borderbottom")
//							list.prepend(entry);
//							if (c.owner)
//							{
//								$("#" + c.id + "_deletecomment").bind("click", { guid: guid }, BSC.UI.Comment.Delete);
//							}
//							$("#" + c.profileid + "_gotoprofile").click(BSC.UI.Comment.GO);
//							$("#" + c.profileid + "_profilelink").click(BSC.UI.Comment.GO);
//						}
//					}
//				}
//				BSC.UI.Comment.Bind(guid);
//			},


			/// <summary>Retrieves comments for the new page</summary>
			/// <param name="guid">Unique identifier for selected window</param>
			/// <param name="fkeyid">Unique identifier for the profile being watched</param>
			/// <param name="type">What type the comments are for.(Profiles or pictures comments)</param>
			/// <param name="pagesize">Size of comment page</param>
			/// <param name="pagenumber">The number of the page</param>
//			Get: function(guid, fkeyid, type, pagesize, pagenumber)
//			{
//				var p = new BSC.D.Param("BSC.WS.JS.Comment.Get");
//				p.Add("FkeyID", fkeyid);
//				p.Add("type", type);
//				p.Add("pagesize", pagesize);
//				p.Add("pagenumber", pagenumber);
//				BSC.D.Send(p, "Content.Comment", "Get", BSC.UI.Comment.ReRender, null, guid);
//			},

			/// <summary>Callback function. Prepares the input data so comments can be rendered</summary>
			/// <param name="data">Comments data</param>
//			ReRender: function(data)
//			{
//				if (data)
//				{
//					var guid = this.d;
//					var comments = data.d.comments;
//					var commentscount = data.d.count;
//					BSC.UI.Comment.RemoveComments(guid);
//					BSC.UI.Comment.Render(guid, comments, commentscount);
//				}
//			},

			/// <summary>Removes the comment shown in the given window</summary>
			/// <param name="guid">Unique identifier for selected window</param>
//			RemoveComments: function(guid)
//			{
//				$("#" + guid + "_commentlist div.section").remove();
//				$("#" + guid + "_commentlist div.nocomment").remove();
//				$("#" + guid + "_commentlist div.section a").unbind();
//			},
			/// <summary>Deletes the comment clicked</summary>
			/// <param name="e">Event information</param>
			Delete: function(e)
			{
				var eventdata = e.data;
				var guid = eventdata.guid;
				var el = BSC.E.GetTarget(e);
				var t = (el.id).split("_");
				var commentid = t[0];
				$("#" + commentid + "_deletecomment").unbind("click");
				$("#" + commentid + "_entirecomment").remove();
				var p = new BSC.D.Param("BSC.WS.JS.Comment.Delete");
				p.Add("commentid", commentid);
				BSC.D.Send(p, "Content.Comment", "Delete", function()
				{
					localcache[guid].comments.commentscount -= 1;
					localcache[guid].comments["page" + cache[guid].comments.pagenumber] = null;
					if (cache[guid].comments.commentscount == 0)
					{
						BSC.UI.Comment.DisableCommentButtons(guid);
						return;
					}
					BSC.UI.Comment.CommentGoPage(guid, localcache[guid].comments.pagenumber);
				}, null, BSC.UI.Comment.Error);
			},

			/// <summary>Called when error message from server is retrieved. Shows the error message</summary>			
			Error: function()
			{
				//use boolmessage		       
				alert("Comment wasn't deleted");
			},

			/// <summary>Opens the profile clicked</summary>
			/// <param name="e">Event information</param>
//			GO: function(e)
//			{
//				var el = BSC.E.GetTarget(e);
//				var t = (el.id).split("_");
//				var profileid = t[0];
//				GO("/profile/id=" + profileid);
//			},

			/// <summary>Enable buttons</summary>
			/// <param name="guid">Unique identifier for selected window</param>
			EnableCommentButtons: function(guid)
			{
				$("#" + guid + "_pageviewbutton").removeClass("inactive_down");
				$("#" + guid + "_pageviewbutton").addClass("down");

				$("#" + guid + "_pageviewbuttonbottom").removeClass("inactive_downright");
				$("#" + guid + "_pageviewbuttonbottom").addClass("downright");

				$("#" + guid + "_commentsnext").removeClass("inactive_rightdown");
				$("#" + guid + "_commentsnext").addClass("rightdown");

				$("#" + guid + "_commentsprev").removeClass("inactive_prevsingle");
				$("#" + guid + "_commentsprev").addClass("prevsingle");

				$("#" + guid + "_content a.down").click(BSC.UI.Comment.OnPageViewClick);
				$("#" + guid + "_commentlist a.downright").click(BSC.UI.Comment.OnPageViewClick);
			},

			/// <summary>Disalbe buttons</summary>
			/// <param name="guid">Unique identifier for selected window</param>
			DisableCommentButtons: function(guid)
			{
				$("#" + guid + "_content a.down").unbind();
				$("#" + guid + "_commentlist a.downright").unbind();

				$("#" + guid + "_pageviewbutton").removeClass("down");
				$("#" + guid + "_pageviewbutton").addClass("inactive_down");

				$("#" + guid + "_pageviewbuttonbottom").removeClass("downright");
				$("#" + guid + "_pageviewbuttonbottom").addClass("inactive_downright");

				$("#" + guid + "_commentsnext").removeClass("rightdown");
				$("#" + guid + "_commentsnext").addClass("inactive_rightdown");

				$("#" + guid + "_commentsprev").removeClass("prevsingle");
				$("#" + guid + "_commentsprev").addClass("inactive_prevsingle");
				$("#" + guid + "_commentlist").prepend("<div class=\"nocomment\"><span>" + BSC.T.Get("JS.BSC.UI.Comment.DisableCommentButtons.BeTheFirst") + "</span></div>");
			},

			/// <summary>Cathces on next comment page click event. Sets next pagenumber.</summary>
			/// <param name="e">Event information</param>
			OnCommentNextPageClick: function(e)
			{
				var el = BSC.E.GetTarget(e);
				var t = (el.id).split("_");
				var guid = t[0];
				if (localcache[guid].comments.pagemax == 1) { return; }
				var pn = (localcache[guid].comments.pagenumber == localcache[guid].comments.pagemax) ? localcache[guid].comments.pagenumber = 1 : localcache[guid].comments.pagenumber += 1;
				BSC.UI.Comment.CommentGoPage(guid, pn);
			},

			/// <summary>Cathces on previous comment page click event. Sets previous pagenumber.</summary>
			/// <param name="e">Event information</param>
			OnCommentPrevPageClick: function(e)
			{
				var el = BSC.E.GetTarget(e);
				var t = (el.id).split("_");
				var guid = t[0];
				if (localcache[guid].comments.pagemax == 1) { return; }
				var pn = (localcache[guid].comments.pagenumber == 1) ? calocalcacheche[guid].comments.pagenumber = localcache[guid].comments.pagemax : localcache[guid].comments.pagenumber -= 1;
				BSC.UI.Comment.CommentGoPage(guid, pn);
			},

			/// <summary>Cathces page selector event. Shows all pages dropdown menu and binds events</summary>
			/// <param name="e">Event information</param>
			OnPageViewClick: function(e)
			{
				var el = BSC.E.GetTarget(e);
				var t = (el.id).split("_");
				var guid = t[0];
				var newRow = 1;
				var temp = 0;
				if (el.className.toLowerCase() == "down")
				{
					if ($("#" + guid + "_pageviewtop")[0].className.toLowerCase() == "paginationwrap comments top")
					{
						$("#" + guid + "_pageviewtop").addClass("none");
						return;
					}
					$("#" + guid + "_pageviewtop").removeClass("none");
					$("#" + guid + "_pageviewtop td").remove();

					for (i = 0; i < localcache[guid].comments.pagemax; i++)
					{
						if (i == 0)
						{
							$("#" + guid + "_pageviewtop table").append("<tr id=" + guid + "_" + newRow + "></tr>");
						}
						temp = newRow + 9;
						if (i >= temp)
						{
							newRow += 10;
							$("#" + guid + "_pageviewtop table").append("<tr id=" + guid + "_" + newRow + "></tr>");
						}
						var count = i + 1;
						$("#" + guid + "_" + newRow + "").append("<td><a id=" + guid + "_" + count + "_link>" + count + "</a></td>");
					}
				}
				else
				{
					if ($("#" + guid + "_pageviewbottom")[0].className.toLowerCase() == "paginationwrap comments bottom")
					{
						$("#" + guid + "_pageviewbottom").addClass("none");
						return;
					}
					$("#" + guid + "_pageviewbottom").removeClass("none");
					$("#" + guid + "_pageviewbottom td").remove();

					for (i = 0; i < localcache[guid].comments.pagemax; i++)
					{
						if (i == 0)
						{
							$("#" + guid + "_pageviewbottom table").append("<tr id=" + guid + "_" + newRow + "></tr>");
						}
						temp = newRow + 9;
						if (i >= temp)
						{
							newRow += 10;
							$("#" + guid + "_pageviewbottom table tr").after("<tr id=" + guid + "_" + newRow + "></tr>");
						}
						var count = i + 1;
						$("#" + guid + "_" + newRow + "").append("<td><a id=" + guid + "_" + count + "_link>" + count + "</a></td>");
					}
				}
			},

			/// <summary>Cathces the specific page selected event for page selector shown in the buttom. Insures that that page is shown</summary>
			/// <param name="e">Event information</param>   
			GoToPageBottom: function(e)
			{
				var el = BSC.E.GetTarget(e);
				var t = (el.id).split("_");
				var guid = t[0];
				var pn = t[1];
				$("#" + guid + "_pageviewbottom").addClass("none");
				BSC.UI.Comment.CommentGoPage(guid, pn);
			},

			/// <summary>Cathces the specific page selected event for page selector shown in the top. Insures that that page is shown</summary>
			/// <param name="e">Event information</param>   
			GoToPageTop: function(e)
			{
				var el = BSC.E.GetTarget(e);
				var t = (el.id).split("_");
				var guid = t[0];
				var pn = t[1];
				$("#" + guid + "_pageviewtop").addClass("none");
				BSC.UI.Comment.CommentGoPage(guid, pn);
			},

			/// <summary>Checks if the page requestet is cachet</summary>
			/// <param name="guid">Unique identifier for selected window</param>     
			/// <param name="pagenumber">The number of the requestet page</param>     
			CommentGoPage: function(guid, pagenumber)
			{
				localcache[guid].comments.pagenumber = pagenumber;
				if (localcache[guid].comments["page" + pagenumber])
				{
					BSC.UI.Comment.Render(guid, localcache[guid].comments["page" + pagenumber], localcache[guid].comments.commentscount);
				}
				else
				{
					BSC.UI.Comment.Get(guid, localcache[guid].comments.fkeyid, localcache[guid].comments.type, localcache[guid].comments.pagesize, localcache[guid].comments.pagenumber);
				}
			}
		};
	} ();
})();
