$(function() {
		   
	$.global.MyLibrary = new $.MyLibrary();
	$.global.AvatarSelector = new $.AvatarSelector();
	//$.global.AddToList = new $.AddToList();

	if($("#selectPenName").get(0) != null) {
		$.global.PenNameSelector = new $.PenNameSelector({
			onComplete: function() {
				$("#profile").removeClass('unpopulated');
				$("#unpopBanner").hide();
				$("#selectPenName").remove();
				$("#penname").html('<h4>Pen name:</h4><p class="penname">'+$.global.PenNameSelector.penname+'</p></h4>');
				$('input.profileNavRadio').unbind("click",showPrivacyError)
				$('[name=Privacy]').removeAttr("disabled");
				privacySettingChanged();
				$('input.profileNavRadio').click(privacySettingChanged);
				//window.location.reload(true);
			}
		});
	}

	if($("#holdingPenAlert").get(0) != null) {
		$.global.HoldingPen = new $.HoldingPen();
	}

	if($("#findProductsBooks").get(0) != null) {
		$.global.AddToFavoriteBK = new $.AddToFavorites({
			heading: "Add To My Favorite Books",
			id: 'AddToFavoriteBK',
			productTypes: ["Books",	"DigAudio",	"eBooks", "eNewspapers", "eMagazines"]
		});
		$("#findProductsBooks").click(function(e) {
			$.global.AddToFavoriteBK.add(e);
		});
	}

	if($("#findProductsFilm").get(0) != null) {
		$.global.AddToFavoriteDV = new $.AddToFavorites({
			heading: "Add To My Favorite DVDs",
			id: 'AddToFavoriteDV',
			productTypes: ["DVD"]
		});
		$("#findProductsFilm").click(function(e) {
			$.global.AddToFavoriteDV.add(e);
		});
	}

	if($("#findProductsMusic").get(0) != null) {
		$.global.AddToFavoriteMU = new $.AddToFavorites({
			heading: "Add To My Favorite Music",
			id: 'AddToFavoriteMU',
			productTypes: ["Music"]
		});
		$("#findProductsMusic").click(function(e) {
			$.global.AddToFavoriteMU.add(e);
		});
	}
	
	if ($("#communityNav").exists()) {
		newPrivacySetting = $('[name=Privacy]:checked').val();
		if (newPrivacySetting == 'private') {
			disableCommunityNavLink();
		}
	}

	if ($(".activityOptions").exists() || $("#activityFeedWidget a.paginate").exists()) {
		$.global.activityFeedDisplay = new $.ActivityFeedDisplay ();
	}
	
	$.global.checkIfFollowing = function () {
		ui.request({ 
			baseURL: $.hosts.commServices + '?',
			parameters:  "page=FavoriteBookmarks&uiAction=GetSortedBookmarks&type=0&orderBy=1&ce_purpose=checkIfFollowing&ce_targetPenName=" + $('#profilePenName').text(),
			callback: {name: "cbf", value: "$.global.checkIfFollowingCallBack"}
	
		});
	}
	
	if($("#pageType").html() == "profileVisitor") {
		
		$.global.checkIfFollowing();
	}
	
	$.global.checkIfFollowingCallBack = function (response) {
		if(response.status=='True') {
			if(String(response.output).indexOf("favoriteProfileFound") != -1) {
				$.global.followingProfileId = String(response.output).split("=")[1];
				$("#favoritesLink").hide();
				$("#removeFavoritesLink").show();
			}
		}
	}
	
		
		   
	$.PrivacyPopUpQuestion	= function () {
		
		// The following is the pre-defined content for PopUp Question:makeProfilePublic - Question Id 11111 in the community Annoucement mechanism:
		
		var self = this;
		var o = new $.Overlay();					
		self.questionId = "11111";
		self.triggerTarget = {};
		self.isReadyToDepart = false;
		self.addListners = {};
		
		var QuestionContent = $.global.popUpQuestionContent.Header_1
				+ "<div class='questionContent'>	\
						<div class='questionMessage' style='display:block;'/>		\
						<b>We noticed your profile is set to private. </b><br/>	\
						Would you like to make your profile public so it can be <br/>	\
						shared with others?	\
						<div class='questionOptions'>	\
							<form id='questionOptions-"+ self.questionId + "'>	\
								<input type='radio' name='popUpPrivacy' value='public'/> Make it Public	\
								<input type='radio' name='popUpPrivacy' value='private'/> Keep it Private	\
								<br/> \
								<br/>	\
								<img class='continue' src='"+$.hosts.resources+"/presources/community/images/btn_continue.gif'	\
								<br/>	\
								<br/>	\
								<div>	\
									<input align='center' type='checkbox' name='DoNotShowAgain' value='N' id='dismissIfChecked'/>	\
									 Don't show me this again	\
								<div>	\
							</form> \
						</div>	\
					</div>";
					
		this.shouldAskQuestion = function () {
		
			var shouldAsk  = Boolean((context.pageType == 'profileOwner' 
									  && $("#popUpQuestions #popUpQuestion-11111").exists() 
									  && context.profilePrivacyLevel == "Private" 
									  && $('#userPenName').exists() 
									  && $('#userPenName').text() != "")
								|| window.location.href.indexOf('testPrivacyQuestion=1') != -1);
			
			return shouldAsk;
			
		}
		
		this.open = function () {
			
			 o.set.id("ovrly-privacyPopUpQuestion");
			 o.set.content(QuestionContent);
			 o.set.width(430);
			 o.open();
			 
			 setDepartureAction (); // creates $.global.PrivacyPopUpQuestionCallBack();
			 
			 $('.questionContent .continue').click (function(e){
	
	
				e.preventDefault(e);
				
				if (! $("[name='popUpPrivacy']:checked").exists()) {
					
					showManualError ("Please select a Privacy setting to continue.", "choosePrivacy", ".questionContent .questionMessage");
				}
				else {
					setProfilePrivacySetting ();
				}
				
				
			 });
			 
			 
			o.element.find("a.overlayClose").click(function(e){
				 e.preventDefault(e);
				 o.close();
			});

			return;
		}

		function setDepartureAction () {
			
			// Remeber 'globally' where the user clicked and make a 'global' call back to be called by the service all response once the question process is complete 
			
			$.global.PrivacyPopUpQuestionTrigger = self.triggerTarget;
			
			$.global.PrivacyPopUpQuestionCallBack = function (response) {
				var currentTrigger = $.global.PrivacyPopUpQuestionTrigger;
				// The response is ignored because the user is attempting to leave the page either way and that should not be impeded.
				$.departPageNowDestination = currentTrigger;
				$.departPageNow();		
			}
		}

			 
		
		function setProfilePrivacySetting () {  // Copied and addpated from Community Nav
	
			var newPrivacy = "";
	
	
			$.CheckAndSetDoNotAskAgain ("#questionOptions-" + self.questionId, self.questionId);
			
			if ($("[name='popUpPrivacy']:checked").exists()){

				self.isReadyToDepart = true;
				
				newPrivacy = $("[name='popUpPrivacy']:checked").val();
			
				var myParameters = '?uiAction=UpdatePrivacySetting&status=' + newPrivacy + '&page=userprofile'
				

				
				ui.request({
						baseURL: communityHost + "ServiceRequest.aspx",
						parameters: myParameters,
						callback: {
							name: "cbf",
							value: "$.global.PrivacyPopUpQuestionCallBack"
						}
				
				});
			}
			
			
		}
		

		// END pre-defined content for PopUp Question:makeProfilePublic 
	
	}
	
	$.PenNamePopUpQuestion = function () {
		
		// The following is the pre-defined content for PopUp question:makePenName - Question Id 33333 in the community Annoucement mechanism:		
			
		var self = this;
		var o = new $.Overlay();					
		self.questionId = "33333";
		self.triggerTarget = {};
		self.isReadyToDepart = false;
		self.addListners = {};		
		

		var QuestionContent = $.global.popUpQuestionContent.Header_1
				+ "<div class='questionContent'>	\
						<div class='questionMessage' style='display:block;'/>		\
						<strong>We noticed your profile is set to private. </strong><br/>	\
						Would you like to create a pen name so you can set it to public now?	\
						<div class='questionOptions'>	\
							<form id='questionOptions-" + self.questionId + "'>	\
								<button class='yesOption'><img src='" + $.hosts.resources + "/presources/community/images/btn_yes_white.gif'/></button>	\
								<button class='noOption'><img src='" + $.hosts.resources + "/presources/community/images/btn_nothanks.gif'/></button>	\
								<div>	\
									<br/>	\
									Your unique pen name is your identity on Barnes &amp; Noble.com. It also allows you to share your profile with friends and family. 	<br/>\
									<br/>	\
								</div>	\
								<div>	\
									<input align='center' type='checkbox' name='DoNotShowAgain' value='N' id='dismissIfChecked'/>	\
									 Don't show me this again	\
								<div>	\
							</form> \
						</div>	\
					</div>";
					
		this.shouldAskQuestion = function () {
			
			var shouldAsk  = Boolean((context.pageType == 'profileOwner' 
									  	&& $("#popUpQuestions #popUpQuestion-33333").exists() 
										&& (!$('#userPenName').exists() || $('#userPenName').text() == ""))
									|| window.location.href.indexOf('testPenNameQuestion=1') != -1);
			
			return shouldAsk;				
		}
	
		this.open = function () {
			
			 o.set.id("ovrly-penNamePopUpQuestion");
			 o.set.content(QuestionContent);
			 o.set.width(430);
			 o.open();
			 
			 setDepartureAction (); // creates $.global.PrivacyPopUpQuestionCallBack();
			 
			 $('.questionContent .yesOption').click (function(e){
															  
				e.preventDefault(e);
				
				
				$.global.PenNameSelector.onCompleteOverrideFlag = true;

				$.global.PenNameSelector.onCompleteOverrideAction = function () { 
				
					$.CheckAndSetDoNotAskAgain ("#questionOptions-" + self.questionId, self.questionId);
				
					// Then make the profile public:
					var myParameters = '?uiAction=UpdatePrivacySetting&status=Public&page=userprofile'
				
						ui.request({
								baseURL: communityHost + "ServiceRequest.aspx",
								parameters: myParameters,
								callback: {
									name: "cbf",
									value: "$.global.PenNamePopUpQuestionCallBack"
								}
						
						});
			
				}
				
				$.global.PenNameSelector.onCompleteOverrideToProfile = function () {

					// If, at the end of selecting a penname, the user does chooses to 'go to their profile', this action is executed: it means that the user has successfully done one popup, and they can leave now.
					$.global.isReadyToDepart = true;
					
					$.CheckAndSetDoNotAskAgain ("#questionOptions-" + self.questionId, self.questionId);
				
					// Then make the profile public:
					var myParameters = '?uiAction=UpdatePrivacySetting&status=Public&page=userprofile'
				
					ui.request({
							baseURL: communityHost + "ServiceRequest.aspx",
							parameters: myParameters,
							callback: {
								name: "cbf",
								value: "$.global.PenNameQuestionToProfileCallBack"
							}
					
					});
					
				}
				
				$.global.PenNameSelector.open();
			
				$("#ovrly-penNamePopUpQuestion").hide();
					
			 });
			 
			 $('.questionContent .noOption').click (function(e){
															  
				e.preventDefault(e);
				
				$.CheckAndSetDoNotAskAgain ("#questionOptions-" + self.questionId, self.questionId);
				
				$.global.PenNamePopUpQuestionCallBack();
				
			 });
			 
			 
			o.element.find("a.overlayClose").click(function(e){
				 e.preventDefault(e);
				 o.close();
			});

			return;
		}
		
		
		function setDepartureAction () {
			
			// Remeber 'globally' where the user clicked and make a 'global' call back to be called by the service all response once the question process is complete 
			
			$.global.PenNamePopUpQuestionTrigger = self.triggerTarget;
			
			$.global.PenNamePopUpQuestionCallBack = function (response) {
			

				var currentTrigger = $.global.PenNamePopUpQuestionTrigger;
				
				//alert("test, setting action: " + currentTrigger); // vvvvv
				
				// The response is ignored because the user is attempting to leave the page either way and that should not be impeded.
				$.departPageNowDestination = currentTrigger;
				$.departPageNow();				
				// The response is ignored because the user is attempting to leave the page either way and that should not be impeded.
			}
			
			$.global.PenNameQuestionToProfileCallBack = function (response) {
				// This is intended to be used when the PenName selector is complete and the user has selected to 'go to the profile page' (ie: close the selector).
				//  But standard jQuery cannot update the privacy radio buttons with out a pluggin, which there is not time to test.  
				//	So the page is refreshed to accurately reflect the profile's privacy settings.
				
				window.location.reload(true);
			}
			
		}
	
	
		
		// END pre-defined content for PopUp Question:makeProfilePublic 
		
	}

	// Setup the Questions objects:
	$.global.privacyPopUpQuestion = new $.PrivacyPopUpQuestion();	
	$.global.penNamePopUpQuestion = new $.PenNamePopUpQuestion();

	if ($.global.penNamePopUpQuestion.shouldAskQuestion()){ 
		
		//XXXXXX	alert('right kind of PenName profile');		

		$.preventDepatureOnAllRealLinks ($.global.penNamePopUpQuestion);
				
	}	
	else if ($.global.privacyPopUpQuestion.shouldAskQuestion()) { 
		
		//XXXXX alert('right kind of profile');

		$.preventDepatureOnAllRealLinks ($.global.privacyPopUpQuestion);
	
	}	
		   
	if($("#announcements").get(0) != null) {
        var announcements = $("#announcements").text().split("|");
        var url = "http://www.barnesandnoble.com/help/help_cds2.asp";
        var url2 = 'https://secure.barnesandnoble.com/help/content.asp';

        for (i = announcements.length-1; i >= 0; i--) {
               var pid = announcements[i];
               ui.request({
					baseURL: url2, //+ "?pid=" + pid,
					parameters: "?pid=" + pid + "&outformat=1",
					overrideCallback: true,
					getScript: true,
					callback: { name: "callbackfunc", value: "AnnouncementCallback" }
				});

        }
    }

	
	if($('#suggestions4u').exists()){
		$.global.suggestions = new $.Suggestions({
			container: $('#suggestions4u'),
			footer: $('div.suggestionsFooter'),
			thumbnails: $('#suggestions4u div.thumbnails'),
			tabLinkClass: 'suggestionsTab',
			tabClass: 'tab',
			currentClass: 'current',
			stripClass: 'strip',
			arrowClass: 'arrow',
			paginationClass: 'paginate',
			speed: 1000,
			animationOptions: { easing: 'easeOutCubic' }
		});
	}
	
});

function privacyPopUpSettingCallBack () {
		// do nothing	
	}


function AnnouncementCallback(result){
	var o = new $.Overlay();
	if (String(result.html).indexOf('overlayClose') <= -1){
		// Provide the markup to all the user to close an Annoucement in case it is an error message from CDS (which does not have a close button)
		result.html = '<div style="height:30px" align="right"><a class="overlayClose" style="display:block;margin:3px;width:30px;cursor:pointer;"></a></div>'
					+ result.html;
	}
	o.set.content(result.html);
	//o.set.content( $("#testCDSOverlayContent").html() )
	o.open();

	// Test against string if there is a CDS page to dismiss popup automatically
	// if (result.html == "") {
	// o.close();
	// }

	o.element.find("a.overlayClose").click(function(e){
		e.preventDefault(e);
		markAnnouncementAsViewed();
		 o.close();
	});

	o.element.find("input.dissmissAnnouncement").click(function(){
		markAnnouncementAsViewed();
		o.close();
	});

	function markAnnouncementAsViewed() {
		var announcementID = $("#announcementIDs").text().split("|");
		var checkedStatus = new Boolean($("input[name='showmsg']").attr("checked"))
		var strCheckedStatus = checkedStatus.toString();

		if(strCheckedStatus == "true") {
			for (i = announcementID.length - 1; i >= 0; i--) {
				ui.request({
					baseURL: $.hosts.commServices,
					parameters: "?page=UserProfile&uiAction=MarkAnnouncementAsViewed&announcementID=" + announcementID,
					callback: {
						name: "cbf",
						value: "$.markAnnouncementViewedCB"
					}
				});
			}
		} else {
			//nothing for now
		}

	}


}


$.AddToFavorites = function(options) {
	var self = this;
	var sw = null;
	
	var settings = $.extend({
		heading: "Add To My Favorite Music",
		id: 'AddToFavoriteMU',
		productTypes: ["Music"],
		maxNum: 5
	}, options);

	function init() {
		self.searchWidget = new $.SearchWidget({
			heading: settings.heading,
			id: settings.id,
			productTypes: settings.productTypes,
			add: function(e) {
				e.preventDefault(e);

				var values = $(e.target).get(0).id.split("_");
				var pt = values[0];
				var ean = values[1];
				
				if (pt == 'ER') { pt = 'BK'}; // reassign eBook product code for Comm serv

				ui.request({
					baseURL: $.hosts.commServices,
					parameters: "?uiAction=AddItemToListFavoriteProductsFromProfile&ean="+ean+"&page=FavoriteProducts&pageType=fav" + pt, 
					callback: {name: "cbf", value: "jQuery.global.AddToFavorite"+pt+".Favorite"+pt+"Callback"}
				});

			},
			refresh: function(e) {
				if(e) { e.preventDefault(e); }

			},
			cbf: "jQuery.global."+settings.id+".searchWidget.displayResults"
		});
		sw = self.searchWidget;
	}

	function adjustProducts(container, response) {
		var $bucket = $(container);
		var numLinks = $bucket.get(0).getElementsByTagName("a").length;
		if(numLinks == 4) {
			$bucket.find("li:last").remove();
		}
		$bucket.prepend('<li>'+ response.output +'</li>');
	}
	function updateFavoriteCount(type){ 
	    // udpate count dynamically on first additions.
		if(type){
			var maxCount = 4, favoriteCount = 0;
			if(typeof $.global.FavoriteTotal === "undefined"){
				$.global.FavoriteTotal = {};
			}
			if(typeof $.global.FavoriteTotal[type] === "undefined"){
				$.global.FavoriteTotal[type] = 1;
			}else{
				$.global.FavoriteTotal[type] = ($.global.FavoriteTotal[type] + 1);
			}
			var favoriteType = parseInt($.global.FavoriteTotal[type]);
			
			if(favoriteType <= maxCount){
				favoriteCount = favoriteType;
			}else{
				favoriteCount = maxCount;
			}
			$('#favorites'+type+'Count').removeClass("Empty");
			$('#favorites'+type+'Count').text('('+favoriteCount+ ' of ' +favoriteType+')');
		}
	} 
	this.FavoriteBKCallback = function(response) {
		if(isPopUpError (response, "AddFavBk", "Error Adding Book")) {
			return false;
		}		
		$("div.productsBooks.Empty ul").addClass("favItemsList")
		$("div.productsBooks.Empty ul").html("")
		$("div.productsBooks.Empty").removeClass("Empty");

		adjustProducts("div.productsBooks ul", response);

		$("#addTitleHeaderFB").show();
		$("#editButtonFB").show();
		$("#seeAllFB").show();
		updateFavoriteCount("FB");
	}

	this.FavoriteDVCallback = function(response) {
		if(isPopUpError (response, "AddFavDv", "Error Adding DVD")) {
			return false;
		}
		$("div.productsFilm.Empty ul").addClass("favItemsList")
		$("div.productsFilm.Empty ul").html("")
		$("div.productsFilm.Empty").removeClass("Empty")
		
		adjustProducts("div.productsFilm ul", response);
		
		$("#addTitleHeaderFD").show();
		$("#editButtonFD").show();
		$("#seeAllFD").show();
		updateFavoriteCount("FD");
	}

	this.FavoriteMUCallback = function(response) {
		if(isPopUpError (response, "AddFavMu", "Error Adding CD")) {
			return false;
		}
		$("div.productsMusic.Empty ul").addClass("favItemsList")
		$("div.productsMusic.Empty ul").html("")
		$("div.productsMusic.Empty").removeClass("Empty")
		
		adjustProducts("div.productsMusic ul", response);
		
		$("#addTitleHeaderFC").show();
		$("#seeAllFC").show();
		$("#editButtonFC").show();
		updateFavoriteCount("FC");
	}

	this.add = function(e) {
		if(e) { e.preventDefault(e); }
		self.searchWidget.addItems(null);
	}

	init();
}

$.AvatarSelector = function(options) {
	var self = this;
	var overlay = null;
	var overlayLayout = '<div id="avatarContent"></div>';
	var avatarID = null;
	var btn_useThisAvatar = null;

	$("#editAvatar").click(function() {
		//show();
		ui.request({
			baseURL: $.hosts.commServices,
			parameters: "?page=userprofile&uiAction=GetAvatarGallery&bnOutput=1&categoryId=0",
			callback: {name: "cbf", value: "jQuery.global.AvatarSelector.show"}
		});
	});
	
	$("#editAvatarImg").click(function() {
		//show();
		ui.request({
			baseURL: $.hosts.commServices,
			parameters: "?page=userprofile&uiAction=GetAvatarGallery&bnOutput=1&categoryId=0",
			callback: {name: "cbf", value: "jQuery.global.AvatarSelector.show"}
		});
	});

	function init() {
		overlay = new $.Overlay({
			useHeading: 1,
			heading: "Add an Avatar"
		});
		overlay.set.content(overlayLayout);
		overlay.set.id("avatarSelector")
		overlay.set.width(730);

		$("#avatarSelector").delegate("click", {
			"a.overlayClose": close,
			"a.tab": changeTab
		});

	}

	function changeTab(e) {
		e.preventDefault(e);
		var tab = $(e.target);
		$("li.on a.tab").parents("li").removeClass("on");
		tab.parents("li").addClass("on");
		var content = document.getElementById(tab.get(0).id + "-content");

		$("#ovrly_AvatarSelector div.avatars").css({display: "none"});

		
		content.style.display = "block";
	}
		


	function setAvatar() {
		ui.request({
			baseURL: $.hosts.commServices,
			parameters: "?page=userprofile&uiAction=UpdateAvatar&bnOutput=1&avatar=" + $("#currentAvatar").get(0).name.replace("cur-", ""),
			callback: {name: "cbf", value: "jQuery.global.AvatarSelector.setCallback"}
		});
	}

	this.setCallback = function(response) {
		if(response.status == "True") {
			$("#prof-avatar img").get(0).src = $("#currentAvatar").get(0).src;
			if ($("#currentAvatar").get(0).name.replace("cur-", "") == '101') {
				$("#noAvatarCTA").show();
				$("#afterAvatarCTA").hide();
			}
			else {
				$("#noAvatarCTA").hide();
				$("#afterAvatarCTA").show();
			}
			close();
			
		}
	}

	function close(e) {
		if(e) { e.preventDefault(e); }
		$("#avatarContent").html("");
		overlay.close();
	}

	this.show = function(response) {
		$("#avatarContent").html(response.output);
		overlay.open();

	
		$("button.useThisAvatar").hide();
		
		if(jQuery.browser.msie) {
			// $("#avatarContent").pngFix();  // The pngFix was found to be incompatable with the manageDragables functionality. Instead design has been asked for PNG-8's for the new avatars.  3-2-09
		}
		
		
		manageDraggables();
		
		$("#avatarSelector button.cancel").click(function(e) {
			close(e);
		});
		$("#avatarSelector button.useThisAvatar").click(function(e) {
			setAvatar(e);
		});
	

	}

	function manageDraggables() {
		$("img.drag").click(function(e) {
			avatarID = $(e.target).get(0).id;
			var curAvatar = $("#currentAvatar").get(0);
			curAvatar.src = $(e.target).get(0).src.replace("_M", "_L");
			curAvatar.name = avatarID;
			$("button.useThisAvatar").show();
		});

		$("img.drag").draggable({
			helper: 'clone',
			appendTo: $("#avatarSelector"),
			start: function() {
				var helper = arguments[1].helper;
				helper.css({opacity : ".5", filter : "alpha(opacity = 50)"});
				helper.get(0).src = helper.get(0).src.replace("_M", "_L");
				avatarID = helper.get(0).id;
			},
			stop: function() {
				avatarID = null;
			}
		});

		$("#avatarSelection").droppable({
			accept: ".drag",
			drop: function(e, ui) {
				var curAvatar = $("#currentAvatar").get(0);
				curAvatar.src = $(e.target).get(0).src;
				curAvatar.name = "cur-" + avatarID;
				//$("#prof-avatar img").get(0).src = curAvatar.src;
				$("button.useThisAvatar").show();
			}
		});

	}

	init();
}

$.MyLibrary = function() {
	var self = this;
	this.searchWidget = null;
	var productDetails = null;
	var overlayFlag = 0;
	var currentItem = null;
	var owner = 1;
	
	if($("#pageType").html() == "profileVisitor") {
		owner = 0;
	}
	
	function init() {
		self.searchWidget = new $.SearchWidget({
			heading: "Add to My Library",

			productTypes: ["Books",	"DigAudio",	"eBooks", "eNewspapers", "eMagazines", "DVD", "Music"],
			add: function(e) {
				e.preventDefault(e);
				var values = $(e.target).attr('id').split("_");
				var pt = values[0];
				var ean = values[1];
				ui.request({
					baseURL: $.hosts.commServices,
					parameters: "?page=Library&uiAction=AddLibraryItem&bnOutput=1&maxNum=7&ean="+ ean +"&pt=" + pt,
					errorMsgHolder: $('#searchWidget-resultArea'),
					callback: {name: "cbf", value: "$.global.MyLibrary.add"}
				});
			},
			refresh: function() {
				refresh();
			},
			cbf: "jQuery.global.MyLibrary.searchWidget.displayResults"
		});

		productDetails = new $.Overlay({block: 0, container: $("#forceWidth")});
		productDetails.set.id("productDetailOverlay");

		$("#productDetailOverlay").bind("mouseleave", function(e) {
			hideProductOverlay(e);
		});

		if(jQuery.browser.msie) {
			$("#myLib-addMoreItems").css({position: "relative", top: 5}).pngFix()
			$(".myLibraryTitleContainer").pngFix()
			$("#myLib-seeAll").css({position: "relative", top: 5}).pngFix()
			$("#ovrly-holdingPenContent").pngFix();
			$("#myLib img.readingNow").wrap("<span style='position: absolute; margin: -10px 0 0 -10px;'></span>").parent().pngFix();
		}
		
		//refresh on Load because pageload for Reading Now flags to match entire Reading Now list and not just whats on pageload for profile
		//better solution would be adapt service to accept parameter to identify owner or visitor
		
		if ($("#pageType").text() == 'profileOwner') {
			refresh();
		}
		
	}

	this.render = function(response) {
		$("#myLib div.products").html(response.output);
		$("#mylib-countView").html($("#mylib-count").html());
		
		//Re-starts Ratings stars on page; duplicated from ui.js - 9-18-08
		var ratingWidgets = $("span.rating-widget").not("span.ignore");
		
		for(var i=0; i<ratingWidgets.length; i++) {
			var spanParent = ratingWidgets[i];
			if(spanParent.getElementsByTagName("img").length == 0) {
				spanParent.className += " noNA";
			}
			spanParent.innerHTML = "<a href='#' class='section_rateTitle rating-0'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-1'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-2'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-3'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-4'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-5'>&nbsp;&nbsp;&nbsp;&nbsp;</a>" + spanParent.innerHTML;
			if ($.browser.msie) {
				$('a.ratingVal').css('top', 'auto');
			}
		}
			
		if(jQuery.browser.msie){
			$("#myLib-addMoreItemsToEmpty").pngFix();
			$("#myLib-addMoreItemsToEmpty span.lib-find-empty").css({width:"111px",height:"113px"});
		}
		
		$("#myLib-addMoreItemsToEmpty").click(function(e) {
			e.preventDefault(e);
			self.searchWidget.addItems(e);
		});
		
	}

	$("#myLib").delegate("mouseover", {
		"img.lib-product": showDetails
	});

	// TODO: div.overlay is too general, eventually must make this specific to this instance
	$('#forcewidth').delegate("mouseout", {
		"img.lib-product": flagOff
	});

	$(document).delegate("click", {
		"a.deleteFromLib": deleteItem,
		"input.addToReadingNow": toggleReadingNow,
		"a.newEssentialist": newEssentiaList,
		"a.addItemToLibrary": addItemToLibrary,
		'img.lib-product': showDetails,
		'a.viewPastPurchases' : getAndOpenPastPurchases,
		'a.addFavorites': function(e){
			var classes = $(e.target).attr('class').split(' ');
			var ean = null;
			var pt = null; // This is actually the value of the product code, not product type, which is used for searches
			
			$.each(classes, function(k, className){
				if (className.indexOf('ean') != -1) ean = className.split('_')[1];
				if (className.indexOf('pt') != -1) pt = className.split('_')[1];
			});
			
			if (pt != 'MU' && pt != 'DV') {pt = 'BK'} //reassign non-Music and non-Video product code to be BK (so to always added un-recognized items to favorite books (like the Nook, etc)

			ui.request({
				baseURL: $.hosts.commServices,
				parameters: '?page=FavoriteProducts&uiAction=AddItemToListFavoriteProducts&bIsTemp=false&ean=' + ean + '&pageType=fav' + pt,
				callback: {name: 'cbf', value: '$.global.MyLibrary.addFavorites'}
			});

			$.global.MyLibrary.addFavorites = function(response){
				
				
				
				if ($('#userPenName').text() == "" || $('#bnRewriteURL').text() == "N") {
				
					var favLink = ''				
					switch (pt) {
						case 'BK':
							pt = 'favBK';
							break;
						case 'ER':
							pt = 'favBK';
							break;
						case 'DV':
							pt = 'favDV';
							break;
						case 'MU':
							pt = 'favMU';
							break;
					}

					favLink = 'http://my.barnesandnoble.com/communityportal/favoriteproducts.aspx?pageType=' + pt
					
				}
				else {
					switch (pt) {
						case 'BK':
							pt = 'books';
							break;
						case 'ER':
							pt = 'books';
							break;
						case 'DV':  
							pt = 'dvds';
							break;
						case 'MU':
							pt = 'music';
							break;
					}	
					
					favLink = 'http://my.barnesandnoble.com/favorite-' + pt + '-' + $('#userPenName').text()
				}

				$('div.mylib-' + ean).find('a.favoritesLink')
					.text('Go to My Favorites')
					.attr('href', favLink)
					.removeClass('addFavorites');
			}

			return false;
		}
	});
	
	function getAndOpenPastPurchases (e) {

		e.preventDefault(e);
		
		if (! $.global.HoldingPen) {
			$.global.HoldingPen	= new $.HoldingPen();
		}
		
		$.global.HoldingPen.openPastPurchases ();
		
	}
	
	function addItemToLibrary(e) {
		
		e.preventDefault(e);
		
		var classes = $(e.target).attr('id').split('_');
		var pt = classes[0];
		var ean = classes[1];
		
				ui.request({
					baseURL: $.hosts.commServices,
					parameters: "?page=Library&uiAction=AddLibraryItem&bnOutput=1&maxNum=7&ean="+ ean +"&pt=" + pt,
					callback: {name: "cbf", value: "$.global.MyLibrary.addItemFromVisitorProfile"}
				});
			
		$('div.mylib-' + ean).find('a.addItemToLibrary').text('Go to Your Library').attr('href', 'http://my.barnesandnoble.com/communityportal/Library.aspx?penName=' + $('#userPenName').text()).removeClass('addItemToLibrary');
			
	}

   function newEssentiaList(e) {
        //this function will fire the newEssentiaList function in $.AddToList in ui.js. If we remove this function it won't = odd behavior
		e.preventDefault(e);

		$.global.AddToListCreateListPrompt = '<div style="padding: 20px;"><form id="createEssentialistForm"><span class="CreateListPrompt_ErrorHolder" style="display:none;"><span style="color:#DD0000; font-weight:bold">Please name your EssentiaList*: (This is a required field)</span></span><span class="CreateListPrompt_LabelHolder">Please name your EssentiaList:</span><span style="font-size:10px;" class="CreateListPromptTitle"></span><br/><input type="text" class="new_list_inputTitle" name="title" maxlength="100" value="" style="width: 360px; height: 30px; color:#666;font-size:16px; margin-top:4px;" /><br/><br/><span>You may add a description of the list:</span><br /><textarea class="new_list_Description" name="desc" style="width: 360px; height: 60px;color:#666; font-family: verdana, arial; font-size:12px;margin-top:4px;"></textarea><br/><br/><button class="create_listlink_okay"><img src="http://images.barnesandnoble.com/presources/community/images/btn_submit.gif" /></button><button class="create_listlink_cancel"><img src="http://images.barnesandnoble.com/presources/community/images/btn_cancel.gif" /></button></form></div>';

		$.global.CreateListPrompt = new $.Confirm({
		    heading: "Create a new EssentiaList",
		    id: "myCreateListPrompt",
		    content: $.global.AddToListCreateListPrompt,
		    cancel: {path: "button.create_listlink_cancel", action: function() {
				$("input.new_list_inputTitle").val("");
			    $("textarea.new_list_Description").val("");
				$("#createEssentialistForm div.errorMsg").remove();
				$.global.CreateListPrompt.remove();
			   return true;
		    }},
		    ok: {path: "button.create_listlink_okay", action: function() {
				ui.request({
					baseURL: $.hosts.commServices,
					parameters: "?uiAction=CreateListForLinkOnly&page=List&pageType=listCreate&ce_type=library&ean=" + $.global.CreateListPrompt.ean + "&productCode="+$.global.CreateListPrompt.productCode +"&privacy=1&" + $("#createEssentialistForm").find(":input").serialize(),
					callback: {name: 'cbf', value: '$.global.CreateListPrompt.redirect'}
				});

				$.global.CreateListPrompt.remove();
				return false;
		    }}
		});

		$.global.CreateListPrompt.redirect = function(response){
			window.location = response.output;
		}

		var values = $(e.target).attr('id').split("_");
		$.global.CreateListPrompt.ean = values[0];
		$.global.CreateListPrompt.productCode = values[1];

		$('#myCreateListPrompt').find('textarea').maxLength(250);

		$.global.CreateListPrompt.prompt();
    }

	function flagOff() {
		overlayFlag = 0;
	}

	// temp
	this.reload = function() {
		refresh();
	}

	function refresh() {
		ui.request({
			baseURL: $.hosts.commServices,
			parameters: "?page=Library&uiAction=GetLibrary&bnOutput=1&sort=10&maxNum=7",
			callback: {name: "cbf", value: "jQuery.global.MyLibrary.render"}
		});
	}

	function deleteItem(e) {
		e.preventDefault(e);
		var itemID = $(e.target).attr('id');

		ui.request({
			baseURL: $.hosts.commServices,
			parameters: "?page=Library&uiAction=RemoveLibraryItem&bnOutput=1&itemID=" + itemID,
			callback: {name: "cbf", value: "jQuery.global.MyLibrary.deleted" }
		});
	}

	this.deleted = function() {
		productDetails.close();
		refresh();
	}

	function showDetails(e) {
		var type = e.originalEvent.type;
		currentItem = $(e.target);
		overlayFlag = 1;
		
		var EAN = $(e.target).get(0).id.split("_")[1];

		if(type == 'click'){
			popup();
		}
		else {
			setTimeout(function() {
				popup();
			}, 700);
		}

		function popup(){
			if(overlayFlag) {
				if (currentItem.data('requested') != true && owner) {
					currentItem.data('requested', true);
					ui.request({
						baseURL: $.hosts.commServices,
						parameters: "?page=Library&uiAction=GetItemDetail&bnOutput=1&ean=" + EAN,
						callback: {
							name: "cbf",
							value: "$.global.MyLibrary.overlayResponse"
						}
					});
				}

				productDetails.set.top($(e.target).offset().top - $(e.target).get(0).offsetTop)

				var hiddenOverlay = $(e.target).parents("td").find("div.mylib-overlay");
				self.showProductOverlay({
					output: hiddenOverlay.html()
				})
				//hiddenOverlay.html("");

				if($(window).width() < $(e.target).offset().left + 375) {
					productDetails.set.left($(window).width() - 375);
				} else {
					productDetails.set.left($(e.target).offset().left);
				}
				
				addDepartureListners (EAN);
			}
		}
	}

	function addDepartureListners (EAN) {

		var thisItem = $('div.mylib-' + EAN);
		var newLinks = "";

		if ($.global.penNamePopUpQuestion.shouldAskQuestion() ) {
			newLinks = ($(thisItem).find("a[href!='']").not("a[href='#'], a[href^='#'], a[href^='javascript:']"));
			//alert ('Bounding PanName Links Dynamically');					
			$.addPreventDepartureListners($(newLinks), $.global.penNamePopUpQuestion);
		}	
		else if ($.global.privacyPopUpQuestion.shouldAskQuestion()) { 
			newLinks = ($(thisItem).find("a[href!='']").not("a[href='#'], a[href^='#'], a[href^='javascript:']"));					
			$.addPreventDepartureListners($(newLinks), $.global.privacyPopUpQuestion);
		}	
	}
	

	this.overlayResponse = function(response) {
		//console.log(response.output)
		if ($('#pageType').text() == 'profileOwner') {
			if (response.status == "True") {
				var ean = response.output.ean;
				var pt = $('div.mylib-' + ean).find('a.newEssentialist').attr('id').split('_')[1];

				if (response.output.hasReview == 'True') {
					$('div.mylib-' + ean).find('a.reviewLink').text('Read My Review').attr('href', 'http://my.barnesandnoble.com/communityportal/Review.aspx?page=Review&reviewid=' + response.output.reviewId);
				}

				if (response.output.isInEbookLB == 'True' ) {
					$('div.mylib-' + ean).find('a.eBookProductPageLink').replaceWith($('<a href="http://my.barnesandnoble.com/ebooks/ebookslibrary.html">go to My eBooks Library</a>'));
				}
				
				if (response.output.isFavorite == 'True') {
					switch (pt) {
						case 'BK':
							pt = 'books';
							break;
						case 'ER':
							pt = 'books';
							break;
						case 'DV':
							pt = 'dvds';
							break;
						case 'MU':
							pt = 'music';
							break;
					}

					$('div.mylib-' + ean).find('a.favoritesLink').text('Go to My Favorites').attr('href', 'http://my.barnesandnoble.com/favorite-' + pt + '-' + $('#userPenName').text()).removeClass('addFavorites');
					
				}
				
			}
			
		
		}
	}

	function hideProductOverlay(e) {
		overlayFlag = 0;
		//currentItem.html($(e.target).html());
		//currentItem.parents("td").find("div.mylib-overlay").html($("#productDetailOverlay").html());
		productDetails.close();
		productDetails.set.left(-10000);
	}

	this.showProductOverlay = function(response) {
		productDetails.close();
		productDetails.set.content("")
		productDetails.set.content(response.output)
		productDetails.open(false);
	}

	this.add = function(response, errorMsgHolder){

		if( isLocalizedErrorFound (response, "", "AddLibraryFail", $(errorMsgHolder))) {
			return;
		}

		ui.log("Response", response);
		$("div.noPenAlert").hide();

		var holdingPenCount = $("#holdingPenCount").text();
		var libraryItemCount = $('div.products').children('table').children('tbody').children('tr.populated').children('td').length

		//alert(libraryItemCount)

		if (holdingPenCount!='0' && libraryItemCount=='0') {
			$("#holdingPenAlert").addClass("newAlert")
			$("#defaultHoldingPen").hide();
			$("#recentPurchase").show();

		}
	}
	
	this.addItemFromVisitorProfile = function(response){
		
		if (response.status == "True") {
		
	//		
		}
		else {
			if (isLocalizedErrorFound(response, "", "AddLibraryFail", $('#holdingPenContainer'))) {
				return;
			}
		}
	}


	$("#myLib-addMoreItems").click(function(e) {
		e.preventDefault(e);
		self.searchWidget.addItems(e);
	});

	if($("#myLib-addMoreItemsToEmpty").get(0) != null) {
		$("#myLib-addMoreItemsToEmpty").click(function(e) {
			e.preventDefault(e);
			self.searchWidget.addItems(e);
		});
	}

	$("#myLib-addMoreItemsToEmpty").click(function(e) {
		e.preventDefault(e);
		self.searchWidget.addItems(e);
	});

	/*
	$("#myLib-seeAll").click(function(e) {
		e.preventDefault(e);
		//self.searchWidget.seeAll(e);
	});
	*/

	function toggleReadingNow(e) {
		var $target = $(e.target);
	    var ean = $target.attr('id').split("-")[0];

	    if($target.is(':checked')) {
			$target.parents('.group').find('a.reviewLink').css('fontWeight', 'normal');
		    ui.request({
				baseURL: $.hosts.commServices,
				parameters:  "?page=FavoriteProducts&uiAction=AddItemToListFavoriteProductsFromProductPage&pageType=favRN&bnOutput=1&ean=" + ean,
				errorMsgHolder: $('#holdingPenContainer'),
				callback: {name: "cbf", value: "jQuery.global.MyLibrary.refreshReadingNow" }
			});
			$("img[id='" + ean + "'].readingNow").show();
			$("input[id='"+$target.attr('id')+"']").each(function(index, item) {
				if(item.checked == "") {
					$(item).replaceWith("<input type='checkbox' id='"+$target.attr('id')+"' class='addToReadingNow' checked='checked' />");
				}
			});
		} else {
			//var ListItemId = $target.get(0).id.split("-")[1];
			$target.parents('.group').find('a.reviewLink').css('fontWeight', 'bold');
			ui.request({
				baseURL: $.hosts.commServices,
				parameters:  "?page=FavoriteProducts&uiAction=RemoveFavoriteProductsItemByEan&bIsTemp=false&pageType=favRN&ean=" + ean,
				callback: {name: "cbf", value: "jQuery.global.MyLibrary.refreshReadingNow" }
			});
			$("img[id='" + ean + "'].readingNow").hide();
			$("input[id='"+$target.attr('id')+"']").each(function(index, item) {
				if(item.checked === true) {
					$(item).replaceWith("<input type='checkbox' id='"+$target.attr('id')+"' class='addToReadingNow' />");
				}
			});
		}
	}

	this.refreshReadingNow = function (response, errorMsgHolder) {

		if( isLocalizedErrorFound (response, "That Reading Now item could not be added: ", "ReadingNowAddFail", $(errorMsgHolder))) {
			return;
		   }

			ui.request({
				baseURL: $.hosts.commServices,
				parameters: "?page=FavoriteProducts&uiAction=RefreshReadingNowListProfilePage&pageType=favRN&pageSize=3",
				callback: {name: "cbf", value: "jQuery.global.MyLibrary.populateReadingNow" }
			});
	}

	this.populateReadingNow = function(response){

		$('#holdingPenContainer').html('');

		if (response.status = "True") {

			$("#readingNowListContainer").html('')
			$("#readingNowListContainer").append(response.output)
		}
	}

	init();
}

function addToRNList() {
	return false;
}

$.HoldingPen = function(options) {
	var self = this;
	var overlay = null;

	var pastPurchasesInfo = {};
	pastPurchasesInfo.currentPage = {};
	pastPurchasesInfo.currentPageIndex = 0;
	pastPurchasesInfo.pageSize = 0;
	pastPurchasesInfo.totalItemCount = 0;	
	pastPurchasesInfo.PageSizeToRequest = 50;
	pastPurchasesInfo.isActive = false;
	pastPurchasesInfo.isPopulated = false; // set to true is at least one page has been downloaded.
	
	this.settings = $.extend({}, options);

	function init() {
		overlay = new $.Overlay();
		overlay.set.id("ovrly-holdingPen");

		$("#holdingPenContainer").delegate("click", {
			"a.holdingPen": getHoldingPen
		});

		$("#ovrly-holdingPen").delegate("click", {
			"a.checkAll": checkAll,
			"a.uncheckAll": uncheckAll,
			"a.holdingPenClose": close,
			"button.btn_cancel": close,
			"button.btn_add": addItems
		});
		
		
//			$("input.holdingPenItemType").click(toggleView);
	}

	this.openPastPurchases = function () {
		getPastPurchasesPage ({'isFirstCallForPastPurchases' : true});			
	}


	function toggleView () {

		var actionToTake = String($("input.holdingPenItemType:checked").val());

		// alert('Got it: ' + actionToTake); 
		
		if (actionToTake == 'PastPurchases') {
			goToOtherPastPurchasesPage (0);	
		}
		else if (actionToTake == 'RecentPurchases') {
			goToRecentPurchases ();
		}
	}
	
	function goToRecentPurchases () {

		
		if($('#ovrly-holdingPen .recentPurchases table').exists()) {
			
			hideAnyPastPurchasesPages ();
			
			// then assume that Recent purchases have already been downloaded and thus show them:
			$('#ovrly-holdingPen .recentPurchases').show();	
		}
		else {
			getRecentPurchases();
		}
	}


	function getRecentPurchases() {

		ui.request({
			baseURL: $.hosts.commServices,
			parameters: "?page=library&uiAction=GetHoldingPenList&ce_HoldingPenAlreadyExists=1&bnOutput=1",
			callback: {name: "cbf", value: "jQuery.global.HoldingPen.getRecentPurchasesCallback"}
		});
		
	}

	function checkAndSetGifButtonsInIE6 () {
		
		
		
		if(jQuery.browser.msie) {
			
			var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
			if (ie6) {
				$("#ovrly-holdingPen .footer .pastPurchasesLabels img").each(
					function(index, image) {
						var imageSrc = String($(image).attr('src'));
						if (imageSrc.indexOf('.png')) {
								$(image).attr('src',imageSrc.replace('.png', '.gif'));
						}
					}
					
					);
					
			}
		}
		
	}
	

	this.getRecentPurchasesCallback = function(response) {
		
		if(isPopUpError (response, "HoldingPenCallError", "Error Retrieving Purchases")) {
			return false;
		}
		
		//alert ('Got recent Purchases');
		hideAnyPastPurchasesPages ();
		
		$('.recentPurchases').html(response.output).show();
		
		checkAndSetGifButtonsInIE6 ();	
		
		$("#ovrly-holdingPen .footer").pngFix();
		
	}

	function getHoldingPen(e) {
		e.preventDefault(e);
		ui.request({
			baseURL: $.hosts.commServices,
			parameters: "?page=library&uiAction=GetHoldingPenList&bnOutput=1",
			callback: {name: "cbf", value: "jQuery.global.HoldingPen.getHoldingPenCallback"}
		});
		
	}

	this.getHoldingPenCallback = function(response) {
		
		if(isPopUpError (response, "HoldingPenCallError", "Error Retrieving Purchases")) {
			return false;
		}
		
		overlay.set.content(response.output);
		overlay.open();

		$("input.holdingPenItemType").click(toggleView);
		
		checkAndSetGifButtonsInIE6 ();
		
		$("#ovrly-holdingPen .footer").pngFix();
		
		//getPastPurchasesPage ({isFirstCall:true}); // for testing only


	}

	this.getFirstPastPurchasesCallback = function (response) {

		if(isPopUpError (response, "HoldingPenCallError", "Error Retrieving Purchases")) {
			return false;
		}

		if (response.status == "True") {
			
			addNewPageHTML (response);

			gatherInfoOnFirstPage ();
			
			updateLabelsAndListeners ();

			
			AddListenersForPastPurchasesLinks ();
		
			
		}
	}
	

	this.getHoldingPenWithPastCallback = function (response) {
		
		if(isPopUpError (response, "HoldingPenCallError", "Error Retrieving Purchases")) {
			return false;
		}
		
		overlay.set.content(response.output);
		overlay.open();

		$("input.holdingPenItemType").click(toggleView);

		checkAndSetGifButtonsInIE6 ();

		$("#ovrly-holdingPen .footer").pngFix();
		
		AddListenersForPastPurchasesLinks ();

		gatherInfoOnFirstPage ();
			
		updateLabelsAndListeners ();

	}

	this.getPastPurchasesCallback = function (response) {

		if(isPopUpError (response, "HoldingPenCallError", "Error Retrieving Purchases")) {
			return false;
		}

		if (response.status == "True") {
			addNewPageHTML (response);
			gatherInfoOnCurrentPage();
			updateLabelsAndListeners ();
		}
	}

	

	function goToNextPastPurchases (e) {

		e.preventDefault(e);

		//console.log('attempting next');
		var newPageIndex = pastPurchasesInfo.currentPageIndex + 1;

		goToOtherPastPurchasesPage (newPageIndex);
		
	}


	function goToPrevPastPurchases (e) {

		e.preventDefault(e);


		var newPageIndex = pastPurchasesInfo.currentPageIndex - 1;
		
		goToOtherPastPurchasesPage (newPageIndex);

	}

	function goToOtherPastPurchasesPage (newPageIndex) {
	
		if ($('#pastPurchasesPage-' + newPageIndex).exists()) {
			redisplayOtherPage(newPageIndex);
		}
		else if (pastPurchasesInfo.isPopulated) {
			getPastPurchasesPage ({'newPageIndex': newPageIndex});
		}	
		else {
			getPastPurchasesPage ({'newPageIndex': newPageIndex, 'isFirstCall': true});
		}
	}


	function redisplayOtherPage(newPageIndex) {
			
		otherPage = $('#pastPurchasesPage-' + newPageIndex); 
		
		if ($(otherPage).exists()) {	
			$('.pastPurchases .currentPage').removeClass('currentPage').hide();
			$(otherPage).addClass('currentPage').show();
			pastPurchasesInfo.currentPage = $(otherPage);
			pastPurchasesInfo.currentPageIndex = newPageIndex;
			pastPurchasesInfo.currentPageObj = pastPurchasesInfo[newPageIndex];
			updateLabelsAndListeners ();	

			// hide the Recent Purchases div, which may, or may not be visible at this time
			$('#ovrly-holdingPen .recentPurchases').hide();
			
			// show the .pastPurchases div incase it is hidden
			$('.pastPurchases').show();
		}
		
	}

	
	function hideAnyPastPurchasesPages () {

		$('.pastPurchases .pastPurchasesPage').hide().removeClass('currentPage');
		$('.pastPurchasesLabels').hide();
		pastPurchasesInfo.isActive = false;

	}

	function getPastPurchasesPage (settings) {
		
		var nextIndex = 0; // default to first page 
		var nextIndexParameter = "";
		var maxnumParameter = "";
		var ce_Parameter = "";
		var myCBF = "jQuery.global.HoldingPen.getPastPurchasesCallback";
		var myParameters = "";

		if (settings && settings.newPageIndex && Number(settings.newPageIndex) > -1) {
			nextIndex = settings.newPageIndex; 
		}
		
		
		if (settings && settings.isFirstCall) {
			myCBF = "jQuery.global.HoldingPen.getFirstPastPurchasesCallback";
		}
		
		if (settings && settings.isFirstCallForPastPurchases) {
			ce_Parameter += "&ce_FirstCallForPastPurchases=1"; 
			myCBF = "jQuery.global.HoldingPen.getHoldingPenWithPastCallback"
		}

		$('.pastPurchases').show(); 

		nextIndexParameter = "&index=" + nextIndex;
		maxnumParameter = "&maxnum=" + pastPurchasesInfo.PageSizeToRequest;
		
		myParameters = "?bnOutput=1&page=library&uiAction=GetPastPurchaseList" + nextIndexParameter + maxnumParameter + ce_Parameter;
		
		ui.request({
			baseURL: $.hosts.commServices,
			parameters: myParameters,
			callback: {name: "cbf", value: myCBF}
		});
		

	}

	
	function addNewPageHTML (response) {
		
		// hide any other pre-existing pages:
		$('.pastPurchases .currentPage').removeClass('currentPage').hide();
		
		// hide the Recent Purchases div, which may, or may not be visible at this time
		$('#ovrly-holdingPen .recentPurchases').hide();

		
		// add this new page (the response the html is assumed to contina the class 'currentPage':
		$('.pastPurchases').append(response.output);	
	}
	
	function AddListenersForPastPurchasesLinks () {

		$("#ovrly-holdingPen .pastPurchasesLabels").delegate("click", {
			"button.next, img.next": goToNextPastPurchases,
			"button.previous, img.next" : goToPrevPastPurchases
		});
		
		// the img.next is to accomidate Safarri and Chrome - 3-3-2009
	}
	
	function updateLabelsAndListeners () {


		updatePastPurchasesLabel ();

		updatePastPurchasesPagination ();
		
		pastPurchasesInfo.isActive = true;	
		pastPurchasesInfo.isPopulated = true;

		if (Number($(pastPurchasesInfo.currentPage).height()) < 350) {
			
			$(pastPurchasesInfo.currentPage).css({'height': '370px'});
		}

		$('.pastPurchasesLabels').show();	
		$(pastPurchasesInfo.currentPage).show();

	}

	function gatherInfoOnFirstPage () {



		var currentPage = gatherInfoOnCurrentPage();
		
		pastPurchasesInfo.pageSize = Number($(currentPage).find('.pastPurchasesPageInfo .pageSize').text());
		pastPurchasesInfo.totalItemCount = Number($(currentPage).find('.pastPurchasesPageInfo .itemTotalCount').text());

	}

	function gatherInfoOnCurrentPage () {
		
		var currentPage = $(".pastPurchasesPage[class*=currentPage]");
		pastPurchasesInfo.currentPage = currentPage;
		pastPurchasesInfo.currentPageIndex = Number($(currentPage).attr('id').split('-')[1]);
		pastPurchasesInfo[pastPurchasesInfo.currentPageIndex] = {};
		pastPurchasesInfo[pastPurchasesInfo.currentPageIndex].firstItemIndex = Number(pastPurchasesInfo.currentPageIndex * pastPurchasesInfo.pageSize);
		pastPurchasesInfo[pastPurchasesInfo.currentPageIndex].lastItemIndex =  Number($(currentPage).find('.pastPurchasesPageInfo .lastItemIndexOnPage').text()); 
		pastPurchasesInfo.currentPageObj = pastPurchasesInfo[pastPurchasesInfo.currentPageIndex];		
		// lastItemIndex may be different from firstItemIndex + pageSize when dealing with the last page which may not have a full page of items		

	}

	function updatePastPurchasesLabel () {
	
		var newLabel = String((pastPurchasesInfo.currentPageObj.firstItemIndex + 1) 
							  	+ " to " 
								+ (pastPurchasesInfo.currentPageObj.lastItemIndex + 1) 
								+ "<br/> of " 
								+ (pastPurchasesInfo.totalItemCount));
		
		// update labels :
		$('.pastPurchasesLabels .paginationLabel').html(newLabel);
	}
	
	function updatePastPurchasesPagination () {
	
	
		if ((pastPurchasesInfo.currentPageObj.lastItemIndex + 1) >= pastPurchasesInfo.totalItemCount) {
			// then no more pages available after this one
			$('.pastPurchasesLabels li.next_on').hide();
			$('.pastPurchasesLabels li.next_off').show();
		}
		else {
			$('.pastPurchasesLabels li.next_on').show();
			$('.pastPurchasesLabels li.next_off').hide();			
		}
		
		if (pastPurchasesInfo.currentPageObj.firstItemIndex <= 0) {
			// then no more pages available after this one
			$('.pastPurchasesLabels li.previous_on').hide();
			$('.pastPurchasesLabels li.previous_off').show();			
		} 
		else {
			$('.pastPurchasesLabels li.previous_on').show();
			$('.pastPurchasesLabels li.previous_off').hide()			
		}

		
	}
	
	function close(e) {
		if(e && e.preventDefault) { e.preventDefault(e); }
		
		pastPurchasesInfo.isActive = false;
		pastPurchasesInfo.isPopulated = false;
		
		overlay.close();
	}

	function checkAll(e) {
		e.preventDefault(e);

		assignCheckStatus ("checked");
		
		updateAddButton ();
	}

	function uncheckAll(e) {
		e.preventDefault(e);

		assignCheckStatus ("");

		updateAddButton ();
	}
	
	function assignCheckStatus (newStatus) {
	
	
		var selector = "#ovrly-holdingPen input:enabled"; 

		if (pastPurchasesInfo.isActive) {
			selector = "#ovrly-holdingPen .currentPage input:enabled";
		}

		$(selector).each(function(index, item) {
			item.checked = newStatus;
		});
	
	}
	
	function updateAddButton () {

		if(false) {		// This was found to be defective in ie6 do to the effects of the PNGfix.
		
			
			if ($("#ovrly-holdingPen input:checked").exists ()) {
				$("#ovrly-holdingPen .btn_add #holdingPenAddNoneImg").hide()
				$("#ovrly-holdingPen .btn_add #holdingPenAddImg").show()
	
			}
			else {
				$("#ovrly-holdingPen .btn_add #holdingPenAddNoneImg").show()
				$("#ovrly-holdingPen .btn_add #holdingPenAddImg").hide()
	
			}
		}
		
	/*	if(jQuery.browser.msie) {
			$("#ovrly-holdingPenContent .btn_add").pngFix()
		}
	*/	
	}
	

	function addItems() {

		var items = "";
		
		var inputs = {};

		if (! pastPurchasesInfo.isActive) {
			
			inputs = $("#ovrly-holdingPen .recentPurchases input:enabled");
		}
		else {
			inputs = $("#ovrly-holdingPen .pastPurchases input:enabled");
		}
		
		$(inputs).each(function(index, item) {
			if(item.checked) {
				items += item.id + ",";
			}
		});
		//alert('XXXXX test adding (' + items.split(',').length + ') items :"'+items+'"');
		ui.request({
			baseURL: $.hosts.commServices,
			parameters: "?page=Library&uiAction=AddItemFromHoldingPen&items="+items+"&bnOutput=1",
			errorMsgHolder: $('div.recentPurchases'),
			callback: {name: "cbf", value: "jQuery.global.HoldingPen.addItemsCallback"}
		});
		
	}

	this.addItemsCallback = function(response, errorMsgHolder) {

		if( isLocalizedErrorFound (response, "", "AddHoldingPenFail", $(errorMsgHolder))) {
			return;
		}

		$.global.MyLibrary.reload({});
		$("#holdingPenAlert").remove();
		close();
	}

	init();
}


$(function() {
	
	$.global.EditAuthorPrompt = new $.Confirm({
		id: "editAuthorPrompt",
		width: 400,
		heading: "EDIT YOUR FAVORITE AUTHORS",
		content: $("#ovrly-favoriteAuthor"),
		cancel: {
			path: "button.btn_cancel_Author",
			action: function(){
				return true;
			}
		},
		ok: {
			path: "button.btn_save_Author",
			action: Call_InputAuthor_List
		}
	});
	
	$.global.EditActorPrompt = new $.Confirm({
		id: "editActorPrompt",
		width: 450,
		heading: "EDIT YOUR FAVORITE ACTORS &amp; DIRECTORS",
		content: $("#ovrly-favoriteActor"),
		cancel: {
			path: "button.btn_cancel_Actor",
			action: function(){
				return true;
			}
		},
		ok: {
			path: "button.btn_save_Actor",
			action: Call_InputActor_List
		}
	});
	
	$.global.EditArtistPrompt = new $.Confirm({
		id: "editArtistPrompt",
		width: 400,
		heading: "EDIT YOUR FAVORITE ARTISTS",
		content: $("#ovrly-favoriteArtist"),
		cancel: {
			path: "button.btn_cancel_Artist",
			action: function(){
				return true;
			}
		},
		ok: {
			path: "button.btn_save_Artist",
			action: Call_InputArtist_List
		}
	});
	
	$.global.EditBooksGenrePrompt = new $.Confirm({
		id: "editBooksGenrePrompt",
		width: 750,
		heading: "EDIT YOUR FAVORITE BOOK GENRES",
		content: $("#ovrly-favoriteBooksGenres"),
		cancel: {
			path: "button.btn_cancel_Books",
			action: function(){
				return true;
			}
		},
		ok: {
			path: "button.btn_save_Books",
			action: Call_InputBookGenre_List
		}
	});
	
	$.global.EditFilmGenrePrompt = new $.Confirm({
		id: "editFilmGenrePrompt",
		width: 750,
		heading: "EDIT YOUR FAVORITE FILM GENRES",
		content: $("#ovrly-favoriteFilmGenres"),
		cancel: {
			path: "button.btn_cancel_Film",
			action: function(){
				return true;
			}
		},
		ok: {
			path: "button.btn_save_Film",
			action: Call_InputFilmGenre_List
		}
	});
	
	$.global.EditMusicGenrePrompt = new $.Confirm({
		id: "EditMusicGenrePrompt",
		width: 750,
		heading: "EDIT YOUR FAVORITE CD STYLES",
		content: $("#ovrly-favoriteMusicGenres"),
		cancel: {
			path: "button.btn_cancel_Music",
			action: function(){
				return true;
			}
		},
		ok: {
			path: "button.btn_save_Music",
			action: Call_InputMusicGenre_List
		}
	
	});

});



function getLithiumBookClubList(){

	myParameters = "?xslt=json.xsl";

	ui.request({
		baseURL: $.hosts.bookClubs + "/restapi/vc/categories/id/top",
		parameters: myParameters,
		callback: {
			name: "callback",
			value: "bookClubCallBack"
		}
	});
	return true;

}

function bookClubCallBack(lithiumResponse){
	bookClubName = new Array();
	bookClubID = new Array();
	bookClubURL = new Array();
	bookClubListHTML = ""

	if (lithiumResponse.response.error != null) {
		lithiumTest = lithiumResponse.response.error.$
	} else {
		lithiumTest = lithiumResponse.response.category.boards
	}

	if (lithiumTest != null) {
		for (i = 0; i < lithiumResponse.response.category.boards.board.length; i++) {
			//alert(lithiumResponse.response.category.boards.board[i].title.$);

			bookClubName = lithiumResponse.response.category.boards.board[i].title.$
			bookClubID = lithiumResponse.response.category.boards.board[i].id.$
			bookClubURL = lithiumResponse.response.category.boards.board[i].href

			bookClubListHTML += '<option value='+bookClubID+' id='+bookClubID+'>' + bookClubName + '</option>';
		}
		//alert(bookClubListHTML)
		$('#addClubDropDown').append(bookClubListHTML);
		} else {
			$("#bookclubsError").html("");
			$("#bookclubsError").append('<div class="errorMsg">The system could not retrieve all of the Book Clubs at this time.</div>')
			$("#bookclubsError div.errorMsg").show();
		}

		myParameters = "?xslt=json.xsl";

		ui.request({
		baseURL: $.hosts.bookClubs + "/restapi/vc/categories/id/BNBlogs",
		parameters: myParameters,
		callback: {
			name: "callback",
			value: "bookClubBooksBlogsCallBack"
		}
	});
	return true;
}

function bookClubBooksBlogsCallBack(lithiumResponse){
	bookClubName = new Array();
	bookClubID = new Array();
	bookClubURL = new Array();
	bookClubListHTML = ""

	if (lithiumResponse.response.error != null) {
		lithiumTest = lithiumResponse.response.error.$
	} else {
		lithiumTest = lithiumResponse.response.category.boards
	}

	if (lithiumTest != null) {
		for (i = 0; i < lithiumResponse.response.category.boards.board.length; i++) {
			//alert(lithiumResponse.response.category.boards.board[i].title.$);

			bookClubName = lithiumResponse.response.category.boards.board[i].title.$
			bookClubID = lithiumResponse.response.category.boards.board[i].id.$
			bookClubURL = lithiumResponse.response.category.boards.board[i].href

			bookClubListHTML += '<option value='+bookClubID+' id='+bookClubID+'>' + bookClubName + '</option>';
		}
		//alert(bookClubListHTML)
		$('#addClubDropDown').append(bookClubListHTML);
		} else {
			$("#bookclubsError").html("");
			$("#bookclubsError").append('<div class="errorMsg">The system could not retrieve all of the Book Clubs at this time.</div>')
			$("#bookclubsError div.errorMsg").show();
		}

		myParameters = "?xslt=json.xsl";

		ui.request({
		baseURL: $.hosts.bookClubs + "/restapi/vc/categories/id/firstlook",
		parameters: myParameters,
		callback: {
			name: "callback",
			value: "bookClubFirstLookCallBack"
		}
	});
	return true;

}


function bookClubFirstLookCallBack(lithiumResponse){
	bookClubName = new Array();
	bookClubID = new Array();
	bookClubURL = new Array();
	bookClubListHTML = ""

	if (lithiumResponse.response.error != null) {
		lithiumTest = lithiumResponse.response.error.$
	} else {
		lithiumTest = lithiumResponse.response.category.boards
	}

	if (lithiumTest != null) {
		for (i = 0; i < lithiumResponse.response.category.boards.board.length; i++) {
			//alert(lithiumResponse.response.category.boards.board[i].title.$);

			bookClubName = lithiumResponse.response.category.boards.board[i].title.$
			bookClubID = lithiumResponse.response.category.boards.board[i].id.$
			bookClubURL = lithiumResponse.response.category.boards.board[i].href

			bookClubListHTML += '<option value='+bookClubID+' id='+bookClubID+'>' + bookClubName + '</option>';
		}
		//alert(bookClubListHTML)
		$('#addClubDropDown').append(bookClubListHTML);
		} else {
			$("#bookclubsError").html("");
			$("#bookclubsError").append('<div class="errorMsg">The system could not retrieve all of the Book Clubs at this time.</div>')
			$("#bookclubsError div.errorMsg").show();
		}

		myParameters = "?xslt=json.xsl";

		ui.request({
		baseURL: $.hosts.bookClubs + "/restapi/vc/categories/id/BooksAuthors",
		parameters: myParameters,
		callback: {
			name: "callback",
			value: "bookClubBooksAuthorsCallBack"
		}
	});
	return true;

}

function bookClubBooksAuthorsCallBack(lithiumResponse){
	bookClubName = new Array();
	bookClubID = new Array();
	bookClubURL = new Array();
	bookClubListHTML = ""

	if (lithiumResponse.response.error != null) {
		lithiumTest = lithiumResponse.response.error.$
	} else {
		lithiumTest = lithiumResponse.response.category.boards
	}

	if (lithiumTest != null) {
		for (i = 0; i < lithiumResponse.response.category.boards.board.length; i++) {
			//alert(lithiumResponse.response.category.boards.board[i].title.$);

			bookClubName = lithiumResponse.response.category.boards.board[i].title.$
			bookClubID = lithiumResponse.response.category.boards.board[i].id.$
			bookClubURL = lithiumResponse.response.category.boards.board[i].href

			bookClubListHTML += '<option value='+bookClubID+' id='+bookClubID+'>' + bookClubName + '</option>';
		}
		//alert(bookClubListHTML)
		$('#addClubDropDown').append(bookClubListHTML);
		} else {
			$("#bookclubsError").html("");
			$("#bookclubsError").append('<div class="errorMsg">The system could not retrieve all of the Book Clubs.</div>')
			$("#bookclubsError div.errorMsg").show();
		}

		myParameters = "?xslt=json.xsl";

		ui.request({
		baseURL: $.hosts.bookClubs + "/restapi/vc/categories/id/CD",
		parameters: myParameters,
		callback: {
			name: "callback",
			value: "bookClubCDCallBack"
		}
	});
	return true;


}

function bookClubCDCallBack(lithiumResponse){
	bookClubName = new Array();
	bookClubID = new Array();
	bookClubURL = new Array();
	bookClubListHTML = ""
	
	if (lithiumResponse.response.error != null) {
		lithiumTest = lithiumResponse.response.error.$
	} else {
		lithiumTest = lithiumResponse.response.category.boards
	}

	if (lithiumTest  != null) {
		for (i = 0; i < lithiumResponse.response.category.boards.board.length; i++) {
			//alert(lithiumResponse.response.category.boards.board[i].title.$);

			bookClubName = lithiumResponse.response.category.boards.board[i].title.$
			bookClubID = lithiumResponse.response.category.boards.board[i].id.$
			bookClubURL = lithiumResponse.response.category.boards.board[i].href

			bookClubListHTML += '<option value='+bookClubID+' id='+bookClubID+'>' + bookClubName + '</option>';
		}

		$('#addClubDropDown').append(bookClubListHTML);
	
		// Next step in the daisy chain:
		getLithiumProfile();

	} else {
		$("#bookclubsError").html("");
		$("#bookclubsError").append('<div class="errorMsg">The system could not retrieve all of the Book Clubs.</div>')
		$("#bookclubsError div.errorMsg").show();
	}
}


function getLithiumProfile(){
	
	// Now that the bookclub list has been recieved, begin the 5 api calls to get the bokkclub-profile data from lithium
	var bnPenName = $('#bnPenName').text();

	myParameters = "?xslt=json.xsl";
	
	ui.request({
		baseURL: $.hosts.bookClubs + "/restapi/vc/users/login/",
		parameters: bnPenName + myParameters,
		callback: {
			name: "callback",
			value: "lithiumProfileCallback"
		}
	});
	
	return true;

}

$.global.lithium = new Object();

$.global.lithium.profileID = "";

function lithiumProfileCallback(lithiumResponse) {

	var profileStatus = ""

	if (lithiumResponse) {
	
		profileStatus = lithiumResponse.response.status
	
		if (profileStatus == "success") {
	
			$.global.lithium.profileID = lithiumResponse.response.user.id.$
			
		
			seeMyProfileHTML = "<a class='left-arrow-small' href=\"" + $.hosts.bookClubs + "/bn/profile?user.id=" +$.global.lithium.profileID+ "\">" + $('#seeMyProfileText').html() + "</a>";
		
			$('#seeMyLithiumProfile').append(seeMyProfileHTML);
			$('#seeMyLithiumProfile').show();
	
			// Start gathering other user profile values through a daisy-chain of rest calls.  
			// This is called at the end of the daisy chain to populate the Select drop of available book clubs defined in getLithiumBookClubList()
			myParameters = "?xslt=json.xsl&";

			ui.request({
				baseURL: $.hosts.bookClubs + "/bn/restapi/vc/users/id/" + $.global.lithium.profileID + "/ranking/name",
				parameters: myParameters,
				callback: {
					name: "callback",
					value: "bookClubRankCallBack"
				}
			});
			
	
		}

	}
}

function bookClubRankCallBack (lithiumResponse) {
	var lithiumCallFailed = false;
	var lithiumValue = null;
	
	if (lithiumResponse.response.error != null) {
		lithiumCallFailed = true;
	} 
	else if (lithiumResponse.response.value.$ != "" || (lithiumResponse.response.value.$ == "0" && context.pageType == 'profileOwner')) {
		
		seeMyProfileHTML = "<div class='seeMyLithiumRank'>Rank: " + lithiumResponse.response.value.$ + "</div>";
		
		$('#seeMyLithiumProfile').append(seeMyProfileHTML);		
	}
	
	if (!lithiumCallFailed) { // Then get the next part of the profile data
	
			myParameters = "?xslt=json.xsl&";
			
			ui.request({
					baseURL: $.hosts.bookClubs + "/bn/restapi/vc/users/id/" + $.global.lithium.profileID + "/posts/count",
					parameters: myParameters,
					callback: {
						name: "callback",
						value: "bookClubNumPostsCallBack"
					}
				});
	}
	
}

function bookClubNumPostsCallBack (lithiumResponse) {
	var lithiumCallFailed = false;
	var lithiumValue = null;
	
	if (lithiumResponse.response.error != null) {
		lithiumCallFailed = true;
	} 
	else if (lithiumResponse.response.value.$ != "" || (lithiumResponse.response.value.$ == "0" && context.pageType == 'profileOwner')) {
		seeMyProfileHTML = "<div class='seeMyLithiumNumPosts'>Number of Posts: " + lithiumResponse.response.value.$ + "</div>";
		
		$('#seeMyLithiumProfile').append(seeMyProfileHTML);		
	}
	
	if (!lithiumCallFailed) { // Then get the next part of the profile data
	
			myParameters = "?xslt=json.xsl&";
		
			ui.request({
					baseURL: $.hosts.bookClubs + "/bn/restapi/vc/users/id/" + $.global.lithium.profileID + "/kudos/received/count",
					parameters: myParameters,
					callback: {
						name: "callback",
						value: "bookClubNumLaurelsCallBack"
					}
				});
	}
		
}



function bookClubNumLaurelsCallBack (lithiumResponse) {
	var lithiumCallFailed = false;
	var lithiumValue = null;
	
	if (lithiumResponse.response.error != null) {
		lithiumCallFailed = true;
	} 
	else if (lithiumResponse.response.value.$ != "" || (lithiumResponse.response.value.$ == "0" && context.pageType == 'profileOwner')) {
		seeMyProfileHTML = "<div class='seeMyLithiumNumLaurels'>" + lithiumResponse.response.value.$ + " Laurels "
					+	"<a id='whatsThisLaurelsLink'>What's This?</a>"
					+	"</div>";
		    
		$('#seeMyLithiumProfile').append(seeMyProfileHTML);		
		
	   	$("#whatsThisLaurelsLink").click(function() {
        	showWhatsThis('BookClubLaurels');
	    });

	}
	
	if (!lithiumCallFailed) { // Then get the next part of the profile data
			myParameters = "?xslt=json.xsl&page=1&page_size=20";
		
			ui.request({
					baseURL: $.hosts.bookClubs + "/bn/restapi/vc/users/id/" + $.global.lithium.profileID + "/posts/latest",
					parameters: myParameters,
					callback: {
						name: "callback",
						value: "bookClubRecentPostsCallBack"
					}
				});
	}
		
}

function bookClubRecentPostsCallBack (lithiumResponse) {
	// Make links to actual recent posts by the user
	var lithiumCallFailed = false;
	var lithiumValue = null;
	
	if (lithiumResponse.response.error != null) {
		lithiumCallFailed = true;
	} 
	else if (lithiumResponse.response.messages != null && lithiumResponse.response.messages.hasOwnProperty('message')) {
		
		
		seeMyProfileHTML = "<div class='seeMyLithiumRecentPosts'>" 
		+ "<a class='seeMyLithiumAllPosts left-arrow-small' href='" + $.hosts.bookClubs + "/bn/tracker?user.id=" + $.global.lithium.profileID + "'>See all</a>";

		seeMyProfileHTML += "My Recent Posts: <ul class='list'>";
		
		var messageCount = 1;
		for (var messageItem in lithiumResponse.response.messages.message) {
			if (messageCount <= 3) {
				
				// also find the categories these posts occurred (only the category ID is provide in the call response.
				var currentCategoryId = (lithiumResponse.response.messages.message[messageItem].board.href.split('/').reverse())[0]; //.reverse()).pop()			
	
				// The actually category name does exist on the page already (assuming the 'Add your bookclubs' drop down has already been populate from its own lithium service calls
				var currentCategory = $("#addClubDropDown option#" + currentCategoryId);
				if ($(currentCategory).exists()) {
					currentCategory = $(currentCategory).text();
				}
				
				seeMyProfileHTML += "<li>"
								+ "		<a class='subject' href='" + $.hosts.bookClubs + "/bn/board/message?board.id=" + currentCategoryId + "&message.id=" + lithiumResponse.response.messages.message[messageItem].board_id.$ + "#M" + lithiumResponse.response.messages.message[messageItem].board_id.$ + "'>"
								+ "		" + lithiumResponse.response.messages.message[messageItem].subject.$
								+ "		</a>"
								+ "		<a class='category' href='" + $.hosts.bookClubs +  "'>"
								+ "		" + currentCategory 
								+ "		</a>"
								+ "</li>";
			}
			messageCount ++;
		}
		
		seeMyProfileHTML += "</ul>"
			+ "</div";
		
		$('#seeMyLithiumProfile').append(seeMyProfileHTML);		
	}
	
}

function addBookClub(){

	var addedBookClubID = $('#addClubDropDown').val();
	var addedBookClubName = $('#addClubDropDown').children('option[value=' + addedBookClubID +']').html();
	var addedBookClubURL = $('#addClubDropDown').children('option[value=' + addedBookClubID +']').attr('url')

   if (addedBookClubName.length >= 33) {
   	addedBookClubName = addedBookClubName.substring(0, 33) + '...';
   }


	if (addedBookClubID != 'Select') {

		//	alert (addedBookClub);
		//	alert( $(this).attr('value') );

		addedBookClubHTML = '<tr id="' + addedBookClubID + '"><td width="40"><img src="' + $.hosts.resources + '/presources/community/images/bookclubs/'+ addedBookClubID +'.gif" /></td><td width="150" class="bookclubs"><a href="' + $.hosts.bookClubs + '/bn/board?board.id=' + addedBookClubID + '">' + addedBookClubName + '</a></td>'
		addedBookClubHTML += '<td valign="middle"><div style="display:none;" id="deleteThisID-'+addedBookClubID+'">9</div><a href="javascript:void(0)" onclick="removeThisItem(this);"><img src="'+$.hosts.resources+'/presources/community/images/icon_x.png" /></a></td></tr>'
		
		var encodedBookClubName = encodeURIComponent(addedBookClubName);

		var myParameters = '?page=FavoriteBookmarks&uiAction=AddBookmark&type=9&favoriteId=' + addedBookClubID + '&title=' + encodedBookClubName

		ui.request({
			baseURL: $.hosts.commServices,
			parameters: myParameters,
			callback: {name: "cbf",	value: "clubAddedCallback"}

		});


	//	$('#addClubDropDown').children('option[value=' + addedBookClubID + ']').remove();

	}
	else {
			$("#bookclubsError").html("");
			$("#bookclubsError").append('<div class="errorMsg">Please select a Book Club from the pull-down menu; then click "Add."</div>')
			$("#bookclubsError div.errorMsg").show();
	}

}

function clubAddedCallback (response) {

	if (response.status == "True") {

		$("#bookclubsError").html("");

		$('#appendBookClubs').append(addedBookClubHTML);
		//alert("Bookclub: " + addedBookClubHTML)

		$("#appendBookClubs").children("tr").removeClass("last");
		$("#appendBookClubs").children("tr:last").addClass("last");

		var bookClubTotal = $('#appendBookClubs').children('tbody').children('tr').length

		//	alert(bookClubTotal)

		if (bookClubTotal > '4') {

			$('div.addClubs').hide();

		}
	}
	else if (response.status == "False") {
			$("#bookclubsError").html("");
			$("#bookclubsError").append("<div class='errorMsg'>This Book Club is already on your list.</div>")
			$("#bookclubsError div.errorMsg").show();
		}
	}




function removeThisItem (target) {

   var removeThisItemID = $(target).parents('tr').attr('id')
   var removeThisItemType = $("#deleteThisID-" +removeThisItemID+ "").text();
   var myParameters = '?page=FavoriteBookmarks&uiAction=RemoveBookmark&type='+ removeThisItemType +'&favoriteId=' + removeThisItemID

			ui.request({
			baseURL: $.hosts.commServices,
			parameters: myParameters,
			callback: {name: "cbf", value: "itemRemovedCallback" }

		});

		$(target).parents('tr').remove();

		if (removeThisItemID = '9') {

			var bookClubTotal = $('#appendBookClubs').children('tbody').children('tr').length

				//	alert(bookClubTotal)

				if (bookClubTotal <= '5') {

					$('div.addClubs').show();

				}

		}

}

function addProfileToFavorites(target) {

	  var communityIDarray = $(target).attr('id')
	  var splitIDArray = communityIDarray.split('|')
	  var communityID = splitIDArray[0];
	  var penName = splitIDArray[1];

		var myParameters = "?page=FavoriteBookmarks&uiAction=AddBookmark&type=0&favoriteId="+ communityID +"&title="+ penName +""

			ui.request({
			baseURL: $.hosts.commServices,
			parameters: myParameters,
			callback: {name: "cbf", value: "profileFavoriteAddedCallback" }

		});
}

function profileFavoriteAddedCallback (result) {
	if (result.status == "True") {
		alert("Profile Added.")
	//	$("<span class='flag'>Profile Added. Thank you</span>").appendTo($(self).parents("p"));
	} else
	if (result.status == "False") {
		alert("Profile Not added.")
	}
}

function showEditAboutMe () {
	$('#hideCancel').hide();
	$('#showSaveCancel').show();
	$('#editAboutMe').hide();
	$('#editableAboutMe').show();
	$('#aboutMeTextBox').maxLength(500);
	$('#aboutMeTextBox').val('').val( $('#aboutMeDescInitial').text() );
}
	
function cancelEditAboutMe(){
	$('#editableAboutMe').hide()
	$('#editAboutMe').show()
	$('div.aboutMeError').html('')
}

function saveEditAboutMe () {
	
	
	
		var newAboutMeDesc = encodeURIComponent($('#aboutMeTextBox').val());
		
	
		myParameters = "?page=UserProfile&uiAction=UpdateProfile&desc=" + newAboutMeDesc + "&bnOutput=1"
		
		ui.request({
			baseURL: $.hosts.commServices,
			parameters: myParameters,
			callback: {
				name: "cbf",
				value: "aboutMeCallback"
			}
		});


}

function aboutMeCallback (result) {
		if (result.status == "True") {
			$('#editableAboutMe').hide();
			$('#tellUsAboutMeHeader').hide();
			$('#aboutMeHeader').show();
			$('div.aboutMeError').html('')
			$('#editAboutMe').show();
			$('#editAboutMe .aboutMeDesc').html('')

			var newAboutMe = escapeHTML( $('#aboutMeTextBox').val() );

			$('#aboutMeDescInitial').text('').text( HtmlDecode(newAboutMe) )
			$('#editAboutMe .aboutMeDesc').html('').append( newAboutMe );
		} else
		if (result.status == "False") {
			$('div.aboutMeError').html('')
			$('div.aboutMeError').append('<div class="errorMsg" style="display:block;">'+ result.output +'</div>')
		}
}

function itemRemovedCallback() {

}


function showReviews(){
	$('#ratingsModule').hide();
	$('#RatingsOn').removeClass('on');
	$('#ReviewOn').addClass('on');
	$('#reviewsModule').show();
}

function showRatings() {
	$('#reviewsModule').hide();
	$('#ReviewOn').removeClass('on');
	$('#RatingsOn').addClass('on');
	$('#ratingsModule').show();
}

function createNewListError() {
	$('#essentiaListPodError').remove();
	$('#essentiaListPod').prepend('<div class="errorMsg" style="display:block;" id="essentiaListPodError">Your number of EssentiaLists has reached its limit of 100. If you wish to add this list, delete an existing one to make room.</div>')

}

function createNewWishListError() {
	$('#wishlistPodError').remove();
	$('#wishlistPod').prepend('<div class="errorMsg" style="display:block;" id="wishlistPodError">You can create only 25 Wish Lists. If you\'d like to create a new Wish List, delete an existing one to make room.</div>')

}


$.Suggestions = function(options){
	var self = this;
	var isAnimating = false;
	this.settings = $.extend(this.settings, options);
	this.settings.animationOptions.onAfter = function(){
		isAnimating = false;
	}
	var s = this.settings;
	var currentTab = 'books';
	var isLoading = false;

	this.init = function(){
		$.easing.def = 'easeOutCubic'; // default easing method
		$.scrollTo.defaults.axis = 'x';
		s.thumbnails.scrollTo( 0 );//reset all scrollable panes to (0,0)

		var suggestionEvents = {};
		var tabLink = '.' + s.tabLinkClass;
		var arrow = '.' + s.arrowClass;
		var pagination = '.' + s.paginationClass + ' img';

		$('.' + s.arrowClass).hover(
			function(){ $(this).addClass('hover'); },
			function(){ $(this).removeClass('hover'); }
		)

		if($.browser.msie) {
			$(s.container).find('div.suggestionsContent').css('zoom', '1');
		}

		this.loader.start();

		isLoading = true;
		ui.request({
			baseURL: $.hosts.commServices,
			parameters: '?page=UserProfile&uiAction=GetSuggestions&pt=BK&bnOutput=1',
			requestID: "suggestions", 
			callback: {name: 'cbf', value: '$.global.suggestions.insertTab'}
		})

		$('#emptyMsg').html("<strong>What do you like?</strong> Choose your favorite books below and we'll suggest some new titles you might enjoy!");

		suggestionEvents[tabLink] = function(e){
			if (!isLoading) {
				var $this = $(e.target);
				if ($this.is('.' + s.currentClass))
					return false;

				self.loader.start();

				$('.' + s.tabLinkClass).removeClass(s.currentClass);
				$this.addClass(s.currentClass);
				s.thumbnails.scrollTo(0);//reset all scrollable panes to (0,0)
				$('.' + s.arrowClass + '.previous').hide();
				$('.' + s.arrowClass + '.next').show();

				switch ($this.attr('rel')) {
					case 'books':
						var type = 'BK';
						var msg = "<strong>What do you like?</strong> Choose your favorite books below and we'll suggest some new titles you might enjoy!";
						break;
					case 'dvds':
						var type = 'VD';
						var msg = "<strong>What do you like?</strong> Choose your favorite films below and we'll suggest some new titles you might enjoy!";
						break;
					case 'music':
						var type = 'MU';
						var msg = "<strong>What do you like?</strong> Choose your favorite music below and we'll suggest some new titles you might enjoy!";
						break;
				}

				$('#emptyMsg').html(msg);

				currentTab = $this.attr('rel');

				if ($('#tab-' + $this.attr('rel')).exists()) {
					$('.' + s.tabClass + '.' + s.currentClass).removeClass(s.currentClass);
					$('#tab-' + $this.attr('rel')).addClass(s.currentClass);
					$('#emptyMsg').hide();
					generatePagination();
					self.loader.stop();
				}
				else {
					isLoading = true;
					ui.request({
						baseURL: $.hosts.commServices,
						parameters: '?page=UserProfile&uiAction=GetSuggestions&pt=' + type + '&bnOutput=1',
						requestID: "suggestions", 
						callback: {
							name: 'cbf',
							value: '$.global.suggestions.insertTab'
						}
					});
				}
			}

			return false;
		}

		suggestionEvents[arrow] = function(e){
			if(!isAnimating){
				var $currentStrip = s.thumbnails.children('.' + s.currentClass).children('.' + s.currentClass);
				var direction = $(e.target).attr('rel');

				if ($currentStrip[direction]('.' + s.stripClass).exists()) {
					var $nextStrip = $currentStrip[direction]('.' + s.stripClass);
					$currentStrip.removeClass(s.currentClass);
					$nextStrip.addClass(s.currentClass);
					isAnimating = true;
					var nextStripId;
					var classes = $nextStrip.attr('class').split(' ');
					$.each(classes, function(k, v){
						if(v.indexOf('strip-') != -1) nextStripId = v;
					})
					var $oldPaginate = $('.' + s.paginationClass + ' img.' + s.currentClass);
					var $newPaginate = $('.' + s.paginationClass + '[rel=' + nextStripId + '] img');
					paginateHighlight($oldPaginate, 'off');
					paginateHighlight($newPaginate, 'on');
					s.thumbnails.scrollTo($nextStrip, s.speed, s.animationOptions);
				}
			}

			return false;
		}

		suggestionEvents[pagination] = function(e){
			if ($(e.target).parent().is('.' + s.paginationClass)) {
				if (!isAnimating) {
					var $current = s.thumbnails.children('.' + s.currentClass).children('.' + s.currentClass);
					var page = $(e.target).parent().attr('rel');
					if ($current.is('.' + page))
						return false;

					var $new = $current.parents('.' + s.tabClass).children('.' + page);

					if ($new.exists()) {
						var $old = $('.' + s.paginationClass + ' img.' + s.currentClass);
						paginateHighlight($old, 'off');
						$current.removeClass(s.currentClass);
						$new.addClass(s.currentClass);
						isAnimating = true;
						paginateHighlight($(e.target), 'on');
						s.thumbnails.scrollTo($new, s.speed, s.animationOptions);
					}
				}

				return false;
			}
		}

		s.container.delegate('click', suggestionEvents);
	}

	this.loader = {
		start: function(){
			if (!s.thumbnails.parent().find('div.loader').exists()) {
				s.thumbnails.parent().append('<div class="loader">&nbsp;</div>');
				s.container.find('div.suggestionsHeader').append('<div class="loaderMsg"><img src="http://images.barnesandnoble.com/presources/images/ajax-loader.gif" /> <span>Loading...</span></div>')
			}
		},
		stop: function(){
			s.container.find('div.loader').remove();
			s.container.find('div.loaderMsg').remove();
		}
	}

	this.insertTab = function(response){
		if (response.output != '' && response.output != '<Products></Products>' && response.output != '<Products/>' && String(response.output).indexOf('<div class=\"tab current\">\r\n  <div class=\"strip strip-1 current\">\r\n    <ul></ul>\r\n  </div>\r\n</div>') == -1) {  // See covers when the Suggestions are 'off' for server load reasons (case 1), or when then user does not have suggestions for them (case 2 and 3 and 4) 
			s.thumbnails.children('.' + s.currentClass).removeClass(s.currentClass);
			$('#emptyMsg').hide();
			s.thumbnails.append(response.output);
			s.thumbnails.children('.' + s.tabClass + '.' + s.currentClass).attr('id', 'tab-' + currentTab);
			
			ProductPreview.initialize(); //initializes ProductPreview in /pimages/js/product-preview-core.js
			overrideProductPreview();
			
			
			if ($.global.penNamePopUpQuestion.shouldAskQuestion()){ 
				//alert ('Bounding PanName Links Dynamically');					
				$.addPreventDepartureListners($(s.thumbnails.find("a")), $.global.penNamePopUpQuestion);
			}	
			else if ($.global.privacyPopUpQuestion.shouldAskQuestion()) { 
				//alert ('Bounding Privacy Links Dynamically');										
				$.addPreventDepartureListners($(s.thumbnails.find("a")), $.global.privacyPopUpQuestion);
		
			}
		

			
			self.loader.stop();
		}
		else {
			$('.' + s.tabClass).removeClass(s.currentClass);
			$('#emptyMsg').show();
			self.loader.stop();
		}

		isLoading = false;

		generatePagination();
	}
	
	function overrideProductPreview() {
		ProductPreview.positionPreview = function() {
			this.previewObj.style.display="";

		    var topPos = 0, leftPos = 0;
	        var rePositionLeft = false, rePositionTop = false;
	        var offSets = ProductPreview.getOffsets(this.target);
			if($(this.target).hasClass("suggestionLink")) {
				offSets.offsetLeft = $(this.target).position().left + 650;
			}
	        var spacing = this.target.offsetWidth/2;
	        leftPos = offSets.offsetLeft + 4 + spacing;    
		    topPos = offSets.offsetTop + this.target.offsetHeight + 4;
	    	
		    if (ProductPreview.isInFrame()) {
		        var iframeObj = ProductPreview.getIFrameReference(window);
			    if (iframeObj) {
			        var iframeOffsets = ProductPreview.getOffsets(iframeObj);
				    leftPos += iframeOffsets.offsetLeft;
				    topPos += iframeOffsets.offsetTop;
			    }
		    }
	    		
		    var windowDim = ProductPreview.getWindowScroll();
		    var w = 750; // fixed width layout ignore windowDim.width;
	    	
	    	if (this.isLithium)
	    	    w = windowDim.width;
	    	
		    var spaceWidth =  w - leftPos;
	        rePositionLeft = spaceWidth < 320;
	    	
		    var t = windowDim.top;
		    var h = windowDim.height;
		    var heightTooltip = this.previewObj.clientHeight;
	    	
		    if (t+h-topPos < heightTooltip) {
		        topPos = topPos - this.target.offsetHeight - heightTooltip;
		        rePositionTop = true;
		    }
	    	
		    if (!rePositionLeft) {
		        this.previewObj.style.top = topPos + "px";
		        this.previewObj.style.left = leftPos + "px";
		    }
		    else {
		        this.previewObj.style.left = leftPos - spacing - this.previewObj.clientWidth + "px";
		        if (!rePositionTop)
		            this.previewObj.style.top = topPos - this.target.offsetHeight + "px";
		        else
		             this.previewObj.style.top = topPos + this.target.offsetHeight + "px";
		    }

		}
	}

	function generatePagination(){
		s.footer.html('');
		var pages = s.container.find('.' + s.tabClass + '.' + s.currentClass).find('.' + s.stripClass).size();
		var hasPages = false;

		for(var i = 0; i < pages; i++){
			var num = i+ 1;
			var state = (num == 1) ? 'on' : 'off';
			var current = (num == 1) ? s.currentClass : '';
			s.footer.append('<a href="#" class="paginate" rel="strip-' + num + '"><img src="' + $.hosts.resources + '/presources/community/images/s4u/paginate_' + state + '.gif" class="' + current + '" /></a>')
			hasPages = true;
		}

		if (!hasPages) $('.' + s.arrowClass + '.next').hide();
	}

	function paginateHighlight(img, state){
		var src = img.attr('src')
		var index = src.indexOf('_');
		var newSrc = src.substring(0, index);
		img.attr('src', newSrc + '_' + state + '.gif')
		if (state == 'on') img.addClass(s.currentClass);
		else if (state == 'off') img.removeClass(s.currentClass);

		if (s.footer.find('.' + s.paginationClass + ':last img').is('.' + s.currentClass))  $('.' + s.arrowClass + '.next').hide();
		else $('.' + s.arrowClass + '.next').show();

		if (s.footer.find('.' + s.paginationClass + ':first img').is('.' + s.currentClass))  $('.' + s.arrowClass + '.previous').hide();
		else $('.' + s.arrowClass + '.previous').show();
	}

	this.init();
}

jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing, {
	def: 'easeOutCubic',
	swing: function (x, t, b, c, d) {
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	}
});

function resetCacheHistory(e) {
	//alert(window.location.href)
	document.location.href.replace(window.location.href + '#');
	return false;
}


$(function(){ 
	var toggleFavorites = function(param1, param2, cat){
		$("#"+param2+"_"+cat).hide();
		$("#"+param1+"_"+cat).show();
		$("#"+param2+"_"+cat+"_tab").removeClass("on");
		$("#"+param1+"_"+cat+"_tab").addClass("on");
	}
	var typesArray = ["Books","Film","Music"];
	$("#favoritesWidget .widget-header .tabs a").click(function(){
		var tab = $(this);
		for(var x=0; x<typesArray.length; x++){
			if(typesArray[x] == tab.attr("id")){
				$(".favorite"+typesArray[x]).show();
				tab.addClass("on");
			}else{
				$(".favorite"+typesArray[x]).hide();
				$("#favoritesWidget .widget-header .tabs a").each(function(){
					if(typesArray[x] == $(this).attr("id")){
						$(this).removeClass("on");
					}
				});
			}
		}
	});

	$("#favoritesWidget .footer-plain .tabs a").click(function(){
		var footerTab = $(this);
		var tabParent = footerTab.parent();
		if(tabParent.attr("id") == "Books"){
			if(footerTab.attr("id") == "Author_Books_tab"){
				toggleFavorites("Author", "Genres", "Books");
			}else{
				toggleFavorites("Genres", "Author", "Books");
			}
		}else if(tabParent.attr("id") == "Film"){
			if(footerTab.attr("id") == "Actor_Film_tab"){
				toggleFavorites("Actor", "Genres", "Film");
			}else{
				toggleFavorites("Genres", "Actor", "Film");
			}
		}else{
			if(footerTab.attr("id") == "Artist_Music_tab"){
				toggleFavorites("Artist", "Genres", "Music");
			}else{
				toggleFavorites("Genres", "Artist", "Music");
			}
		}
	})
	if(jQuery.browser.msie) {
		$(".activeAvatarContainer").pngFix();
	}
});


/*
function escapeHTML (str) {
	//moved to ui.js
}


function HtmlDecode(s) {
	//moved to ui.js
}

*/


$(function() { 
		   
	if (typeof cmCreatePageviewTag !== "undefined") {
		
		var userPenName = "ANONYMOUS";
		
		if($('#userPenName').exists() && $('#userPenName').text() != "") {
			userPenName = $('#userPenName').text(); 
		} 
		
		cmCreatePageviewTag ("COMM-PROFILE: " + userPenName, "COMMUNITY"); 
		
	}

});


$.ActivityFeedDisplay = function () {

	var self = this;

	function init () {
		self.applyPrivacyMessage();
		self.applyFilterAndPaginationListeners();	
	}

	self.applyFilterAndPaginationListeners = function () {
		
		$("a.peopleActivitiesOption").click(function(e) {
			 e.preventDefault(e);
			 self.refreshActivityFeedService ('FriendsActivity')
		});
		$("a.myActivitiesOption").click(function(e) {
			 e.preventDefault(e);													 
			 self.refreshActivityFeedService ('MyActivity')
		});
		$("a.bothActivitiesOption").click(function(e) {
			 e.preventDefault(e);
			 self.refreshActivityFeedService ('MyAndFriendsActivity')
		});
		$("#activityFeedWidget a.paginate").click(function(e){
			e.preventDefault(e);
			self.paginate(e);
		});
		
	}
	
	self.applyPrivacyMessage = function() {

		if (context.profilePrivacyLevel == "Private") {

			$("#activityFeedWidget .header .tabs").prepend('<div style="color:#666666; margin-bottom:6px;" class="feedPrivacyMessage"><b>Note:</b> These items are only visible to you in your private view of your profile - other users cannot see them.  Set your profile to public if you\'d like to share your activities with others. Your anonymous reviews and essentialists will not be shown when your profile is public.</div>');
				
				
		}
	}
	
	self.paginate = function(e){
		displayActivityLoadingPlaceHolder();
		ui.request({ 
			baseURL: $.hosts.commServices,
			parameters: $(e.target).get(0).name,
			callback: {name: "cbf", value: "$.global.activityFeedDisplay.refreshActivityFeedCallBack"}
		});
	}
	self.refreshActivityFeedService = function (filterOption, pageOffset) {
	
		displayActivityLoadingPlaceHolder ();
		updateFilterButtonDisplay (filterOption);

		var parameters = "uiAction=GetFeedResult&profileActivityPageOffset=0&profileActivityPageSize=15&page=UserProfile";
		
		if (typeof filterOption != "undefined") {			
			parameters += "&profileActivityViewFilter=" + filterOption;
		}
	
		ui.request ({ 
			baseURL: $.hosts.commServices + '?',
			parameters:  parameters,
			callback: {name: "cbf", value: "$.global.activityFeedDisplay.refreshActivityFeedCallBack"}
	
		});
	}
	
	function updateFilterButtonDisplay (filterOption) {
//XXXXXX
	}
	
	function displayActivityLoadingPlaceHolder () {
		
		$("#activityFeedWidget .contentFeedWrapper").addClass("loadingWhiteOut");
		$("#activityFeedWidget .activityLoadingImage").show();
	}
	
	
	self.refreshActivityFeedCallBack = function (response) {
		if(! isPopUpError (response, "", "Error Displaying Activities")) {
			$("#activityFeedWidget").replaceWith (response.output);
			if(jQuery.browser.msie) {
				$("#activityFeedWidget .activeAvatarContainer").pngFix();
			}
			
			if($("#activityFeedWidget .buildCommunity").exists()) {
				$("#activityFeedWidget .buildCommunity").click (function(e) {									 
					e.preventDefault(e);
					$.global.buildCommunityPopup.open(e);
				});
			}

		}
		
		self.applyPrivacyMessage();		
		self.applyFilterAndPaginationListeners();		

	}
	
	init();

}