﻿//RELATED COMBOBOX PLUGIN
jQuery.fn.extend({
    Comments: function (arg) {
        $(this).each(function(){

            var Elem = $(this);
            var elementID = Elem.attr("id");

            var argObj = {
                PageSize: 10,
                RecordOffset: 0,
                SortedField: "CreatedOn",
                SortDirection: "asc",
                AddCommentTitle: "Add New Comment",
                CommentsTitle: "Comments",
                NameLabel: "Name:",
                CommentLabel: "Comment:",
                SubmitLabel: "Submit",
                FooterNote: "",
                Required: "*",
                AllowReplies: true,
                PostedByLabel: "Posted by ",
                OnLabel: " on ",
                FlagOffensiveLabel: "Flag Offensive",
                Loading : "Loading...",
                FirstLabel : "First",
                PreviousLabel : "Previous",
                NextLabel : "Next",
                LastLabel: "Last",
                MorePagesLabel: "...",
                ThankYouMessage: "",
                SubmitButtonImage: "",
                onSubmitComment: Agility.UGC.Plugins.Comments.SubmitComment,
                onEmptyComments: Agility.UGC.Plugins.Comments.onEmptyComments,
                onFlagOffensive: Agility.UGC.Plugins.Comments.onFlagOffensive,
                onCommentSubmitComplete: Agility.UGC.Plugins.Comments.onCommentSubmitComplete,
                validateData : Agility.UGC.Plugins.Comments.ValidateData
            };

            $.extend(argObj, arg);

            if (argObj.RelatedContentID == null || argObj.RelatedContentID == undefined) {
                var relatedContentID = Elem.attr("RelatedContentID");
                if (relatedContentID != null && relatedContentID != undefined && !isNaN(relatedContentID)) {
                    argObj.RelatedContentID = relatedContentID
                }
                else {
                    return;
                }
            }

            if (argObj.RecordTypeName == null || argObj.RecordTypeName == undefined) {
                var recordTypeName = Elem.attr("RecordTypeName");
                if (recordTypeName != null && recordTypeName != undefined && recordTypeName.length > 0) {
                    argObj.RecordTypeName = recordTypeName;
                }
                else {
                    return;
                }
            }

            Agility.UGC.Plugins.Comments.LoadComments(this, argObj);
        });
    }
});

Agility.RegisterNamespace("Agility.UGC.Plugins.Comments");    

(function(Comments) {
    
    var _container = null;
    var _currentComments = new Array();
    var _currentArgs = new Array();
    var _currentPage = 1;    
    var _totalPages = 1;

    Comments.LoadComments=function(elem, argObj){
        
        var CommentContainer = $(elem);
        _currentArgs = argObj;
        _container = CommentContainer;

        var html = "<div class='AgilityCommentsPlugin'>";        
        html+= _buildCommentContainerArea(argObj);
        html+= "<div class='Pager'></div>";
        html+= _buildCommentInputForm(argObj);
        html+= "</div>";

        CommentContainer.html(html);

        _loadComments(CommentContainer, argObj);

        $(".btnSubmit", CommentContainer).click(function(){
            argObj.onSubmitComment(CommentContainer, argObj.RecordTypeName, argObj.RelatedContentID, argObj.validateData);
            return false;
        });
    }

    Comments.onFlagOffensive = function(commentID){
        Agility.UGC.API.SetRecordFlag(commentID, Agility.UGC.API.RecordFlag.Abuse, null, function(data){
             if (data.ResponseType == Agility.UGC.API.ResponseType.OK) {
                alert("The Comment has been Flagged Offensive. Thank you for your submission.");
             }
        });
    }

    Comments.onEmptyComments = function(elem){
        $(".CommentContainer", elem).html("<p>No comments available.</p>");
    }

    Comments.ResetCommentForm=function(elem){
        $(".NameInput", elem).val("");
        $(".EmailInput", elem).val("");
        $(".WebsiteUrlInput", elem).val("");
        $(".CommentInput", elem).val("");
        $(".ParentRecordInput", elem).val("");
        $(".CancelReply", elem).click();

        $.each($(".Error", elem), function() {

            $(this).hide();
        });
    }

    Comments.ValidateData = function(comment, container) {

        if(comment!=null && comment.length==0){
            alert("Please add a comment before submitting");
            return;
        }

        return true;
    };

    Comments.SubmitComment = function(elem, RecordTypeName, RelatedContentID, validateData){
        var name = $(".NameInput", elem).val();
        var comment = $(".CommentInput", elem).val();
        var email = $(".Email", elem).val();
        var websiteUrl = $(".WebsiteUrl", elem).val();
        var parentRecordID = $(".ParentRecordInput", elem).val();

        if(validateData(comment, _container)){
         
            var comment = {
                ID: -1,
                RecordTypeName: RecordTypeName,
                RelatedContentID: RelatedContentID,
                Name: name,
                Comment: comment,
                Email: email,
                WebsiteUrl : websiteUrl,
                ParentRecordID: parentRecordID
            };

            Agility.UGC.API.SaveRecord(comment, function (data) {
                _currentArgs.onCommentSubmitComplete(data);
            });
        }
    }

    Comments.onCommentSubmitComplete = function(data){
        if (data.ResponseType == Agility.UGC.API.ResponseType.OK) {
             //alert("Comment added successfully");
             Comments.ResetCommentForm();

             $(".CommentSubmission", _container).html(_currentArgs.ThankYouMessage);
        }
        else {
            alert("There was an error submitting your comment:" + data.Message);
       }
    }

    function _buildCommentInputForm(argObj){
       var html="";
       html += "<div class='CommentSubmission'>";
       html += "<a name='PostComment-" + argObj.RelatedContentID + "'></a>";
       html +="<div class='Title'>" + argObj.AddCommentTitle + "</div>";
       html += "<div class='Name'><label>" + argObj.NameLabel + "</label><span class='Required'>" + argObj.Required + "</span><span class='Error Hidden NameError'>" + argObj.NameError + "</span><input type='text' id='txtCommentPluginName_"+ argObj.RelatedContentID + "' class='NameInput'/></div>";
       html += "<div class='Email'><label>" + argObj.EmailLabel + "</label><span class='Required'>" + argObj.Required + "</span><span class='Error Hidden EmailError'>" + argObj.EmailError + "</span><input type='text' id='txtCommentPluginEmail_"+ argObj.RelatedContentID + "' class='EmailInput'/></div>";
       html += "<div class='WebsiteUrl'><label>" + argObj.WebsiteUrlLabel + "</label><input type='text' id='txtCommentPluginWebsiteUrl_"+ argObj.RelatedContentID + "' class='WebsiteUrlInput'/></div>";
       html += "<div class='ReplyTo' style='display:none;'></div>";
       html += "<div class='Comment'><label>" + argObj.CommentLabel + "</label><span class='Required'>" + argObj.Required + "</span><span class='Error Hidden CommentError'>" + argObj.CommentError + "</span><textarea id='txtCommentPluginComment_"+ argObj.RelatedContentID + "' class='CommentInput'></textarea></div>";
       html += "<input type='hidden' id='txtCommentParentRecordID_"+ argObj.RelatedContentID + "' class='ParentRecordInput'/>";
       html += "<div class='CommentFooter'>" + argObj.FooterNote + "<div class='Submit'><a href='#' class='btnSubmit'><img src='" + argObj.SubmitButtonImage + "' alt='Submit' /></a></div><div class='Clear'></div></div>";
       html += "</div>";

       return html;
    }

    function _buildCommentContainerArea(argObj){
        var html ="";
        html+="<div class='CommentHeading Title'>" + argObj.CommentsTitle + " (<span class='Count'></span>)</div>";
        html+="<div class='CommentContainer'>" + argObj.Loading + "</div>";
        return html;
    }

    function _buildCommentPager(argObj, currentPage, totalPages) {

        if (totalPages > 1) {
            var morePages = "<span class='MorePages'>" + argObj.MorePagesLabel + "</span>";
            var html = "";
            if (currentPage != 1) {
            
                html += "<a class='First' href='#'>" + argObj.FirstLabel + "</a>";
                html += "<a class='Previous' href='#'>" + argObj.PreviousLabel + "</a>";
            }

            html += _pageHtml(1, currentPage);

            if (currentPage > 5)
            {
                html += morePages;
            }

            for (var i = Math.max(2, currentPage - 4); i <= Math.min(totalPages - 1, currentPage + 4); i++)
            {
                html += _pageHtml(i, currentPage);
            }

            if (currentPage < totalPages - 5)
            {
                html += morePages;
            }

            html += _pageHtml(totalPages, currentPage);

            if (currentPage != totalPages) {  
               
                html += "<a class='Next' href='#'>" + argObj.NextLabel + "</a>";
                html += "<a class='Last' href='#'>" + argObj.LastLabel + "</a>";
            }

            $(".AgilityCommentsPlugin .Pager").html(html);

            $.each($(".AgilityCommentsPlugin .Pager .GoToPage"), function() {

                $(this).unbind("click");

                if ($(this).hasClass("CurrentPage")) {

                    $(this).bind("click", function() {
                        return false;
                    });
                } else {

                    $(this).bind("click", function() {
                        var page = $(this).text();
                        _currentPage = Number(page);
                        _loadComments(_container, argObj);
                        return false;
                    });
                }
            });

            $(".AgilityCommentsPlugin .Pager .First").bind("click", function() {

                _currentPage = 1;
                _loadComments(_container, argObj);
                return false;
            });            

            $(".AgilityCommentsPlugin .Pager .Previous").bind("click", function() {

                _currentPage = Math.max(1, (_currentPage - 1));
                _loadComments(_container, argObj);
                return false;
            });

            $(".AgilityCommentsPlugin .Pager .Next").bind("click", function() {

                _currentPage = Math.min(_totalPages, (_currentPage + 1));
                _loadComments(_container, argObj);
                return false;
            });            

            $(".AgilityCommentsPlugin .Pager .Last").bind("click", function() {

                _currentPage = _totalPages;
                _loadComments(_container, argObj);
                return false;
            });

        } else {

            $(".AgilityCommentsPlugin .Pager").html("");
        }
    }

    function _pageHtml(pageNumber, currentPage) {

        return "<a class='GoToPage" + ((pageNumber == currentPage) ? " CurrentPage" : "") + "' href='#'>" + pageNumber + "</a>";
    }

    function _loadComments(elem, argObj){
            
            var commentSearchArg = {
                RelatedContentID: argObj.RelatedContentID,
                PageSize: argObj.PageSize,
                RecordOffset: (_currentPage - 1) * argObj.PageSize,
                SortedField: argObj.SortedField,
                SortDirection: argObj.SortDirection,
                RecordTypeName:  argObj.RecordTypeName,
                State: Agility.UGC.API.RecordState.Published
            };       

            Agility.UGC.API.SearchComments(commentSearchArg, function (data) {
					
                if (data.ResponseType == 0) {

                    _currentComments[argObj.RelatedContentID] = data.ResponseData.Records;
                    _totalPages = Math.ceil(data.ResponseData.TotalRecords / argObj.PageSize);

                    $(".CommentHeading .Count", elem).html(data.ResponseData.TotalRecords);

                    var topLevelItems = new Array();
                    var subItems = new Array();
                    ary = new Array();
                    for(var i=0; i<_currentComments[argObj.RelatedContentID].length; i++){
                        var parentRecordID = _currentComments[argObj.RelatedContentID][i].ParentRecordID;
                        if(parentRecordID=null || parentRecordID==undefined || parentRecordID<=0){
                            topLevelItems.push(data.ResponseData.Records[i]);
                        }   
                        else{
                            subItems.push(_currentComments[argObj.RelatedContentID][i]);
                        }
                    }
                    
                    var commentHtml = Comments.LoadCommentData(0, 0, topLevelItems, subItems, argObj);
                    $(".CommentContainer", elem).html(commentHtml);

                    _bindActionEvents(elem, argObj);

                    if(data.ResponseData.TotalRecords==0){
                        if(argObj.onEmptyComments!=null && argObj.onEmptyComments!=undefined){
                            if($.isFunction(argObj.onEmptyComments)){
                                argObj.onEmptyComments(elem);
                                return;
                            }
                        }
                    }

                    _buildCommentPager(argObj, _currentPage, _totalPages);
                }
                else{
                    $(".CommentContainer", elem).html("Error Loading Comments: " + data.Message);
                }
            });
    }    

    Comments.LoadCommentData = function(recordID, level, topLevelItems, subItems, argObj) {
		
		if (level > 5) {
            return "";
        }

        var childAry = new Array();
        if(level == 0 && recordID==0){
            childAry = topLevelItems;
        }
        else{
		    childAry = $.grep(subItems, function(item) {
			    return item.ParentRecordID == recordID;	
		    });
        }
		
		var html = "";
		
		var isAlt = false;
		for (var i = 0; i<childAry.length; i++) {
			var comment = childAry[i];
			html += Comments.GetCommentHTML(comment, level, isAlt, argObj);
			html += Comments.LoadCommentData(comment.ID, level+1, topLevelItems, subItems, argObj);

            isAlt = !isAlt;

		}
		return html;
	}

	Comments.GetCommentHTML = function(comment, level, isAlternate, argObj){
        
        var html="";     
        
        if (level == undefined || level == null || level== NaN) {
            level = 0;
        }

		var margin = (level * 30);

        var altClass = "";
        if(isAlternate && level == 0){
            altClass = " AltRow";
        }
        else if(level>0){
            altClass = " SubItem";
        }

		html += "	<div class='CommentRow" + altClass +"' style='margin-left: "+margin+"px' id='pnlComment_"+comment.ID+"' contentID='" + comment.ID +"' commentLevel='"+ comment.CommentLevel + "' parentRecordID='" + comment.ParentRecordID + "'>";
        html += "			<div class='CommentDescription'><p>" + comment.Comment + "</p></div>";
		html += "			<div class='PostDetails'><p>" + argObj.PostedByLabel + "<span class='Name'>" + comment.Name + '</span>' + argObj.OnLabel + comment.CreatedOn + "</p></div>";

        if (argObj.AllowReplies) {
            html += "			<div class='Reply'><input class='CommentReply' type='Button' Value='Reply' commentID='" + comment.ID + "' replyTo='" + comment.Name + "'></div>";
        }

        html += "           <div class='Flag'><a class='FlagOffensive' href='#' commentID='" + comment.ID + "'>" +  argObj.FlagOffensiveLabel + "</a></div>";
        html += "           <div class='Clear'></div>";
		html += "	</div>";	

        return html;
    }

    function _bindActionEvents(elem, argObj){
        $(".FlagOffensive", elem).click(function(){
            var commentID = $(this).attr('commentID');
            argObj.onFlagOffensive(commentID);
        });

        $(".CommentReply", elem).click(function(){
            var commentID = $(this).attr('commentID');
            var replyTo = $(this).attr('replyTo');
           _setParentRecordID(elem, commentID, replyTo, argObj);
        });
    }

    function _setParentRecordID(elem, commentID, replyTo, argObj){
        var parentInput = $(".ParentRecordInput", elem);

        parentInput.val(commentID);

        var message = "<div class='CancelReply'><a class='CancelReply' href='#'>Cancel Reply</a></div>";
        
        message +="Replying to comment";
        if(replyTo!=null && replyTo!=undefined && replyTo.length>0){
            message+= " from '" + replyTo + "'";
        }

        for(var i=0; i<_currentComments[argObj.RelatedContentID].length; i++){
            if(_currentComments[argObj.RelatedContentID][i].ID == commentID){
                message+= "<div class='CommentPreview'>" + _currentComments[argObj.RelatedContentID][i].Comment + "</div>";
            }
        }

        $(".ReplyTo", elem).html(message);
        location.href="#PostComment-" + argObj.RelatedContentID;

        $(".ReplyTo", elem).slideDown('fast');

        $(".CancelReply", elem).click(function(){

            $(".ReplyTo").slideUp('fast');
            parentInput.val("");

             $(".ReplyTo", elem).html("");
        });

    }
	
})(Agility.UGC.Plugins.Comments);
