﻿/// <reference path="~/Content/Scripts/jquery-1.3.2-vsdoc.js" />
/// <reference path="~/Content/Scripts/tools-0.1.0.js" />
/*
* CommentsWebService - should provide CRUD operations
*/

(function ($) {

    $.extend({

        comments: new function () {

            this.defaults = {
                Debug: false,
                PageKey: "",
                Pagename: "",
                AppPath: "",
                GetPerRequest: 10,
                TreeDepth: 2,
                CommentsWebService: "/DesktopModules/InvenManager.Comments/Comment.asmx",
                FooterTemplate: "",
                FooterId: "",
                alreadyLoaded: 0,
                IsModerated: false,
                OnCommentAdded: function (comment) { },
				CommentTextId: "#comments-textarea",
				PostButtonId: "#comment-post-button",
				UserCanReply: false
            };

            this.construct = function (options) {

                return this.each(function () {
                    var $this;
                    var config = $.extend($.comments.defaults, options);

                    // store common expression for speed
                    $this = $(this);

                    //var alreadyLoaded = 0;

                    LoadComments($this, config);
					
					var textarea = $(config.CommentTextId);
					//textarea.val("");
					var btn = $(config.PostButtonId)
					btn.bind("click", function(){
						if (!Tools.Trim(textarea.val())){
							alert("Comment can not be empty.");
						} else {
							var request = {
								pageKey: config.PageKey,
								comment: textarea.val(),
								pageName: config.PageName,
								GetPerRequest: config.GetPerRequest
							};

							Tools.Ajax({
								url: config.AppPath + config.CommentsWebService + "/Create",
								data: request,
								success: function (data) {
									Tools.Log("comment posted", config);
									textarea.attr("disabled","disabled");
									btn.val("Comment Posted!");
									btn.attr("disabled","disabled");
									
									if (config.IsModerated == "0") {
									    config.alreadyLoaded = 0;
									    $("#comments").html(""); 
									    LoadComments($this, config);
                                    }
								}
							});
						}
					});
                });

            }; // constructor

            function LoadComments(comments, config) {

                var url = config.AppPath + config.CommentsWebService + "/Read";

                var request = {
                    pageKey: config.PageKey,
                    parentId: 0,
                    skip: config.alreadyLoaded,
                    take: config.GetPerRequest
                };

                Tools.Ajax({
                    url: config.AppPath + config.CommentsWebService + "/Read",
                    data: request,
                    success: function (data) {
                        Tools.Log("comments loaded", config);
                        AppendComments(data, comments, config);
                        UpdateFooter(data, comments, config);
                    }
                });

            };

            function AppendComments(data, comments, config) {
                if (!data.Items) Tools.Log("response doesn't contains Items", config);

                if (data.Items != null && data.Items.length > 0) {
                    if (data.Items[0].CommentId == null) {
                        alert("All returned from web service objects must have 'CommentId' property!");
                        return;
                    }

					$.each(data.Items, function (i, item) {
						// generate comment by replacing tokens with model's values
						var content = Tools.Format(config.CommentsTemplate, item);
						var id = "comment" + item.CommentId;
						var comment = $(content);
						comment.attr("id", id);

						comments.append(comment);
						config.alreadyLoaded++;

						// rise OnCommentAdded 
						var addedComment = $("#" + id, comments);
						config.OnCommentAdded(addedComment, item);
					});
				}
            }

            function UpdateFooter(data, comments, config) {
                Tools.Log("Footer Updating", config);
                var template = config.FooterTemplate;
                var model = {
                    loaded: config.alreadyLoaded,
                    total: data.Total
                };
                var newFooter = Tools.Format(template, model)
                $(config.FooterId).html(newFooter);

                var showMoreLink = $("#show-more", config.Footer);
                if (config.alreadyLoaded == data.Total) showMoreLink.hide();

                showMoreLink.bind("click", function (e) {
                    LoadComments(comments, config);
                    return false;
                });

            }
 
        } // comments

    }); // extend

    // extend plugin scope
    $.fn.extend({
        comments: $.comments.construct
    });

})(jQuery);
