﻿var Comments = (
    function($) {
        return {
            AddCommentUrl: "",
            GetCommentsUrl: "",

            Init: function(data) {
                AddCommentUrl = data.AddCommentUrl;
                GetCommentsUrl = data.GetCommentsUrl;

                //////////////////////////////////////////////////////////////////////////////
                // blog entry listing page

				$('a[rel=commentSummary]').click(function() {
					
					// Get the entry id
					var id = $(this).parents('li').attr('id').split('-')[1];
					var data = {
						entryId : id
					};
					var target = $(this);
					// Load the comment html just before/above the comment summary
					var comments = $('<div></div>');
					// Now give this comments list a unique id, format "comments-itemTypeId-itemId"
					{
						// We need the itemTypeId and the ItemId to figure out which item the comment belongs to
						var itemTypeId = $('input[name=itemTypeId]').val();
						// For e.g the blog entry, the format of the element id is "entry-entryId"
						var itemId = target.parents('li[id^=entry-]').attr('id').split('-')[1];	
						var commentsId = 'comments-' + itemTypeId + '-' + itemId;
						comments.attr('id', commentsId);
					}
					// Load the comments from the server into the new div
					comments.load(GetCommentsUrl, data, function() {
						comments.append(BuildCloseCommentsAnchor('close-comments-' + id));
						comments.css('display', 'none');
						// Insert into the DOM
						target.parent().before(comments);
						comments.show('slow');
						
						// Hide the comments summary
						target.parents('p[rel=comments]').hide();
						// Hook in the handlers for the submit button
						resetHandlers();	
					});
					
					return false;
				});
				
				var BuildCloseCommentsAnchor = function(id) {
					var anchor = $('<a href="">Hide Comments</a>');
					anchor.click(function() {
						var target = $(this);
						// Show the comments summary
						var parentItem = target.parents('li[id^=entry-]');
						$('p[rel=comments]', parentItem).show();
							
						// Hide the comments
						target.parent().hide('slow', function() {
							// Remove the comments div from the DOM
							$('div[id^=comments-]', parentItem).remove();	
						});
						
						
						return false;
					});
					return anchor;
				}

                //////////////////////////////////////////////////////////////////////////////
                // Single blog entry page (not really used)

				var resetHandlers = function() {
					// First unbind all handlers
					var b = $('form[id^=commentForm] input[type=submit]');
					$('form[id^=commentForm] input[type=submit]').unbind('click');
					
					// Add new comment handlers for any existing buttons, ensuring we unbind old ones
					$('form[id^=commentForm] input[type=submit]').unbind('click').click(function() {
	                    // Gather post data
	                    var form = $(this).parents('form[id^=commentForm]');
	                    var comment = $('textarea', form).val();
						var itemTypeId = $('input[name=itemTypeId]').val(); 
	                    var mainCommentList = form.parents('div[id^=commentsList-]');
						var id = mainCommentList.attr('id').split('-')[1];
	                    var data = {
	                        itemId: id,
							itemTypeId: itemTypeId,
	                        commentContent: comment
	                    };
	                    // Send the request
	                    $.post(AddCommentUrl, data, function(result) {
	                        // Clear the error list (though it might not exist but that doesn't matter)
	                        $('#errorList').remove();
	                        // If the request wasn't successful then let the user know why
	                        if (!result.success) {
	                            renderErrors(result.errors);
	                            return false;
	                        }
	
	                        // Post was successful
	
	                        // Clear the text area
	                        $('textarea', form).val('');
	                        var data = result.data;
	
	                        // Clone the template row, set its data from the server's response, and insert it into the comment list
	                        var newRow = $('li[id^=comment-][class=template]:first').clone();
	                        newRow.attr('id', 'comment-' + data.Id);
	                        $('p[rel=meta]', newRow).html(data.UserDisplayName + " : " + data.PublishDateShortString);
	                        $('p[rel=content]', newRow).html(data.CommentContent);
	
	                        mainCommentList.children('ul:first').append(newRow);
	                        newRow.show('slow', function() { newRow.removeClass('template'); });
							
							// Update the number of comments in the summary
							var parentItem = form.parents('li[id^=entry-]');
							var commentSummary = $('p[rel=comments]', parentItem);
							var anchor = $('a', commentSummary);
							var commentCount = 1;
							// Update the count if there were previous comments i.e '2 Comment(s)'
							if (!isNaN(anchor.html()[0])) {
								var comment = anchor.html().split(' ')[0];
								var commentCount = parseInt(comment);
								commentCount++;	
							}
							
							anchor.html(commentCount + ' Comment(s)');
	
	                    }, "json");
	
	                    return false;
	                });	
				};
                

                var renderErrors = function(errors) {
                    // Create a list
                    var errorList = $('<ul></ul>');
                    errorList.attr('id', 'errorList').addClass('validation-summary-errors');
                    // Append all errors
                    for (var i = 0; i < errors.length; i++) {
                        var item = $('<li></li>');
                        item.html(errors[i]);
                        errorList.append(item);
                    }
                    // Insert the list into the DOM just before the comment textarea
                    $('textarea[name=commentContent]').before(errorList);
                }
            }
        }
    })(jQuery);
