﻿

$.CFUserWallDefaultResources = {
	globalWallPostWatermarkText: 'What\'s on your mind?',
	globalWallCommentWatermarkText: 'Write a comment...',
	globalViewMoreText: 'view more',
	globalViewLessText: 'view less',
	globalConfirmDeleteText: 'Are you sure you want to delete ?',
	globalCancelText: 'Cancel',
	globalWallCommentText: 'Comment',
	globalWallSeeMoreText: 'See More',
	globalErrorWhileProcessingText: 'There was a problem while processing your request'
};
var userWallResources = $.CFUserWallDefaultResources;

///#region Set Resources


$.setUserWallResources = function(options) {
	userWallResources = $.extend({}, $.CFUserWallDefaultResources, options || {});
};


var shareALinkTextWaterMark = 'http://';
var commentTextWaterMark = userWallResources.globalWallCommentWatermarkText;
///#endregion Set Resources
///#region Resource Declaration


var path = null;

// Initialize this and store globally for tracking state.
var currentPage = 1;

// Initialize this to 1, so that "Next" is disabled until
//  GetItemCount returns and we know there's a second page.
var lastPage = 1;
var pageLength = 10;
var postTextBoxRows = 3;
var postTextBoxColumns = 120;
var sharedLinksArray = new Array();
var tabSelected = 'wallactivity';
	///#endregion Resource Declaration
(function ($) {
    $.fn.cfWallComment = function (options) {
        var o = $.extend({}, $.fn.cfWallComment.defaults, options);
        var wcPostReadMoreSelector = o.wcPostReadMoreSelector;
        var wcTemplateID = o.wcTemplateID;
        var wcTextBoxContainerSelector = o.wcTextBoxContainerSelector;
        var wcActiveTextBoxContainerSelector = o.wcActiveTextBoxContainerSelector;
        var wallPostAndCommentsContainerSelector = o.wallPostAndCommentsContainerSelector;
        var wcOptionsCommentAnchorSelector = o.wcOptionsCommentAnchorSelector;
        var wcOptionsDeleteAnchorSelector = o.wcOptionsDeleteAnchorSelector;
        var wallPostIDSelector = o.wallPostIDSelector;
        var wcIDSelector = o.wcIDSelector;
        var wcActiveTextBoxSelector = o.wcActiveTextBoxSelector;
        var wcTextBoxSelector = o.wcTextBoxSelector;
        var wcContainerSelector = o.wcContainerSelector;
        var wcIndividualContainerSelector = o.wcIndividualContainerSelector;
        var wcPostContainerSelector = o.wcPostContainerSelector;
        var wcTextBoxContainer = $(wcTextBoxContainerSelector);
        var wcTextBox = wcTextBoxContainer.find(wcTextBoxSelector);
        var wcActiveTextBox = wcTextBoxContainer.find(wcActiveTextBoxSelector);

        var wallPostReadMoreLinkClickHandler = function (parentContainer) {
            parentContainer.addClass('axero-wall-entry-post-readmore-opened');
            return false;
        };

        var saveWallComment = function (wallComment, success, failure) {
            $.cfAjax({ url: o.addWallPostCommentURL,
                data: '{wc: ' + JSON.stringify(wallComment) + '}',
                success: success,
                error: failure
            });
        };

        var setWCDefaults = function (context) {
            context = $(context || document);
            $.each(context.find(wcTextBoxContainerSelector).find(wcTextBoxSelector), function (index, item) {
                $(item).Watermark(commentTextWaterMark);
            });
            $.each(context.find(wcActiveTextBoxContainerSelector).find(wcActiveTextBoxSelector), function (index, item) {
                var self = $(item);
                self.autoResize();
                self.keydown(function (e) {
                    if (e.keyCode == 13) {
                        if (e.shiftKey) {

                        }
                        else {
                            saveComment(self);
                        }
                    }
                });
            });

            var parent = context.find(wallPostAndCommentsContainerSelector);
            parent.find(wcOptionsDeleteAnchorSelector).click(function () {
                return wallPostCommentDeleteLinkClickHandler($(this));
            }).end().find(wcOptionsCommentAnchorSelector).click(function () {
                return wallPostCommentLinkClickHandler($(this));
            }).end().find(wcPostReadMoreSelector).click(function () {
                return wallPostReadMoreLinkClickHandler($(this).closest('div'));
            }).end().find(wcPostContainerSelector).find('span').expander({
                slicePoint: 400,  // default is 100
                expandText: userWallResources.globalViewMoreText, // default is 'read more...'
                collapseTimer: 0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
                userCollapseText: userWallResources.globalViewLessText   // default is '[collapse expanded text]'
            });
        };

        var wallPostCommentLinkClickHandler = function (instance) {
            var parent = instance.closest(wallPostAndCommentsContainerSelector);
            parent.find(wcTextBoxSelector).trigger('focus');
            parent.find(wcTextBoxContainerSelector).removeClass('hide-visiblity-absolute').addClass('visible-inherit');
            var wcTextBox = parent.find(wcTextBoxSelector);
            //$.scrollTo(wcTextBox,200);
            //wcTextBox.focus();
            return false;
        };

        var applyWallCommentTemplateAfterInsert = function (data, insertContainer) {

            var s = parseTemplate(document.getElementById(wcTemplateID).innerHTML, { wallComments: data });
            var container = $('<div/>').html(s);

            var current = container.appendTo(insertContainer).find(wcIndividualContainerSelector);

            current.find(wcPostContainerSelector).find('span').expander({
                slicePoint: 400,  // default is 100
                expandText: userWallResources.globalViewMoreText, // default is 'read more...'
                collapseTimer: 0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
                userCollapseText: userWallResources.globalViewLessText  // default is '[collapse expanded text]'
            });

            current.slideDown();


            current.find(wcOptionsDeleteAnchorSelector).click(function () {
                return wallPostCommentDeleteLinkClickHandler($(this));
            }).end().find(wcPostReadMoreSelector).click(function () {
                return wallPostReadMoreLinkClickHandler($(this).closest('div'));
            });

        };

        wcTextBox.live('focus', function () {
            var self = $(this);
            self.hide();
            self.closest(wcTextBoxContainerSelector).find(wcActiveTextBoxContainerSelector)
                .removeClass('hide-visiblity-absolute').addClass('visible-inherit')
                .find(wcActiveTextBoxSelector).focus();
        });

        wcActiveTextBox.live('blur', function () {
            if (this.value.length > 0) return;
            var self = $(this);
            self.closest(wcActiveTextBoxContainerSelector).addClass('hide-visiblity-absolute')
                .removeClass('visible-inherit')
                .end().val('');
            self.closest(wcTextBoxContainerSelector).find(wcTextBoxSelector).show().blur();
        });

        var saveComment = function(commentTextArea, success) {
            var insertContainer = commentTextArea.closest(wallPostAndCommentsContainerSelector)
                .find(wcContainerSelector);
            var postID = commentTextArea.closest(wallPostAndCommentsContainerSelector).find(wallPostIDSelector).val();

            if ($.trim(commentTextArea.val()) == '' || commentTextArea.val() == commentTextWaterMark) return false;

            var wallText = Communifire.Utilities.htmlEncode($.trim(commentTextArea.val()));
            wallText = wallText.replace( /\\/g , "\\\\");
            wallText = wallText.replace( /'/g , "\\'");
            commentTextArea.attr('disabled', true);

            var wc = new Communifire.Common.BusinessEntities.WallComment({
                    wallID: postID,
                    commentText: wallText
                });

            saveWallComment(wc, function(response) {
                applyWallCommentTemplateAfterInsert(response, insertContainer);
                commentTextArea.val('');
                commentTextArea.removeAttr('disabled');
                commentTextArea.trigger('resize');
                commentTextArea.focus();
            });

        };

        var wallPostCommentDeleteLinkClickHandler = function (instance) {
            var parentContainer = instance.closest(wcIndividualContainerSelector);
            var wallPostCommentID = parentContainer.find(wcIDSelector).val();
            var path = o.deleteWallPostCommentURL;
            customConfirm(userWallResources.globalConfirmDeleteText, function () {
                $.ajax({
                    type: 'POST',
                    url: path,
                    data: "{'wallPostCommentID':" + wallPostCommentID + "}",
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (msg) {
                        if ((msg != null) && (msg.d != null) && (msg.d)) {
                            parentContainer.slideUp('normal', function () { $(this).remove(); });
                        }
                    }
                });
            });
            return false;
        };

        var my = {
            setWCDefaults: setWCDefaults
        };
        return my;

    };
    $.fn.cfWallComment.defaults = {
        wcPostReadMoreSelector: '#read-more',
        wcTemplateID: 'wall-list-comment-template',
        wcTextBoxContainerSelector: 'div.axero-wall-entry-post-reply',
        wcActiveTextBoxContainerSelector: 'div.axero-wall-entry-post-reply-active',
        wallPostAndCommentsContainerSelector: 'div.axero-wall-entry-right',
        wcOptionsCommentAnchorSelector: '#axero-wall-entry-post-options-comment',
        wcOptionsDeleteAnchorSelector: '#axero-wall-entry-comment-post-options-delete',
        wallPostIDSelector: 'input#axero-wall-entry-wallID',
        wcIDSelector: 'input#axero-wall-entry-comments-wallCommentID',
        wcActiveTextBoxSelector: '#WCActiveTextBox',
        wcTextBoxSelector: '#WCTextBox',
        wcContainerSelector: 'div.axero-wall-entry-comments',
        wcIndividualContainerSelector: 'div.axero-wall-entry-comment',
        wcPostContainerSelector: 'div.axero-wall-entry-comment-post',
        addWallPostCommentURL: Communifire.buildCommonWSUrl('AddWallPostComment'),
        deleteWallPostCommentURL: Communifire.buildCommonWSUrl('DeleteWallPostComment')
    };
})(jQuery);

$.fn.cfWall = function (options) {
    var o = $.extend({}, $.fn.cfWall.defaults, options);


    var wallComment = $().cfWallComment();
    ///#region  Default code to run



    $('#divViewMoreWallPost').click(NextPage);
    $('ul.toggle').find('a').click(function (e) { e.preventDefault(); toggleLinksClickHandler(this); return false; });


    //DisplaysWallAndActivityContent(1);


    function toggleLinksClickHandler(aInstance) {
        $('ul.toggle').find('a').removeClass('selected');
        $(aInstance).addClass('selected');
        $('div.axero-wall-container').html(Communifire.loadingImage);
        var rel = $(aInstance).attr('rel');
        if (rel == 'wallactivity') {
            // $('#axero-my-status-input').slideDown('slow');
            currentPage = 1;
            tabSelected = 'wallactivity';
            DisplaysWallAndActivityContent(1);
        }
        else if (rel == 'activity') {

            currentPage = 1;
            tabSelected = 'activity';
            DisplaysRecentActivityContent(1);
            // $('#axero-my-status-input').slideUp('slow');
        }
        else if (rel == 'wall') {
            // $('#axero-my-status-input').slideDown('slow');
            currentPage = 1;
            tabSelected = 'wall';

            // Initialize this to 1, so that "Next" is disabled until
            //  GetItemCount returns and we know there's a second page.
            lastPage = 1;

            DisplaysWallContent(1);
            GetWallPostsCount();
        }
        return false;
    }

    ///#region DisplaysWallAndActivityContent
    function DisplaysWallAndActivityContent(currentPage) {
        /// <summary>This method displays the wall content</summary>
        /// <param name="pageNo" type="Integer">Current page number</param>
        ///#region For Spaces
        if (spaceID > 0) {
            path = o.getCombinedSpaceWallPostsAndActivitiesURL;
            $.ajax({
                type: "POST",
                url: path,
                data: "{'spaceID':" + spaceID + ",'pageLength':" + pageLength + ",'pageNo':" + currentPage + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    applyWallAndActivityTemplate(msg, true);
                    if (msg.d.length > 0) {
                        lastPage = currentPage + 1;
                    }
                    else {
                        lastPage = currentPage;
                    }
                    UpdatePaging();
                    var hashPath = window.location.hash;
                    if (hashPath != '' && hashPath != null && hashPath != undefined) {
                        $.scrollTo('a[name=' + window.location.hash.substring(1) + ']', { duration: 200 });
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $.showMessageBar({ message: userWallResources.globalErrorWhileProcessingText, delay: 3000 });
                }
            });
        }
        ///#endregion For Spaces
        else {

            path = o.getCombinedWallPostsAndActivitiesURL;
            $.ajax({
                type: "POST",
                url: path,
                data: "{'userID':" + toUserID + ",'pageNo':" + currentPage + ",'pageLength':" + pageLength + ",'wallContainer':'" + wallContainer + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    applyWallAndActivityTemplate(msg, true);
                    if (msg.d.length > 0) {
                        lastPage = currentPage + 1;
                    }
                    else {
                        lastPage = currentPage;
                    }
                    // Wireup appropriate paging functionality.
                    UpdatePaging();
                    var hashPath = window.location.hash;
                    if (hashPath != '' && hashPath != null && hashPath != undefined) {
                        $.scrollTo('a[name=' + window.location.hash.substring(1) + ']', { duration: 200 });
                    }

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $.showMessageBar({ message: userWallResources.globalErrorWhileProcessingText, delay: 3000 });
                }
            });
        }

    }
    ///#endregion


    ///#region DisplaysRecentActivityContent
    function DisplaysRecentActivityContent(currentPage) {
        /// <summary>This method displays the wall content</summary>
        /// <param name="pageNo" type="Integer">Current page number</param>
        ///#region For Spaces
        if (spaceID > 0) {
            path = o.getLatestSpaceActivityFeedssURL;
            $.ajax({
                type: "POST",
                url: path,
                data: "{'spaceID':" + spaceID + ",'pageLength':" + pageLength + ",'pageNo':" + currentPage + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    applyRecentActivityTemplate(msg);
                    if (msg.d.length > 0) {
                        lastPage = currentPage + 1;
                    }
                    else {
                        lastPage = currentPage;
                    }
                    UpdatePaging();
                    var hashPath = window.location.hash;
                    if (hashPath != '' && hashPath != null && hashPath != undefined) {
                        $.scrollTo('a[name=' + window.location.hash.substring(1) + ']', { duration: 200 });
                    }
                }
            });
        }
        ///#endregion For Spaces
        else {
            path = o.getCombinedActivityFeedsURL;
            $.ajax({
                type: "POST",
                url: path,
                data: "{'userID':" + toUserID + ",'pageNo':" + currentPage + ",'pageLength':" + pageLength + ",'wallContainer':'" + wallContainer + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    applyRecentActivityTemplate(msg);
                    if (msg.d.length > 0) {
                        lastPage = currentPage + 1;
                    }
                    else {
                        lastPage = currentPage;
                    }
                    // Wireup appropriate paging functionality.
                    UpdatePaging();
                    var hashPath = window.location.hash;
                    if (hashPath != '' && hashPath != null && hashPath != undefined) {
                        $.scrollTo('a[name=' + window.location.hash.substring(1) + ']', { duration: 200 });
                    }

                }
            });
        }

    }
    ///#endregion

    ///#region applyWallAndActivityTemplate

    function applyWallAndActivityTemplate(msg, forAppend) {
        var s = parseTemplate($("#wallAndActivity-list-template").html(), { wallAndActivityList: msg.d });
        var container = $('<div/>').html(s);
        var parentContainer = $('#axero-wall-container');
        if (currentPage == 1 && forAppend) parentContainer.html('');
        var current = (forAppend) ?
					$(container).appendTo(parentContainer).find('#axero-wall-entry') :
					$(container).prependTo(parentContainer).find('#axero-wall-entry');


        current.fadeIn();
        bindEventsToWallAndNewsFeedList(current);
    }
    ///#endregion applyRecentActivityTemplate

    ///#region applyRecentActivityTemplate

    function applyRecentActivityTemplate(msg) {
        var s = parseTemplate($("#recentActivity-list-template").html(), { recentActivityList: msg.d });
        if (currentPage == 1) {
            $('div.axero-wall-container').html(s);
        }
        else {
            $('div.axero-wall-container').append(s);
        }

    }
    ///#endregion applyRecentActivityTemplate


    ///#region  $('#btnPostScrap') click event handler

    $('input[id$=btnPostScrap]').click(function (e) { e.preventDefault(); return btnPostScrapClickHandler(); });

    ///#endregion $('#btnPostScrap') click event handler

    ///#region applyTemplate

    function applyTemplate(msg, forAppend) {

        var s = parseTemplate(document.getElementById('wall-list-template').innerHTML, { wallPosts: msg.d });
        var container = $('<div/>').html(s);
        var parentContainer = $('#axero-wall-container');
        if (currentPage == 1 && forAppend) parentContainer.html('');
        var current = (forAppend) ?
					$(container).appendTo(parentContainer).find('#axero-wall-entry') :
					$(container).prependTo(parentContainer).find('#axero-wall-entry');

        current.find('div.axero-wall-entry-post').find('span#wallPost').expander({
            slicePoint: 400,  // default is 100
            expandText: userWallResources.globalViewMoreText, // default is 'read more...'
            collapseTimer: 0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
            userCollapseText: userWallResources.globalViewLessText  // default is '[collapse expanded text]'
        });

        current.fadeIn();

        current.find('#axero-wall-entry-post-options-delete').click(function () {
            return wallPostDeleteLinkClickHandler($(this));
        }).end().find('#read-more').click(function () {
            return wallPostReadMoreLinkClickHandler($(this).closest('div'));
        }).end().find('#divImages').find('a.axero-wall-attach-link-videothumb').click(function () {
            return wallPostVideoThumbClickHandler($(this), $(this).attr('href'));
        });
        wallComment.setWCDefaults(current);

    }
    ///#endregion applyTemplate

    ///#region wallPostVideoThumbClickHandler

    function wallPostVideoThumbClickHandler(instance, linkURL) {
        var container = instance.closest('div.axero-wall-attach-link-preview-images');
        container.removeClass('axero-wall-attach-link-preview-images')
					.addClass('axero-wall-attach-link-preview-images-view-video');

        container.next('div.axero-wall-attach-link-preview-info')
					.removeClass('axero-wall-attach-link-preview-info')
					.addClass('axero-wall-attach-link-preview-infoview-video-clear');

        container.html(Communifire.loadingImage);
        var path = o.getVideoPlayerHTMLURL;
        $.ajax({
            type: "POST",
            url: path,
            data: "{'linkURL':'" + linkURL + "','width':" + o.sharedVideoPlayerWidth + ",'height':" + o.sharedVideoPlayerHeight + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                if (msg != null && msg.d != null) {
                    var data = msg.d.ResponseData;
                    container.html(msg.d.ResponseData);
                }
            }
        });
        return false;
    }

    ///#endregion wallPostVideoThumbClickHandler


    ///#region wallPostReadMoreLinkClickHandler

    function wallPostReadMoreLinkClickHandler($parentContainer) {
        $parentContainer.addClass('axero-wall-entry-post-readmore-opened');
        return false;
    }

    ///#endregion wallPostReadMoreLinkClickHandler

    ///#region wallPostCommentDeleteLinkClickHandler

    function wallPostDeleteLinkClickHandler($instance) {
        var $parentContainer = $instance.closest('div.axero-wall-entry');
        var wallPostID = $parentContainer.find('div.axero-wall-entry-right').find('input#axero-wall-entry-wallID').val();
        var path = o.deleteWallPostURL;
        customConfirm(userWallResources.globalConfirmDeleteText, function () {
            $.ajax({
                type: "POST",
                url: path,
                data: "{'wallPostID':" + wallPostID + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    if ((msg != null) && (msg.d != null) && (msg.d)) $parentContainer.slideUp("normal", function () { $(this).remove(); });
                }
            });
        });
        return false;
    }
    ///#endregion wallPostCommentDeleteLinkClickHandler

    ///#region btnPostScrapClickHandler
    function btnPostScrapClickHandler() {
        var $txtPostScrap = $('#txtPostScrap');
        var postText = ($txtPostScrap.val() == userWallResources.globalWallPostWatermarkText) ? '' : $.trim($txtPostScrap.val());
        if (postText == '' && shareLinkPreviewContainerData.linkHREF == null) return false;

        var wallText = Communifire.Utilities.htmlEncode(postText);
        //var wallTextWithSpaces=wallText.replace(/\'/g,'&nbsp;');
        wallText = wallText.replace(/\\/g, "\\\\");
        wallText = wallText.replace(/'/g, "\\'");


        $txtPostScrap.attr('disabled', true);
        var path = o.addWallPostURL;

        var sharedLinkHrefData = (shareLinkPreviewContainerData.linkHREF == null)
					? "'sharedLinkHref':null"
					: "'sharedLinkHref':'" + shareLinkPreviewContainerData.linkHREF + "'";

        var sharedLinkImageSrcData = (shareLinkPreviewContainerData.imageSRC == null)
					? "'sharedLinkImageSrc':null"
					: "'sharedLinkImageSrc':'" + shareLinkPreviewContainerData.imageSRC + "'";

        var sharedLinkDescriptionData = (shareLinkPreviewContainerData.description == null)
					? "'sharedLinkDescription':null"
					: "'sharedLinkDescription':'" + shareLinkPreviewContainerData.description.escapeForAjax() + "'";

        var sharedLinkTitleData = (shareLinkPreviewContainerData.title == null)
					? "'sharedLinkTitle':null"
					: "'sharedLinkTitle':'" + shareLinkPreviewContainerData.title.escapeForAjax() + "'";

        $.ajax({
            type: "POST",
            url: path,
            data: "{'fromUserID':" + fromUserID + ",'toUserID':" + toUserID + ",'wallpostText':'" + wallText + "','spaceID':"
						+ spaceID + "," + sharedLinkHrefData + "," + sharedLinkImageSrcData + "," + sharedLinkDescriptionData
						+ "," + sharedLinkTitleData + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //applyTemplateAfterInsert(msg);

                shareLinkPreviewContainerData.linkHREF = null;
                shareLinkPreviewContainerData.imageSRC = null;
                shareLinkPreviewContainerData.description = null;
                shareLinkPreviewContainerData.title = null;


                $('input[id$=btnPostScrap]').removeAttr('disabled');
                $('#SharedLinkHref').val('');
                $('#SharedLinkImageSrc').val('');
                $('#SharedLinkDescription').val('');
                $('#SharedLinkTitle').val('');
                $('#txtShareALinkURL').val('');
                $('#axero-wall-attach-link-preview').html('');
                $('.axero-wall-attach-slide-panel').slideUp('slow');
                $('.axero-wall-attachment-container').slideDown('slow');
                applyTemplate(msg, false);
                $.Watermark.HideAll();
                $txtPostScrap.val('');
                $txtPostScrap.attr({
                    rows: postTextBoxRows,
                    cols: postTextBoxColumns
                });
                $.Watermark.ShowAll();
                $txtPostScrap.removeAttr('disabled');
                sharedLinksArray = [];
            }
        });
    }
    ///#endregion btnPostScrapClickHandler

    ///#region GetWallPostsCount
    function GetWallPostsCount() {
        /// <summary>Get wall posts count</summary>

        if (spaceID > 0) {
            $.ajax({
                type: "POST",
                url: o.getSpaceWallPostsCountURL,
                data: "{'spaceID':" + spaceID + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    // msg.d will contain the total number of items, as
                    //  an integer. Divide to find total number of pages.
                    lastPage = Math.ceil(msg.d / pageLength);
                    lastPage = (lastPage == 0) ? 1 : lastPage;
                    // Wireup appropriate paging functionality.
                    UpdatePaging();
                }
            });
        }
        else {

            $.ajax({
                type: "POST",
                url: o.getWallPostsCountURL,
                data: "{'userID':'" + toUserID + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    // msg.d will contain the total number of items, as
                    //  an integer. Divide to find total number of pages.
                    lastPage = Math.ceil(msg.d / pageLength);
                    lastPage = (lastPage == 0) ? 1 : lastPage;
                    // Wireup appropriate paging functionality.
                    UpdatePaging();
                }
            });
        }

    }
    ///#endregion

    ///#region NextPage
    function NextPage(evt) {
        /// <summary>This method performs the logic to fill the next page</summary>
        /// <param name="evt" type="String">The event which is triggered</param>

        // Prevent the browser from navigating needlessly to #.
        evt.preventDefault();

        // Entertain the user while the previous page is loaded.
        DisplayProgressIndication();
        if (tabSelected == 'wallactivity') {

            DisplaysWallAndActivityContent(++currentPage);
        }
        else if (tabSelected == 'activity') {

            DisplaysRecentActivityContent(++currentPage);
        }
        else {
            // Load and render the next page of results, and
            //  increment the current page number.
            DisplaysWallContent(++currentPage);
        }

    }
    ///#endregion NextPage

    ///#region PrevPage
    function PrevPage(evt) {
        /// <summary>This method performs the logic to fill the previous page</summary>
        /// <param name="evt" type="String">The event which is triggered</param>

        // Prevent the browser from navigating needlessly to #.
        evt.preventDefault();

        // Entertain the user while the previous page is loaded.
        DisplayProgressIndication();

        // Load and render the previous page of results, and
        //  decrement the current page number.
        DisplaysWallContent(--currentPage);
    }
    ///#endregion

    ///#region DisplayProgressIndication
    function DisplayProgressIndication() {
        /// <summary>This method displays the progress indication</summary>

        $('#divViewMoreWallPost').addClass('loading');


        //		// Hide both of the paging controls,
        //		//  to avoid click-happy users.
        //		$('a.paging').hide();

        //		// Clean up our event handlers, to avoid memory leaks.
        //		$('a.paging').unbind();

        //		// Add our centered progress indicator animation to it.
        //		$('#search_content').html('<div class="loading"><img src="' + $.facebox.settings.loadingImage + '"/></div>');
    }
    ///#endregion DisplayProgressIndication

    ///#region DisplaysWallContent
    function DisplaysWallContent(pageNo) {
        /// <summary>This method displays the wall content</summary>
        /// <param name="pageNo" type="Integer">Current page number</param>

        ///#region For Spaces
        if (spaceID > 0) {
            path = o.getSpaceWallPostsAndWallCommentsURL;
            $.ajax({
                type: "POST",
                url: path,
                data: "{'spaceID':" + spaceID + ",'pageLength':" + pageLength + ",'pageNo':" + currentPage + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    applyTemplate(msg, true);
                    UpdatePaging();
                    var hashPath = window.location.hash;
                    if (hashPath != '' && hashPath != null && hashPath != undefined) {
                        $.scrollTo('a[name=' + window.location.hash.substring(1) + ']', { duration: 200 });
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $.showMessageBar({ message: userWallResources.globalErrorWhileProcessingText, delay: 3000 });
                }
            });
        }
        ///#endregion For Spaces

        ///#region For Community level
        else {
            path = o.getCombinedWallPostsAndWallComments;
            $.ajax({
                type: "POST",
                url: path,
                data: "{'userID':" + toUserID + ",'pageLength':" + pageLength + ",'pageNo':" + currentPage + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    applyTemplate(msg, true);
                    // Wireup appropriate paging functionality.
                    UpdatePaging();
                    var hashPath = window.location.hash;
                    if (hashPath != '' && hashPath != null && hashPath != undefined) {
                        $.scrollTo('a[name=' + window.location.hash.substring(1) + ']', { duration: 200 });
                    }

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $.showMessageBar({ message: userWallResources.globalErrorWhileProcessingText, delay: 3000 });
                }
            });
        }
        ///#endregion For Community level
    }
    ///#endregion

    ///#region UpdatePaging
    function UpdatePaging() {
        /// <summary>This method updated the visibility of next and previous links</summary>
        $('#divViewMoreWallPost').removeClass('loading');
        // If we're not on the last page, enable the "Next" link.
        if (currentPage == lastPage) {
            $('#divViewMoreWallPost').hide();
        }
        else {
            $('#divViewMoreWallPost').show();
        }
    }
    ///#endregion UpdatePaging

    // delete event
    $('#attach').bind("click", function () {

        $('#loader').html('<div align="center" id="load">' + Communifire.loadingImage + '</div>');
        $.post("/dummy.aspx?url=" + $('#url').val(),
					{
					}, function (response) {
					    $('#loader').html($(response).fadeIn('slow'));
					    //        $('.images img').hide();
					    $('#load').hide();
					    //        $('img#1').fadeIn();
					    //        $('#cur_image').val(1);
					});

    });



    $('#btnAttachLink').click(function () {
        return attachLinkClickHandler($('#txtShareALinkURL').val());
    });
    var isLoading = false;
    $('#txtPostScrap').keyup(function () {
        if (shareLinkPreviewContainerData.linkHREF == null) {

            var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
            var text = this.value;
            var mm = text.match(exp);
            var isAttached = false;

            if (sharedLinksArray.length > 0) {
                var linkWithNoResponseExist = false;

                for (var i = 0; i < mm.length; i++) {
                    var linkIsInArray = false;
                    for (var j = 0; j < sharedLinksArray.length; j++) {
                        if (mm[i] == sharedLinksArray[j].href) {
                            linkIsInArray = true;
                            if (sharedLinksArray[j].noResponse == true) {
                                //linkWithNoResponseExist = true;
                                break;
                            }
                            else {
                                //linkWithNoResponseExist = false;
                                //isAttached =

                                if (!isLoading) {

                                    isLoading = true;

                                    attachLinkClickHandler(mm[i], function (isAttached) {
                                        if (!isAttached) { sharedLinksArray[j].noResponse = true; }
                                        isLoading = false;
                                    });
                                }

                                //									if (!isAttached) {
                                //										sharedLinksArray[j].noResponse = true;
                                //									}
                                //									else {
                                //										break;
                                //									}
                            }
                        }
                        else {

                        }
                    } //end for j

                    //						if (isAttached) {
                    //							break;
                    //						}

                    if (!linkIsInArray) {
                        sharedLinksArray.push({
                            href: mm[i],
                            noResponse: false
                        });
                        if (mm != null && mm.length > 0) {
                            $('#txtShareALinkURL').val(mm[i]);
                            openAttachmentLinkClickHandler();
                            //								var isAttached = attachLinkClickHandler(mm[i]);
                            //								if (isAttached) {
                            //									sharedLinksArray[0].noResponse = true;
                            //									break;
                            //								}
                            if (!isLoading) {

                                isLoading = true;
                                attachLinkClickHandler(mm[i], function (isAttached) {
                                    if (!isAttached) { sharedLinksArray[j].noResponse = true; }
                                    isLoading = false;
                                });
                            }

                        }
                    }

                }

            }
            else {

                if (mm != null && mm.length > 0) {
                    sharedLinksArray.push({
                        href: mm[0],
                        noResponse: false
                    });
                    $('#txtShareALinkURL').val(mm[0]);
                    openAttachmentLinkClickHandler();
                    //						var isAttached = attachLinkClickHandler(mm[0]);
                    //						if (!isAttached) {
                    //							sharedLinksArray[0].noResponse = true;
                    //						}
                    //						attachLinkClickHandler(mm[0], function(isAttached) {
                    //							if (!isAttached) { sharedLinksArray[0].noResponse = true; }
                    //						});

                    if (!isLoading) {
                        isLoading = true;
                        attachLinkClickHandler(mm[0], function (isAttached) {
                            if (!isAttached) { sharedLinksArray[0].noResponse = true; }
                            isLoading = false;
                        });
                    }
                }

            }
        }


    });

    function attachLinkClickHandler(txtShareALinkURL, callback) {
        var postText = (txtShareALinkURL == shareALinkTextWaterMark) ? '' : $.trim(txtShareALinkURL);
        if (postText == '') return false;

        var isAttached = false;

        shareLinkPreviewContainerData.linkHREF = null;
        shareLinkPreviewContainerData.imageSRC = null;
        shareLinkPreviewContainerData.description = null;
        shareLinkPreviewContainerData.title = null;

        $('#axero-wall-attach-link-preview').html(Communifire.loadingImage);
        var path = o.attachShareALinkURL;
        $.ajax(
					{
					    type: "POST",
					    url: path,
					    data: "{'linkURL':'" + txtShareALinkURL + "'}",
					    contentType: "application/json; charset=utf-8",
					    dataType: "json",
					    success: function (msg) {
					        $('#axero-wall-attach-link-preview').html('');

					        var response = msg.d;
					        if (response != null) {
					            if (response.IsError == false) {
					                response.ResponseData.Description = Communifire.Utilities.htmlDecode(response.ResponseData.Description);
					                var responseData = response.ResponseData;
					                var a = new Array();

					                a.push(responseData);
					                var s = parseTemplate($("#wall-sharelink-template").html(), { wallShareALinks: a });
					                var doc = $('<div/>').html(s);
					                var divImages = doc.find('#divImages');
					                divImages.find('img').hide();
					                divImages.find('#1').show();

					                if (responseData.ImagesCount > 0) {
					                    if (responseData.ImagesCount == 1) {
					                        doc.find('.buttons').hide();
					                    }
					                }
					                else {
					                    divImages.hide();
					                    doc.find('.buttons').hide();

					                }
					                //doc.find('.editable').editable({ type: 'textarea' });
					                //.find('#divImages').find('img').hide().end().find('#1').fadeIn().end();

					                var previewContainer = $('#axero-wall-attach-link-preview');
					                previewContainer.html(doc.html());
					                previewContainer.find('#editable-textarea').editable({ type: 'textarea', onSubmit: onDescEdit });
					                previewContainer.find('#editable-text').editable({ editClass: 'textBox', onSubmit: onTitleEdit });

					                var imagesContainer = previewContainer.find('#divImages');
					                var currentItem = 1;
					                previewContainer.find('#chkNoImageForShareALink').click(function () {
					                    if (this.checked) {
					                        imagesContainer.hide();
					                        shareLinkPreviewContainerData.imageSRC = null;
					                        previewContainer.find('.buttons').hide();
					                    }
					                    else {
					                        var newImage = imagesContainer.find('#' + currentItem).show();
					                        shareLinkPreviewContainerData.imageSRC = newImage.attr('src');
					                        previewContainer.find('.buttons').show();
					                        imagesContainer.show();
					                    }
					                });



					                $('input[id$=btnPostScrap]').removeAttr('disabled');

					                shareLinkPreviewContainerData.linkHREF = responseData.LinkHREF;
					                shareLinkPreviewContainerData.imageSRC = imagesContainer.find('img#1').attr('src');
					                shareLinkPreviewContainerData.description = responseData.Description;
					                shareLinkPreviewContainerData.title = responseData.Title;


					                var totalItems = parseInt($('span[id$=\'spanTotalImages\']').html());
					                $('#currentItem').html(currentItem);
					                // next image
					                previewContainer.find('#next').bind("click", function () {
					                    if (currentItem < totalItems) {
					                        currentItem = currentItem + 1;
					                        $('#currentItem').html(currentItem);
					                        imagesContainer.find('img').hide();
					                        var newImage = imagesContainer.find('#' + currentItem).show();
					                        shareLinkPreviewContainerData.imageSRC = newImage.attr('src');
					                    }
					                    return false;

					                });
					                // prev image
					                previewContainer.find('#prev').bind("click", function () {
					                    if (currentItem > 1) {
					                        currentItem = currentItem - 1;
					                        $('#currentItem').html(currentItem);
					                        imagesContainer.find('img').hide();
					                        var newImage = imagesContainer.find('#' + currentItem).show();
					                        shareLinkPreviewContainerData.imageSRC = newImage.attr('src');


					                    }
					                    return false;
					                });
					                isAttached = true;
					                callback.call(this, true);
					            }
					            else {
					                callback.call(this, false);
					                isAttached = false;
					            }
					        }

					    },
					    error: function (jqXHR, textStatus, errorThrown) {
					        callback.call(this, false);
					        //isAttached = false;
					        //$.showMessageBar({ message: '<CFControl:JSResource runat="server" ResourceKey="VideoConversionFailedText" />' , delay:10000 });

					    }

					});
        return isAttached;
    }
    function onTitleEdit(content) {
        shareLinkPreviewContainerData.title = content.current;
    }
    function onDescEdit(content) {
        shareLinkPreviewContainerData.description = content.current;
    }
    $('#open-attachment-link').click(function () {
        return openAttachmentLinkClickHandler();
        // call some jquery method to clear the form

    });

    function openAttachmentLinkClickHandler() {
        $('#axero-wall-attach-link-preview').html('');
        shareLinkPreviewContainerData.linkHREF = null;
        shareLinkPreviewContainerData.imageSRC = null;
        shareLinkPreviewContainerData.description = null;
        shareLinkPreviewContainerData.title = null;
        $('input[id$=btnPostScrap]').attr('disabled', true);
        $('#axero-wall-attach-slide-panel').slideDown('slow');
        $('#axero-wall-attachment-container').slideUp('slow');
        return false;
    }

    $('#close-attachment-link').click(function () {
        $('input[id$=btnPostScrap]').removeAttr('disabled');
        shareLinkPreviewContainerData.linkHREF = null;
        shareLinkPreviewContainerData.imageSRC = null;
        shareLinkPreviewContainerData.description = null;
        shareLinkPreviewContainerData.title = null;
        $('#axero-wall-attach-link-preview').html('');
        $('#axero-wall-attach-slide-panel').slideUp('slow');
        $('#axero-wall-attachment-container').slideDown('slow');
        return false;
        // call some jquery method to clear the form

    });




    $(function () {
        $('#txtPostScrap').autoGrow().Watermark(userWallResources.globalWallPostWatermarkText);
        $('#txtShareALinkURL').Watermark(shareALinkTextWaterMark);
    });

    function bindEventsToWallAndNewsFeedList(current) {

        current.find('div.axero-wall-entry-post').find('span#wallPost').expander({
            slicePoint: 400,  // default is 100
            expandText: userWallResources.globalViewMoreText, // default is 'read more...'
            collapseTimer: 0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
            userCollapseText: userWallResources.globalViewLessText  // default is '[collapse expanded text]'
        });

        current.find('#axero-wall-entry-post-options-delete').click(function () {
            return wallPostDeleteLinkClickHandler($(this));
        }).end().find('#read-more').click(function () {
            return wallPostReadMoreLinkClickHandler($(this).closest('div'));
        }).end().find('#divImages').find('a.axero-wall-attach-link-videothumb').click(function () {
            return wallPostVideoThumbClickHandler($(this), $(this).attr('href'));
        });

        wallComment.setWCDefaults(current);
    }

    var my = {
        bindEventsToWallAndNewsFeedList: bindEventsToWallAndNewsFeedList,
        options: o,
        updatePaging: UpdatePaging
    };
    return my;

};

	$.fn.cfWall.defaults = {
		getCombinedSpaceWallPostsAndActivitiesURL: Communifire.buildCommonWSUrl('GetCombinedSpaceWallPostsAndActivities'),
		getCombinedWallPostsAndActivitiesURL: Communifire.buildCommonWSUrl('GetCombinedWallPostsAndActivities'),
		getLatestSpaceActivityFeedssURL: Communifire.buildCommonWSUrl('GetLatestSpaceActivityFeeds'),
		getCombinedActivityFeedsURL: Communifire.buildCommonWSUrl('GetCombinedActivityFeeds'),
		getVideoPlayerHTMLURL: Communifire.buildCommonWSUrl('GetVideoPlayerHTML'),
		addWallPostCommentURL: Communifire.buildCommonWSUrl('AddWallPostComment'),
		deleteWallPostURL: Communifire.buildCommonWSUrl('DeleteWallPost'),
		deleteWallPostCommentURL: Communifire.buildCommonWSUrl('DeleteWallPostComment'),
		addWallPostURL: Communifire.buildCommonWSUrl('AddWallPost'),
		getSpaceWallPostsCountURL: Communifire.buildCommonWSUrl('GetSpaceWallPostsCount'),
		getWallPostsCountURL: Communifire.buildCommonWSUrl('GetWallPostsCount'),
		getSpaceWallPostsAndWallCommentsURL: Communifire.buildCommonWSUrl('GetSpaceWallPostsAndWallComments'),
		getCombinedWallPostsAndWallComments: Communifire.buildCommonWSUrl('GetCombinedWallPostsAndWallComments'),
		attachShareALinkURL: Communifire.buildCommonWSUrl('AttachShareALink'),
	    sharedVideoPlayerWidth: 464,
		sharedVideoPlayerHeight: 261
	};



///#endregion  Default code to run
function SetReadMoreText(input, length) {
	if (input.length <= length) return input;
	var textToHide = input.substring(length);
	var visibleText = input.substring(0, length);
	var html = visibleText + '<span class="readmore-hellip">&nbsp;&hellip;&nbsp;</span>' + ('<span class="readmore">' + textToHide + '</span>');
	html = html + '<a id="read-more" title="' + userWallResources.globalWallSeeMoreText + '" href="#">' + userWallResources.globalWallSeeMoreText + '</a>';
	return html;
	
}

function BuildHTMLForWallPost(wallPost) {
	if (wallPost.WallContentType == 1) {
		return SetReadMoreText(wallPost.WallText, 400);
	}
	else if (wallPost.WallContentType == 2) {
		var a = new Array();
		a.push(wallPost);
		return parseTemplate($("#wall-sharelink-body-template").html(), { wallPosts: a });

	}

}



var currentInstance = null;
var isLnk = null;

var shareLinkPreviewContainerData = {
	title: null,
	description: null,
	imageSRC: null,
	linkHREF: null
};

