﻿/// <reference path="../jquery-1.4.4.js" />
/// <reference path="~/Assets/scripts/main.js" />
/// <reference path="~/Assets/scripts/tiny_mce/tiny_mce.js" />

$.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 resources = $.CFUserWallDefaultResources;

///#region Set Resources


$.setUserWallResources = function(options) {
	resources = $.extend({}, $.CFUserWallDefaultResources, options || {});
};


///#endregion Set Resources
///#region Resource Declaration
; (function($) {

	///#endregion Resource Declaration

	$.fn.cfWall = function(options) {
		var o = $.extend({}, $.fn.cfWall.defaults, options);




		///#region  Default code to run


		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 postTextWaterMark = resources.globalWallPostWatermarkText;
		var shareALinkTextWaterMark = 'http://';
		var commentTextWaterMark = resources.globalWallCommentWatermarkText;
		var postTextBoxRows = 3;
		var postTextBoxColumns = 120;
		var sharedLinksArray = new Array();
		var tabSelected = 'wallactivity';

		$('#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: resources.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: resources.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 });
			//		if (currentPage == 1) {
			//			$('div.axero-wall-container').html(s);
			//		}
			//		else {
			//			$('div.axero-wall-container').append(s);
			//		}
			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');

			//		$(container).appendTo(parentContainer).find('#axero-wall-entry').fadeIn() :
			//		$(container).prependTo(parentContainer).find('#axero-wall-entry').fadeIn();

			current.find('div.axero-wall-entry-post').find('span#wallPost').expander({
				slicePoint: 400,  // default is 100
				expandText: resources.globalViewMoreText, // default is 'read more...'
				collapseTimer: 0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
				userCollapseText: resources.globalViewLessText  // default is '[collapse expanded text]'
			});

			current.fadeIn();

			current.find('div.axero-wall-entry-comment-post').find('span').expander({
				slicePoint: 400,  // default is 100
				expandText: resources.globalViewMoreText, // default is 'read more...'
				collapseTimer: 0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
				userCollapseText: resources.globalViewLessText   // default is '[collapse expanded text]'
			});

			$.each(current.find('#axero-wall-entry-post-reply').hide().find('#txtPostScrap'), function(index, item) {
				$(item).autoGrow().Watermark(commentTextWaterMark);
			});
			current.find('#axero-wall-entry-comment-post-options-delete').click(function() {
				return wallPostCommentDeleteLinkClickHandler($(this));
			}).end().find('#axero-wall-entry-post-options-delete').click(function() {
				return wallPostDeleteLinkClickHandler($(this));
			}).end().find('#axero-wall-entry-post-reply-btnSubmitComment').click(function() {
				return btnSubmitCommentClickHandler($(this));
			}).end().find('#axero-wall-entry-post-reply-cancel').click(function() {
				return wallPostReplyCancelButtonClickHandler($(this));
			}).end().find('#axero-wall-entry-post-options-comment').click(function() {
				return wallPostCommentLinkClickHandler($(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'));
			});


		}
		///#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 applyWallCommentTemplateAfterInsert

		function applyWallCommentTemplateAfterInsert(msg, insertContainer) {


			var s = parseTemplate(document.getElementById('wall-list-comment-template').innerHTML, { wallComments: msg.d });
			var container = $('<div/>').html(s);

			var current = container.appendTo(insertContainer).find('#axero-wall-entry-comment');

			current.find('div.axero-wall-entry-comment-post').find('span').expander({
				slicePoint: 400,  // default is 100
				expandText: resources.globalViewMoreText, // default is 'read more...'
				collapseTimer: 0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
				userCollapseText: resources.globalViewLessText  // default is '[collapse expanded text]'
			});

			current.slideDown();


			current.find('#axero-wall-entry-comment-post-options-delete').click(function() {
				return wallPostCommentDeleteLinkClickHandler($(this));
			}).end().find('#read-more').click(function() {
				return wallPostReadMoreLinkClickHandler($(this).closest('div'));
			});
		}

		///#endregion applyWallCommentTemplateAfterInsert

		///#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: resources.globalViewMoreText, // default is 'read more...'
				collapseTimer: 0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
				userCollapseText: resources.globalViewLessText  // default is '[collapse expanded text]'
			});

			current.fadeIn();

			current.find('div.axero-wall-entry-comment-post').find('span').expander({
				slicePoint: 400,  // default is 100
				expandText: resources.globalViewMoreText, // default is 'read more...'
				collapseTimer: 0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
				userCollapseText: resources.globalViewLessText // default is '[collapse expanded text]'
			});

			$.each(current.find('#axero-wall-entry-post-reply').hide().find('#txtPostScrap'), function(index, item) {
				$(item).autoGrow().Watermark(commentTextWaterMark);
			});
			current.find('#axero-wall-entry-comment-post-options-delete').click(function() {
				return wallPostCommentDeleteLinkClickHandler($(this));
			}).end().find('#axero-wall-entry-post-options-delete').click(function() {
				return wallPostDeleteLinkClickHandler($(this));
			}).end().find('#axero-wall-entry-post-reply-btnSubmitComment').click(function() {
				return btnSubmitCommentClickHandler($(this));
			}).end().find('#axero-wall-entry-post-reply-cancel').click(function() {
				return wallPostReplyCancelButtonClickHandler($(this));
			}).end().find('#axero-wall-entry-post-options-comment').click(function() {
				return wallPostCommentLinkClickHandler($(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'));
			});

		}
		///#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 + "'}",
				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 btnSubmitCommentClickHandler

		function btnSubmitCommentClickHandler($instance) {
			var $commentTextArea = $instance.parent().find('textarea');
			var $insertContainer = $instance.parent().prev();
			var postID = $instance.parent().parent().find('input#axero-wall-entry-wallID').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 path = o.addWallPostCommentURL;
			$.ajax({
				type: "POST",
				url: path,
				data: "{'postID':" + postID + ",'fromUserID':" + fromUserID + ",'toUserID':" + toUserID + ",'wallPostCommentText':'" + wallText + "'}",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function(msg) {
					applyWallCommentTemplateAfterInsert(msg, $insertContainer);
					$.Watermark.HideAll();
					$commentTextArea.val('');
					$commentTextArea.attr({
						rows: postTextBoxRows,
						cols: postTextBoxColumns
					});
					$.Watermark.ShowAll();
					$commentTextArea.removeAttr('disabled');
				}
			});
		}
		///#endregion btnSubmitCommentClickHandler

		///#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(resources.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 wallPostCommentDeleteLinkClickHandler

		function wallPostCommentDeleteLinkClickHandler($instance) {
			var $parentContainer = $instance.closest('div.axero-wall-entry-comment');
			var wallPostCommentID = $parentContainer.find('div.axero-wall-entry-comments-right').find('input#axero-wall-entry-comments-wallCommentID').val();
			var path = o.deleteWallPostCommentURL;
			customConfirm(resources.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;
		}
		///#endregion wallPostCommentDeleteLinkClickHandler

		///#region	

		function wallPostCommentLinkClickHandler($instance) {
			if ($instance.html() === resources.globalWallCommentText) {
				//$instance.parent().next().next().show('slow');
				$instance.closest('div.axero-wall-entry-right').find('div.axero-wall-entry-post-reply').slideDown();
				$instance.html(resources.globalCancelText);
			}
			else {
				//$instance.parent().next().next().hide('slow');
				$instance.closest('div.axero-wall-entry-right').find('div.axero-wall-entry-post-reply').slideUp();
				$instance.html(resources.globalWallCommentText);
			}
			return false;
		}
		///#endregion wallPostCommentLinkClickHandler

		///#region wallPostReplyCancelButtonClickHandler

		function wallPostReplyCancelButtonClickHandler($instance) {
			var $parentContainer = $instance.parent();
			$parentContainer.hide('slow');
			$.Watermark.HideAll();
			$parentContainer.find('textarea').val('');
			$parentContainer.find('textarea').attr({
				rows: postTextBoxRows,
				cols: postTextBoxColumns
			});
			$.Watermark.ShowAll();
			$instance.closest('div.axero-wall-entry-right').find('div.axero-wall-entry-post-options').find('a#axero-wall-entry-post-options-comment').html(resources.globalWallCommentText);
			return false;
		}
		///#endregion wallPostReplyCancelButtonClickHandler

		///#region btnPostScrapClickHandler
		function btnPostScrapClickHandler() {
			var $txtPostScrap = $('#txtPostScrap');
			var postText = ($txtPostScrap.val() == postTextWaterMark) ? '' : $.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').hide();
			$('#divViewMoreWallPostLoadingBar').show();

			//		// 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: resources.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: resources.globalErrorWhileProcessingText, delay: 3000 });
					}
				});
			}
			///#endregion For Community level
		}
		///#endregion

		///#region UpdatePaging
		function UpdatePaging() {
			/// <summary>This method updated the visibility of next and previous links</summary>


			$('#divViewMoreWallPostLoadingBar').hide();
			// 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"> <img src="' + Communifire.virtualDirectory + 'assets/images/sharelink/load.gif" /></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:Resource 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

		});



		$('#txtPostScrap').autoGrow().Watermark(postTextWaterMark);
		$('#txtShareALinkURL').Watermark(shareALinkTextWaterMark);

		return this;

	};

	$.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')
	};
	;

})(jQuery);

///#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="' + resources.globalWallSeeMoreText + '" href="#">' + resources.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
};

