/**
/*	Follow Feed Object
/*	Version 1.0 (10/27/2009)
/*
/*	Author: Brennan Strum (brennan.strum@mtvnmix.com)
/*
/*	About: 
/*			This object communicates with PC Locals /script/jquery/follow/jquery.follow.js to generate
/*			a follow feed for the user to control via /me/follow.jhtml or a module located in the right
/*			rail of www.parentsconnect.com.
*/

	var follow = {
		_currentPage: 1,																	// current page of the follow feed
		_pageCount: 0,																		// amount of pages in the feed
		_paginationFlow: 3,																	// pages to show in the follow feed pagination
		_pageSize: 10,																		// number if items to show per page
		_stopFeedActions: false,															// the follow feed request failed termiate all actions and report failure
		_followFeedElements: new Array(),													// instances of the follow feed on the page
		_loggedIn: false,																	// track if the user is logged in
		_feedURL: (typeof gocitykidsHost == 'undefined')?"http://" + window.location.hostname.replace(/(www|local|clone)/,'gocitykids'):gocitykidsHost,	// base url to call for ajax feed
		//_feedURL: "http://local.parentsconnect-d.mtvi.com:9090",
		_sort: "RecentlyAdded",
		_currentUser: "",
		
		_checkFollowFeed: function(){													// check if the $.followManager is active and the url is resolving
			if ( !$.followManager && $.followManager == undefined){
				return false;
			} else {
				return true;
			}
		},
		
		_debugMode: function(target, value){
			// detect if debugMode is enabled
			if (location.hash == "#debugMode" ){ 
				if ( jQuery.support.cssFloat ){
					// Mozilla / WebKit Browsers
					if ( window["console"] == undefined ) return;
					
					//detect what is being passed to the debug
					if ( typeof(value) == "object" ){ //object
						//console.log(target);
						//console.log(value); 
					} 
					
					
					if ( typeof(value) == "string" || typeof(value) == "number" ){ //string
						//console.log(target + value);
					} 
					
					//console.log(typeof(value));
					
				} else {
					// Trident(IE)
					//alert(value);
					
				}
			}
		},
		
		updateLogin: function(state){
			if ( state == "true" ){
				follow._loggedIn = state;
			} else {
				follow._loggedIn = state;
			}
		},
		
		sortFeed: function(target, sort, type, pagination, size){
			
			// test feed to see if it's active
			var activeFeed = follow._checkFollowFeed();
			
			// if feed is inactive stop ajax call and report error to user
			if ( activeFeed == false ){
				follow.error("feedInitError", "");
				return false;
			}
			
			// update sort type
			follow._sort = sort;
		
			var followList = $.followManager.getContentUserIsFollowing({
				successCallback: successfulFeed,
				failureCallback: feedError,
				page: follow._currentPage,
				pageSize: size,
				sort: sort, 										// RecentlyCommented, RecentlyAdded
				envUrl: follow._feedURL
			});
			
			function successfulFeed(data){
				
				// [DEBUG] -- if debug is enabled report feed response to console -- [DEBUG]
				follow._debugMode("Sort Feed: ", data);
				
				if ( data.followStatus["error"] != "" ){
					follow.error(data.followStatus["error"], "");
					return false;
				}
				
				if ( pagination ) { 
					follow._pageSize = size; 								// change page size if paginated
					follow._pageCount = parseInt(data.followStatus['totalPages']);	// update page count
					
					//follow._pageCount = Math.ceil( (data.followStatus['@totalItems'] ) / data.followStatus['@pageSize'] ); // HACK -> Feed coming with wrong page count because feed has 1 extra follow items
				}
			
				follow.makeFollowFeed(data, target, type, pagination);
			}
			
			function feedError(){
				follow.error("feedInitError", "");
			}
		},
		
		getSortedFeed: function(target, type, sort, pagination, size, whoseMgid){
			
			// update sort type
			follow._sort = sort;

			$(target).empty();

			follow.getFeed(target, type, pagination, size, whoseMgid);	
		},

		getFeed: function(target, type, pagination, size, whoseMgid){

			// test feed to see if it's active
			var activeFeed = follow._checkFollowFeed();
			
			// if feed is inactive stop ajax call and report error to user
			if ( activeFeed == false ){
				follow.error("feedInitError", "");
				return false;
			}
			
			// add feed elements to the list
			follow._addFollowFeedElement( target, type, pagination, size );
			
			// is this another user
			if ( whoseMgid != "" && whoseMgid != undefined ){
				follow._currentUser = whoseMgid;
			}
			switch(type){
				case "friend-list":
					var followList = $.followManager.getFriendsList({
						successCallback: successfulFriendFeed,
						failureCallback: feedError,
						type: "friend",
						page: follow._currentPage,
						pageSize: size,
						sort: follow._sort,
						envUrl: follow._feedURL
					});
					break;
				
				case "this-persons-friend-list":
					//console.log("whoseMgid "+whoseMgid);
					var followList = $.followManager.getFriendsListOfSomeone({
						successCallback: successfulFriendFeed,
						failureCallback: feedError,
						type: "friend",
						page: follow._currentPage,
						mgid: whoseMgid,
						pageSize: size,
						sort: follow._sort,
						envUrl: follow._feedURL
					});
					break;
					
				case "friend-request-list":
					var followList = $.followManager.getPendingFriendsList({
						successCallback: successfulFriendRequestFeed,
						failureCallback: friendRequestFeedError,
						type: "friend_request",
						page: follow._currentPage,
						pageSize: size,
						sort: follow._sort,
						envUrl: follow._feedURL
					});
					break;
					
				default:
					var followList = $.followManager.getContentUserIsFollowing({
						successCallback: successfulFeed,
						failureCallback: feedError,
						page: follow._currentPage,
						pageSize: size,
						sort: follow._sort,
						envUrl: follow._feedURL
					});
					break;
			}
			
			
			function friendRequestFeedError(data) {
				//alert("it's broken");	
			}
			
			function getParameterByName( name )
			{
			  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
			  var regexS = "[\\?&]"+name+"=([^&#]*)";
			  var regex = new RegExp( regexS );
			  var results = regex.exec( window.location.href );
			  if( results == null )
			    return "";
			  else
			    return results[1];
			}


			function successfulFriendRequestFeed(data){
				//console.log("successfulFriendRequestFeed");
				if(target == "#friend-request-list"){
					$(target).empty();
				}	
				if ( data.followStatus["error"] != "" ){
					follow.error(data.followStatus["error"], "");
					return false;
				}
				
				$("#friend-link").click(function(event) {
				  if(data.followStatus.totalItems==0) {
					$("#friend-link").attr("href", "/me/index.jhtml#friends-tab");
					$("#friends-tab").addClass("active");
					$("#activity-tab").removeClass("active");
					$("#bio-tab").removeClass("active");
					$("#board-tab").removeClass("active");
					$("#friends-tab").click();
				  }
				});
				
				if (data.followStatus.totalItems>0)
					{
					if(target=="#friend-link")
						{
							var meButtonCopy = (data.followStatus.totalItems==1) ? "1 Friend Request" : data.followStatus.totalItems+" Friend Requests";
							$(target).html(meButtonCopy);
						} else {
							$("#total-friend-requests").html("total requests: "+data.followStatus.totalItems);
							//console.log("totalItems is "+data.followStatus.totalItems);
							if(data.followStatus.totalItems==1)
								{
								//console.log("items.targetUserName is "+data.followStatus.items.targetUserName);
								
								var friendName = data.followStatus.items.targetUserName;
								var friendAvatarPath = data.followStatus.items.targetUserAvatarPath;
								var mutualFriendCount = data.followStatus.items.mutualFriendCount;
								var targetMgid = data.followStatus.items.targetMgid;
								var personalMessage = data.followStatus.items.requestMessage;
								var friendItemBlock1 = makeFriendRequestHTMLBlock(friendName,friendAvatarPath);
								
								var mutualFriendsBlock ="";
								if(mutualFriendCount>0)
									{
									var mutualFriendCountCopy =(mutualFriendCount==1)? "1 mutual friend" : mutualFriendCount+" mutual friends" 
									friendItemBlock1 += '<div class="mutual-friends-housing"> <a href="#!" onclick="revealMutualFriendsOf(\''+friendName+'\', this)" id="friends-of-'+friendName+'" class="mutual-friend-toggle closedUp">'+
													mutualFriendCountCopy+ '</a> <div id="friends-of-'+friendName+'-list" class="friend-list-default clearfix"> ';
									if(mutualFriendCount==1)
										{
											var mutualFriend = data.followStatus.items.mutualFriends.entry.key;											var mutualFriendAvatarPath = data.followStatus.items.mutualFriends.entry.value;
											mutualFriendsBlock = makeMutualFriendHTMLBlock(mutualFriend,mutualFriendAvatarPath)
											
										} else {
											for(j=0; j<data.followStatus.items.mutualFriends.entry.length; j++)
												{
												var mutualFriend = data.followStatus.items.mutualFriends.entry[j].key;
												var mutualFriendAvatarPath = data.followStatus.items.mutualFriends.entry[j].value;
												mutualFriendsBlock += makeMutualFriendHTMLBlock(mutualFriend,mutualFriendAvatarPath)
												}
										}
										mutualFriendsBlock +=' <br clear="all" /> </div> </div> ';
									}
								
								var friendItemBlockMsg = makeOptionalFriendRequestPersonalMessageHTMLBlock(targetMgid, personalMessage);
								var friendItemBlock2 = makeFriendRequestHTMLBlock2(targetMgid);
								var friendItem=friendItemBlock1+mutualFriendsBlock+friendItemBlockMsg+friendItemBlock2;
								
								$(target).append(friendItem);
								} else {
								
								for(i = 0; i < data.followStatus.items.length; i++)
									{
										var friendName = data.followStatus.items[i].targetUserName;
										var friendAvatarPath = data.followStatus.items[i].targetUserAvatarPath;
										var mutualFriendCount = data.followStatus.items[i].mutualFriendCount;
										var targetMgid = data.followStatus.items[i].targetMgid;
										var personalMessage = data.followStatus.items[i].requestMessage;
										var friendItemBlock1 = makeFriendRequestHTMLBlock(friendName,friendAvatarPath);
										
										var mutualFriendsBlock ="";
										if(mutualFriendCount>0)
											{
											var mutualFriendCountCopy =(mutualFriendCount==1)? "1 mutual friend" : mutualFriendCount+" mutual friends" 
											friendItemBlock1 += '<div class="mutual-friends-housing"> <a href="#!" onclick="revealMutualFriendsOf(\''+friendName+'\', this)" id="friends-of-'+friendName+'" class="mutual-friend-toggle closedUp">'+
											mutualFriendCountCopy+ '</a> <div id="friends-of-'+friendName+'-list" class="friend-list-default clearfix"> ';
											if(mutualFriendCount==1)
												{
													var mutualFriend = data.followStatus.items[i].mutualFriends.entry.key;
													var mutualFriendAvatarPath = data.followStatus.items[i].mutualFriends.entry.value;
													mutualFriendsBlock = makeMutualFriendHTMLBlock(mutualFriend,mutualFriendAvatarPath)
													
												} else {
													for(j=0; j<data.followStatus.items[i].mutualFriends.entry.length; j++)
														{
														var mutualFriend = data.followStatus.items[i].mutualFriends.entry[j].key;
														var mutualFriendAvatarPath = data.followStatus.items[i].mutualFriends.entry[j].value;
														mutualFriendsBlock += makeMutualFriendHTMLBlock(mutualFriend,mutualFriendAvatarPath)
														}
												}
												mutualFriendsBlock +=' <br clear="all" /> </div> </div> ';
											}
											
										var friendItemBlockMsg = makeOptionalFriendRequestPersonalMessageHTMLBlock(targetMgid, personalMessage);
										var friendItemBlock2 = makeFriendRequestHTMLBlock2(targetMgid);
										var friendItem=friendItemBlock1+mutualFriendsBlock+friendItemBlockMsg+friendItemBlock2;
										$(target).append(friendItem);
									
									}// END for(i = 0; i < data.followStatus.items.length; i++){

								}//END if(data.followStatus.totalItems==1)
								
								var userNameAnchor = getParameterByName('focus');
								if (userNameAnchor) {
									userNameAnchor = '#anchor-username-'+ userNameAnchor;
									$(document).ready(function() {
										window.location.href = userNameAnchor;

									});
								}
								
								var friendItemBlockMsg = makeOptionalFriendRequestPersonalMessageHTMLBlock(targetMgid, personalMessage);
								var friendItemBlock2 = makeFriendRequestHTMLBlock2(targetMgid);
								var friendItem=friendItemBlock1+mutualFriendsBlock+friendItemBlockMsg+friendItemBlock2;
							//BIND buttons
							$(".sure-thing-button").click( function(){
								follow.startFriending(id, '',true);
								//console.log($(this).attr("id"));										
								var id = $(this).attr("id");
								$.followManager.startFriending({
									type: 'friend',
									mgid: id,
									envUrl: follow._feedURL,
									successCallback: successfulFriendRequestAccept,
									failureCallback: friendRequestFeedError
								});
							});

							function successfulFriendRequestAccept(data){
								var lastFriendAdded = data.followStatus.lastFriendAdded;
								//window.location = "/me/friend-requests.jhtml?lastAdded=" + lastFriendAdded;
								//friend-requests-newly-added-friend-ajax.jhtml
								$.get("/templates/profile/friend-requests-newly-added-friend-ajax.jhtml", { lastAdded: lastFriendAdded },
								  function(data){
									$("#newly-added-friends").html(data+$("#newly-added-friends").html());
									$("#username-"+lastFriendAdded).css("display","none");
								  	$("#newly-added-friends").css("display","");
								  });							
							
							}

							$(".no-thanks-button").click( function(){
								var id = $(this).attr("id");
								$.followManager.stopFriending({
									type: 'friend_request',
									mgid: id,
									envUrl: follow._feedURL,
									successCallback: successfulFriendRequestReject,
									failureCallback: friendRequestFeedError
								});
							});

							function successfulFriendRequestReject(data){
								window.location = "/me/friend-requests.jhtml";
							}
							
						}// END if(target=="#friend-link"){
					}//END if(data.followStatus.totalItems>0)
			}
				
			function makeFriendRequestHTMLBlock(friendName,friendAvatarPath)
				{
				var friendRequestBlock ='<a name="anchor-username-'+friendName+'" id="anchor-username-'+friendName+'" href="#"></a><div class="each-friend-request clearfix" id="username-'+friendName+'"> <div class="avatar-housing clearfix"> <div class="avatar-image-housing"> <a href="/me/index.jhtml?username='+friendName+'" rel="nofollow"> <div class="circle-cut-out"></div> '+
				'<img title="'+friendName+'" src="http://www.parentsconnect.com/'+friendAvatarPath+'" alt="'+friendName+'" align="center" border="0" height="56" width="56"> </a> </div> <div class="avatar-actions clearfix"> '+
				'<a title="Send a note" href="/me/messaging/compose.jhtml?to='+friendName+'" onclick="avatarActionRequest(\''+friendName+'\',\'note\',this,false,\'\');return false;" class="note">Send a Note</a> '+
				'<a title="Send a gift" href="/me/pick-gift-category.jhtml?to='+friendName+'" onclick="avatarActionRequest(\''+friendName+'\',\'gift\',this,false,\'\');return false;" class="gift">Send a Gift</a> '+
				'<a title="Write on Board" href="/me/index.jhtml?username='+friendName+'#theComment" onclick="avatarActionRequest(\''+friendName+'\',\'board\',this,false,\'\');return false;" class="board">Write on Board</a> </div> </div> '+
				'<div class="info"> <div class="wants-to-be"><a href="/me/index.jhtml?username='+friendName+'" class="username">'+friendName+'</a> wants to be your friend</div> ';
				return friendRequestBlock;
				}
				
			function makeMutualFriendHTMLBlock(mutualFriend,mutualFriendAvatarPath)
				{
				var mutualFriendBlock = '<div class="each-mutual-friend clearfix"><div class="avatarBorder60"><div class="avatarFrame60">'+
										 '<a href="/me/index.jhtml?username='+mutualFriend+'" rel="nofollow">'+
										 '<img width="39" height="39" title="'+mutualFriend+'" src="http://www.parentsconnect.com/'+mutualFriendAvatarPath+'" alt="picture of '+mutualFriend+'" align="center" border="0"/>'+
										 '</a></div></div><a href="/me/index.jhtml?username='+mutualFriend+'" class="username">'+mutualFriend+'</a></div>';
				return mutualFriendBlock;
				}
				
			function makeOptionalFriendRequestPersonalMessageHTMLBlock(mutualFriend,requestMessage) {
				if (requestMessage) {
					return '<div class="request-message">&ldquo;' + requestMessage + '&rdquo;</div>';
				} else {
					return '';
				}
			}

			function makeFriendRequestHTMLBlock2(friendMgid)
				{
				var friendRequestBlock2 ='<a href="#!" class="decision-button no-thanks-button" id="'+friendMgid+'" title="no thanks">no thanks</a> <a href="#!" class="decision-button sure-thing-button" '+
				'id="'+friendMgid+'" title="sure thing">sure thing</a> </div> </div>';	
				return friendRequestBlock2;
				}
			

			function successfulFriendFeed(data){
				var totalFriends = 0;
				
				
				// Clean Container
				$(target).empty();
				
				
				if ( data.followStatus["error"] != "" ){
					follow.error(data.followStatus["error"], "");
					return false;
				}
				if (data.followStatus.totalItems==0) { 
					$(".friend-count").html("0 friends"); 
					if (type == 'friend-list') {
						$(target).append("What? You don't have any friends?! Go on out there and add a few to your list! These people would be LUCKY to know an awesome person like YOU!<br/><br/>"); 
					} else if (type == 'this-persons-friend-list') {
						$(target).append("This awesome member doesn't have any friends yet! I know, we can't believe it either! Go ahead and make this fab person your friend!<br/><br/>");
					}
					$(".right-col").hide();
				} else if (data.followStatus.totalItems>0){
					if(data.followStatus.totalItems==1){ 
						totalFriends = 1;
						$(".friend-count").html("1 friend"); 
						var friendName = data.followStatus.items.targetUserName;
						var followStatus = data.followStatus.items.targetLastStatusMessage;
						var friendMgid = data.followStatus.items.targetMgid;
						var friendAvatarPath = data.followStatus.items.targetUserAvatarPath;
						var htmlBlock = makeFriendBlock(friendName, followStatus, friendMgid, friendAvatarPath, type);
						$(target).append(htmlBlock);
							
					} else {
						// Multiple friends, this will require pagination if requested
						totalFriends = parseInt(data.followStatus.totalItems);
						$(".friend-count").html(totalFriends + " friends");
						$(target).empty();
						
						if ( data.followStatus.items.length == undefined ) {
							var friendName = data.followStatus.items.targetUserName;
							var followStatus = data.followStatus.items.targetLastStatusMessage;
							var friendMgid = data.followStatus.items.targetMgid;
							var friendAvatarPath = data.followStatus.items.targetUserAvatarPath;
							var htmlBlock = makeFriendBlock(friendName, followStatus, friendMgid, friendAvatarPath, type);
							$(target).append(htmlBlock);
						} else {
							for(i = 0; i < data.followStatus.items.length; i++){
								var friendName = data.followStatus.items[i].targetUserName;
								var followStatus = data.followStatus.items[i].targetLastStatusMessage;
								var friendMgid = data.followStatus.items[i].targetMgid;
								var friendAvatarPath = data.followStatus.items[i].targetUserAvatarPath;
								
								var htmlBlock = makeFriendBlock(friendName, followStatus, friendMgid, friendAvatarPath, type);
								$(target).append(htmlBlock);
							}
						}
						// Pagination Call
							// set some needed params so pagination knows what's up //
						
							// change page size if paginated
							follow._pageSize = size;
							
							// update page count
							follow._pageCount = parseInt(data.followStatus['totalPages'], 10);
							
							// call pagination
							if (pagination && data.followStatus['page'] < follow._pageCount ){
								follow.pagination("friend-list");
							}
						
					}
					$(".remove-friend").each(function(){
						$(this).tooltip({
							id: "follow-popup",
							contentTitle: false,
							contentSelector: ".remove-friend-confirm",
							followMouse: false,
							allowAccess: true,
							lockToElement: ".remove-friend",
							lockTo: "top",
							delay: 0,
							offsetX: -300,
							offsetY: 0,
							allowFlip: false,
							fixedPostion: 'top-right',
							openMethod: "click"
						});	
					});
					
					

					$(".remove-friend-confirm .cancel").click( function(){
						$(document).unbind();
						$("#follow-popup").hide();
					});

					$(".remove-friend-confirm .confirm").click( function(){
						$(document).unbind();
						$("#follow-popup").hide();
						//removeFriend($(this).parent().parent().children(".friend-mgid").val());
						var mgid = $(this).parent().parent().children(".friend-mgid").val();
						var removeFriendSuccess = function(){
							
						};
						$.followManager.stopFriending({
							mgid: mgid,
							envUrl: follow._feedURL,
							successCallback: removeFriendSuccess
						});
						var niceId = mgid.replace("mgid:ureg:user:parentsconnect.com:","");
						$("#friend_" + niceId).css("display","none");
						totalFriends--;
						if(totalFriends === 1){
							$(".friend-count").html("1 friend"); 
						}else{
							$(".friend-count").html(totalFriends + " friends");
						}
					});
				} else {
					$(target).html("&nbsp;");
				}
			}
			
			function makeFriendBlock(friendName, followStatus, friendMgid, friendAvatarPath, type){
				var removeFriendHtml = '';
				var status = '';
				if (type == 'friend-list') {
					removeFriendHtml =  '<a class="remove-friend">' +
					'<div class="remove-friend-confirm" style="display:none;">' +
					      '<div class="copy">Are you sure you want to remove ' +
					      '<b>'+friendName+'</b> as a friend? 	' +
					      '<b>'+friendName+'</b> won\'t be notified.</div>' +
					    '<input class="friend-mgid" value="'+friendMgid+'" type="hidden" />' +
					    '<div class="buttons" style="padding-top: 10px">' +
						'<div class="cancel no">cancel</div>' +
						'<div class="confirm yes">confirm</div>' +
					    '</div>' +
					'</div></a>';
				}
				if (followStatus) {
					status = followStatus;
				}
				var niceId = friendMgid.replace("mgid:ureg:user:parentsconnect.com:","");
				var friendItem ='<div id="friend_' + niceId + '" class="each-friend clearfix"> <div class="avatar-image-housing"> <a href="/me/index.jhtml?username='+friendName+'" rel="nofollow">'+
				' <div class="circle-cut-out" ></div> <img width="56" height="56" title="'+friendName+'" src="http://www.parentsconnect.com/'+friendAvatarPath+'" alt="picture of '+friendName+'" align="center" border="0"/>'+
				' </a> </div> <div class="info">'
				+ removeFriendHtml +
				' <div class="name-status-housing"> '+
				'<a href="/me/index.jhtml?username='+friendName+'" class="username">'+friendName+'</a> <span class="status">' + status + '</span> '+
				'</div> <div class="avatar-actions-housing"> <div class="avatar-actions clearfix"> '+
				'<a title="Send a note" href="/me/messaging/compose.jhtml?to='+friendName+'" class="note" onclick="avatarActionRequest(\''+friendName+'\',\'note\',this,false,\'\');return false;">Send a Note</a> '+
				'<a title="Send a gift" href="/me/pick-gift-category.jhtml?to='+friendName+'" class="gift" onclick="avatarActionRequest(\''+friendName+'\',\'gift\',this,false,\'\');return false;">Send a Gift</a> '+
				'<a title="Write on Board" href="/me/index.jhtml?username='+friendName+'#theComment" class="board" onclick="avatarActionRequest(\''+friendName+'\',\'board\',this,false,\'\');return false;">Write on Board</a> '+				
				'<a id="friend-button-'+friendMgid+'" title="Add as friend" href="/me/index.jhtml?username='+friendName+'" class="friend loggedIn unbound">Add as friend</a> ' +
				
				
				
				'</div> </div> </div> </div> ';
				return friendItem;
			}


			function successfulFeed(data){
/*		
if ( window["console"] != undefined ){
	console.log(":DEBUG FEED:");
	console.log(data);
	console.log(":DEBUG FEED:");
}*/
				
				// [DEBUG] -- if debug is enabled report feed response to console -- [DEBUG]
				follow._debugMode("-Get Feed- ", data);
				
				if ( data.followStatus["error"] != "" ){
					follow.error(data.followStatus["error"], "");
					return false;
				}
				
				if ( pagination ) { 
					// change page size if paginated
					follow._pageSize = size;
					
					// update page count
					follow._pageCount = parseInt(data.followStatus['totalPages']);
					
					//console.log("Get Feed: " + follow._pageCount);
				}
				
				//console.log("Got Here");

				follow.makeFollowFeed(data, target, type, pagination);
				follow.makeFriendAction();
			}
			
			function feedError(){

alert("feed errored out!");

				follow.error("feedInitError", "");
			}
		},
		
		_addFollowFeedElement: function(target, type, pagination, size){
			
			var inArray = false;
			
			// step through follow._followFeedElements to see if this element is already tracked
			
			if ( follow._followFeedElements.length > 0 ){
			
				for ( i=0; i < follow._followFeedElements.length; i++ ){
					if ( follow._followFeedElements[i][0] == target ) {
						inArray = true;
						break;
					}
				}
			}
			
			if ( inArray == false ){
				// add the new element to _followFeedElements
				follow._followFeedElements.push( [target, type, pagination, size] );
			}
			
			
			// [DEBUG] -- if debug is enabled report feed response to console -- [DEBUG]
			follow._debugMode("-Add Follow Feed Element-", follow._followFeedElements);
			
		},
		
		_updateAllFollowingFeeds: function(){
		
			// [DEBUG] -- if debug is enabled report feed response to console -- [DEBUG]
			follow._debugMode("Update Follow Feeds: ", follow._followFeedElements);
		
			for ( i=0; i < follow._followFeedElements.length; i++ ){
				
				if ( follow._followFeedElements[i][1] == 'button'){
					//update button
					//follow.followButton(follow._followFeedElements[i][0], follow._followFeedElements[i][3]);

				} else {
					follow.getFeed(follow._followFeedElements[i][0], follow._followFeedElements[i][1], follow._followFeedElements[i][2], follow._followFeedElements[i][3]);
				}
				/*console.log(
					"Target: " + follow._followFeedElements[i][0] + " " + typeof(follow._followFeedElements[i][0]) +
					" | Type: " + follow._followFeedElements[i][1] + " " + typeof(follow._followFeedElements[i][1]) +
					" | Pagination: " +  follow._followFeedElements[i][2] + " " + typeof(follow._followFeedElements[i][2]) +
					" | Size: " + follow._followFeedElements[i][3] + " " + typeof(follow._followFeedElements[i][3]) 
				);*/
				
			}
		},
		
		_updateMyFriendFeeds: function(){
		
			// [DEBUG] -- if debug is enabled report feed response to console -- [DEBUG]
			follow._debugMode("Update Follow Feeds: ", follow._followFeedElements);
			follow.getFeed("#list-of-friends", "friend-list", false, 10);
			for ( i=0; i < follow._followFeedElements.length; i++ ){
			
				follow.getFeed(follow._followFeedElements[i][0], follow._followFeedElements[i][1], follow._followFeedElements[i][2], follow._followFeedElements[i][3]);
				/*
				console.log(
					"Target: " + follow._followFeedElements[i][0] + " " + typeof(follow._followFeedElements[i][0]) +
					" | Type: " + follow._followFeedElements[i][1] + " " + typeof(follow._followFeedElements[i][1]) +
					" | Pagination: " +  follow._followFeedElements[i][2] + " " + typeof(follow._followFeedElements[i][2]) +
					" | Size: " + follow._followFeedElements[i][3] + " " + typeof(follow._followFeedElements[i][3]) 
				) */
				
			}
		},

		startFollowing: function(id, email){
			//console.log("who's running me: " + id + " | " + email );
			
			// if feed is inactive stop ajax call and report error to user
			var following = $.followManager.startFollowing({
				mgid: id,
				notify: email,
				envUrl: follow._feedURL,
				successCallback: successfulFollow,
				failureCallback: errorFollow
			});
			
			function successfulFollow(){
				// [DEBUG] -- if debug is enabled report feed response to console -- [DEBUG]
				//follow._debugMode("-Update Follow Feeds-", data);
				
				follow._updateAllFollowingFeeds();
			}
			
			function errorFollow(){
				follow.error("clickFeedError", "");
				follow._stopFeedActions = true;
			}
		},
		startFriending: function(id, msg, friendConfirmation){ //this needs to be expanded to request friendship AND confirm
			if(friendConfirmation){
			//console.log("i will confirm you");
			var following = $.followManager.startFriending({
				mgid: id,
				type:"friend",
				service: "friending",
				envUrl: follow._feedURL,
				successCallback: successfulFriendConfirmation,
				failureCallback: successfulFriendConfirmation//errorFriendConfirmation
			});
			}else{
			//console.log("i want to friend you");
			var following = $.followManager.startFriending({
				mgid: id,
				msg: msg,
				type:"friend_request",
				service: "friending",
				envUrl: follow._feedURL,
				successCallback: successfulFollow,
				failureCallback: errorFollow
			});
			}
			
			function successfulFriendConfirmation(data){
			//console.log(data.followStatus.status);
			}
			
			function successfulFollow(data){
				//console.log("startFriending.successfulFollow");
				if ( data.followStatus["followStatus"] == "false") {
					follow.error(data.followStatus["error"], "");
					return false;
				}
				
				
				$("#follow-popup .content").html('<img align="center" src="/assets/follow-ajax-loader.gif"/>');
				
				$("#follow-popup .content").html($('.on-its-way').html());
				
				$("#follow-popup .content .cancel").click( function(){
					$(document).unbind();
					$("#follow-popup").hide();
				});				
				
				
				$(".friendUnfriend").unbind().tooltip({
					id: "follow-popup",
					contentTitle: false,
					contentSelector: ".on-its-way", //where to clone content from
					followMouse: false,
					allowAccess: true,
					lockToElement: '.friendUnfriend',
					lockTo: 'top',
					delay: 0,
					openMethod: 'click'
				});
				
				$(".on-its-way .cancel").click( function(){
					$(document).unbind();
					$("#follow-popup").hide();
				});
			}
			
			function errorFollow(){
				//alert("error bro")
				follow.error("clickFeedError", "");
				follow._stopFeedActions = true;
			}
			/*
			*/
		},
		
		stopFollowing: function(id){
			var following = $.followManager.stopFollowing({
				mgid: id,
				envUrl: follow._feedURL,
				//successCallback: errorFollow,
				successCallback: stoppedFollowingUpdate,
				failureCallback: errorFollow
			});
			
			function stoppedFollowingUpdate(){
				follow._updateAllFollowingFeeds();
			}
			
			function errorFollow(){
				follow.error("clickFeedError", "");
				follow._stopFeedActions = true;
			}
		},
				
		stopFriending: function(target, type, pagination, size, targetMgid){
			//console.log("stopFriending is called with targetMgid " + targetMgid);	

			var following = $.followManager.stopFriending({
				mgid: targetMgid,
				envUrl: follow._feedURL,
				successCallback: removeFriendUpdateFeed,
				failureCallback: errorFollow
			});

			function removeFriendUpdateFeed(){
				$(target).empty();
				follow.getFeed(target, type, pagination, size);
			}

			function errorFollow(){
				follow.error("clickFeedError", "");
				follow._stopFeedActions = true;
			}	
		},
		
		stopFollowingAll: function(){
			var following = $.followManager.stopFollowingAll({
				envUrl: follow._feedURL,
				successCallback: stoppedFollowingUpdate,
				//successCallback: stoppedFollowingUpdateError,
				failureCallback: stoppedFollowingUpdateError
			});
			
			function stoppedFollowingUpdate(){
				follow._updateAllFollowingFeeds();
				$(".sif-pagination").empty();
			}
			
			function stoppedFollowingUpdateError(){
				follow.error("clickFeedError", "");
				follow._stopFeedActions = true;
			}
		},
		
		makeFollowFeed: function(followList, target, type, pagination){
			
			// clean container
			$(target).empty();
			
			//console.log(followList);
			
			// single element object
			var singleElement = "empty";
			if ( followList.followStatus.followItems){
				singleElement = (followList.followStatus.followItems['created'] != null) ? "single" : "many";
			}
			
			//var totalItems = parseInt(followList.followStatus['@totalItems']) - 1; // HACK -> This is coming in 1 greater then it should REPAIR THIS WHEN FEED IS FIXED*****************
			
			
			// add pagination if requested and there are enough pages to require one
			if ( pagination && follow._pageCount > 1 ){
				follow.pagination("content-list");
			} else if ( pagination && follow._pageCount == 1){
				$(".sif-pagination").empty();
			}
			
			// check browser
			var notIEBrowser = jQuery.support.cssFloat;
			
			
			if ( type == "full" ){
				
				
				if ( singleElement == "many" ){
				
					
					for(i = 0; i < followList.followStatus.followItems.length; i++){
					  var title = ( followList.followStatus.followItems[i]['title'] != null && followList.followStatus.followItems[i]['title'] != "" ) ? followList.followStatus.followItems[i]['title'] : "No title";
					  var lastUpdated = follow.convertDate(followList.followStatus.followItems[i]['lastUpdated']);
					  var mgID = followList.followStatus.followItems[i]['targetMgid'];
					  var email = (followList.followStatus.followItems[i]['notify'] == true) ? '<input class="emailMe" checked="checked" type="checkbox">' : '<input class="emailMe" type="checkbox">' ;
					  var url = '/services/content_redirector.jhtml?uri=' + mgID;
					  var fullUrl = location.protocol + "//" + location.host + url;
					  var shareThisDiv = ('share:' + mgID).replace(/[:.]?/g,'');
					  
					  var shareThisLink = " ";
					  
					  if ( notIEBrowser ){
						shareThisLink = '<div class="share left"><a id="' + shareThisDiv + '" href="#"><img src="/images-pclocal/parentspicks10/fb-icon-16.gif" /> Share</a></div>';
					  }
					  
					  
					  
						var followedItem = '<div class="sif-follow-item clearfix" style="display:none;">'+
												'<ul class="sif-follow-info">'+
													'<li class="sif-follow-title">'+
														'<a href="' + url + '">'+title +'</a>'+
													'</li>'+
													'<li class="sif-follow-date">'+
														'Last commented on : ' + lastUpdated +
													'</li>'+
													'<li class="sif-follow-opt">'+
														'<div class="actions-container" class="clearfix">'+
															'<div class="email-notifications" class="left">'+
																'<form>'+
																	'<div class="clearfix">'+
																		'<div class="input" class="left">'+
																			email +
																			'<input type="hidden" name="mgid" class="mgid" value="' + mgID + '"/>'+
																		'</div>'+
																		'<div class="email-me" class="left">'+
																			'email me'+
																		'</div>'+
																	'</div>'+
																'</form>'+
															'</div>'+
														shareThisLink+
														'</div>'+
													'</li>'+
												'</ul>'+
												'<ul class="sif-follow-remove">'+
													'<li class="sif-follow-x"><a class="unfollow" href="#!">'+
														'<div class="unfollowPopUp" style="display: none;">'+
															'<div class="comment">'+
																'Are you super sure you wanna stop following '+
																'&quot;'+ title +'&quot;?'+
															'</div>'+
															'<div class="buttons">'+
																'<div class="cancel">cancel</div>'+
																'<div class="confirm">confirm'+
																	'<input type="hidden" name="mgid" class="mgid" value="' + mgID + '"/>'+
																'</div>'+
															'</div>'+
														'</div>'+
													'</a></li>'+
												'</ul>'+
											'</div>';
						$(target).append(followedItem);
						
					  if ( notIEBrowser ){
						var sthis = SHARETHIS.addEntry({title: title, url: fullUrl}, {button:false,embeds:true});
					    sthis.attachButton($("#" + shareThisDiv)[0]);
					  }
					  
					}
					
				} else if ( singleElement == "single" ){
				
					
					var title = ( followList.followStatus.followItems['title'] != null && followList.followStatus.followItems['title'] != "" ) ? followList.followStatus.followItems['title'] : "No title";
					var lastUpdated = follow.convertDate(followList.followStatus.followItems['lastUpdated']);
					var mgID = followList.followStatus.followItems['targetMgid'];
					var email = (followList.followStatus.followItems['notify'] == true) ? '<input class="emailMe" checked="checked" type="checkbox">' : '<input class="emailMe" type="checkbox">' ;
					var url = '/services/content_redirector.jhtml?uri=' + mgID;
					var fullUrl = location.protocol + "//" + location.host + url;
					var shareThisDiv = ('share:' + mgID).replace(/[:.]?/g,'');
					
					var shareThisLink = " ";
					
					if ( notIEBrowser ){
						shareThisLink = '<div class="share left"><a id="' + shareThisDiv + '" href="#"><img src="/images-pclocal/parentspicks10/fb-icon-16.gif" /> Share</a></div>';
					}
					
					var followedItem = '<div class="sif-follow-item clearfix" style="display:none;">'+
											'<ul class="sif-follow-info">'+
												'<li class="sif-follow-title">'+
														'<a href="' + url + '">'+title +'</a>'+
												'</li>'+
												'<li class="sif-follow-date">'+
													'Last commented on : ' + lastUpdated +
												'</li>'+
												'<li class="sif-follow-opt">'+
													'<div class="actions-container" class="clearfix">'+
														'<div class="email-notifications" class="left">'+
															'<form>'+
																'<div class="clearfix">'+
																	'<div class="input" class="left">'+
																		email+
																		'<input type="hidden" name="mgid" class="mgid" value="' + mgID + '"/>'+
																	'</div>'+
																	'<div class="email-me" class="left">'+
																		'email me'+
																	'</div>'+
																'</div>'+
															'</form>'+
														'</div>'+
														shareThisLink+
													'</div>'+
												'</li>'+
											'</ul>'+
											'<ul class="sif-follow-remove">'+
												'<li class="sif-follow-x"><a class="unfollow" href="#!">'+
													'<div class="unfollowPopUp" style="display: none;">'+
														'<div class="comment">'+
															'Are you super sure you wanna stop following '+
															'&quot;'+ title +'&quot;?'+
														'</div>'+
														'<div class="buttons">'+
															'<div class="cancel">cancel</div>'+
															'<div class="confirm">confirm'+
																'<input type="hidden" name="mgid" class="mgid" value="' + mgID + '"/>'+
															'</div>'+
														'</div>'+
													'</div>'+
												'</a></li>'+
											'</ul>'+
										'</div>';
						
						$(target).append(followedItem);
						
					if ( notIEBrowser ){
					  var sthis = SHARETHIS.addEntry({title: title, url: fullUrl}, {button:false,embeds:true});
					  sthis.attachButton($("#" + shareThisDiv)[0]);
					}
					
				} else if ( singleElement == "empty" ){
				
					// User isn't following anything
					follow.error("emptyFollowList", "");
				}
				
			} else if ( type == "module" ){
			
				if ( singleElement == "many" ){
					
					
					for(i = 0; i < followList.followStatus.followItems.length; i++ ){
						
						var title = ( followList.followStatus.followItems[i]['title'] != null && followList.followStatus.followItems[i]['title'] != "" ) ? followList.followStatus.followItems[i]['title'] : "No title";
						var mgID = followList.followStatus.followItems[i]['targetMgid'];
						
						
						// filter title length
						var endPoint = title.indexOf(" ", 30) != -1 ? title.indexOf(" ", 30) : title.lastIndexOf(" ");
						title = title.length > 30 ? title.substring(0, endPoint) + "..." : title;
						
						var followedItem = '<div class="sif-follow-item clearfix" style="display:none;">'+
											  '<div class="sif-follow-title left"><a href="/services/content_redirector.jhtml?uri=' + mgID + '">'+ title +'</a></div>'+
												'<div class="right">'+
													'<ul class="sif-follow-remove">'+
														'<li class="sif-follow-x"><a class="unfollow" href="#!">'+
															'<div class="unfollowPopUp" style="display: none;">'+
																'<div class="comment">'+
																	'Are you super sure you wanna stop following '+
																	'&quot;'+ title +'&quot;?'+
																'</div>'+
																'<div class="buttons">'+
																	'<div class="cancel">cancle</div>'+
																	'<div class="confirm">confirm'+
																		'<input type="hidden" name="mgid" class="mgid" value="' + mgID + '"/>'+
																	'</div>'+
																'</div>'+
															'</div>'+
														'</a></li>'+
													'</ul>'+
												'</div>'+
											  '</div>'; 

						$(target).append(followedItem);
					}
					
				} else if ( singleElement == "single" ){
					
					var title = ( followList.followStatus.followItems['title'] != null && followList.followStatus.followItems['title'] != "" ) ? followList.followStatus.followItems['title'] : "No title";
					var mgID = followList.followStatus.followItems['targetMgid'];
					
					// filter title length
					var endPoint = title.indexOf(" ", 30) != -1 ? title.indexOf(" ", 30) : title.lastIndexOf(" ");
					title = title.length > 30 ? title.substring(0, endPoint) + "..." : title;
					
					var followedItem = '<div class="sif-follow-item clearfix" style="display:none;">'+
										  '<div class="sif-follow-title left"><a href="/services/content_redirector.jhtml?uri=' + mgID + '">'+ title +'</a></div>'+
											'<div class="right">'+
												'<ul class="sif-follow-remove">'+
													'<li class="sif-follow-x"><a class="unfollow" href="#!">'+
														'<div class="unfollowPopUp" style="display: none;">'+
															'<div class="comment">'+
																'Are you super sure you wanna stop following '+
																'&quot;'+ title +'&quot;?'+
															'</div>'+
															'<div class="buttons">'+
																'<div class="cancel">cancle</div>'+
																'<div class="confirm">confirm'+
																	'<input type="hidden" name="mgid" class="mgid" value="' + mgID + '"/>'+
																'</div>'+
															'</div>'+
														'</div>'+
													'</a></li>'+
												'</ul>'+
											'</div>'+
										  '</div>'; 
										  
					$(target).append(followedItem);
					
				} else if ( singleElement == "empty" ){
					// User isn't following anything
					follow.error("emptyFollowList", "");
				}
			} else {
				
				// User isn't following anything
				follow.error("emptyFollowList", "");
				
			}
			
			if ( parseInt(followList.followStatus['totalItems']) > 0 ){
				
				
				var moduleDefault = '<p>'+
										'To un-follow something click the X. To follow more stuff, get clicking!'+
									'</p>';
				
				// update module with defalut text
				if ( $("#sif-desc").size() > 0 ){ $("#sif-desc").html(moduleDefault); }
				if ( $("#manage-container").size() > 0 ){ $("#manage-container").html('<a href="/me/follow" class="more">Manage my list</a>'); }
				
				
				
				$(".sif-follow-item").fadeIn("slow"); // animate on to display
				// $(".sif-follow-item").show();
				
				$(".sif-follow-x a").tooltip({ // bind pop-up to unfollow x
					id: "follow-popup",
					contentTitle: false,
					contentSelector: ".unfollowPopUp",
					followMouse: false,
					allowAccess: true,
					lockToElement: '.sif-follow-x',
					delay: 0,
					offsetX: -310,
					offsetY: 0,
					openMethod: 'click',
					allowFlip: false,
					fixedPostion: 'top-right',
					rolloverElementClass: "unfollow-active"
				});
				
				$(".unfollowPopUp .cancel").each( function(){ // bind close funciton to each cancle option in the pop-ups
					$(this).click(function(){
						// close pop-up
						$(document).unbind();
						$("#follow-popup").hide();
						$(".sif-follow-x a").removeClass("unfollow-active");
					});
				});
				
				$(".unfollowPopUp .confirm").each( function(){
					var mgid = $(this).find(".mgid").val(); // id of the emelemt you are trying to stop following
					$(this).click(function(){
						
						// step back a page
						if ( type == "full" && singleElement == "single" && follow._currentPage > 1 ){
							follow._currentPage--;
						}
						
						// just remove selected item
						follow.stopFollowing(mgid);
						
						
						// Show ajax communication finished
						$(this).ajaxComplete( function(){
						
							if ( follow._stopFeedActions ){
								follow._stopFeedActions = false;
								
								// step back a page
								if ( type == "full" && singleElement == "single" && follow._currentPage > 1 ){
									// feed errored out return to last page
									follow._currentPage++;
								}
								
								return false;
							}
						
						
							// close pop-up
							$(document).unbind();
							$("#follow-popup").hide();
							$(".sif-follow-x a").removeClass("unfollow-active");
						});
						
					});
				});
				
				$(".email-notifications .emailMe").each( function(){
					
					var element = $(this);
				
				
					$(this).click( function(){
						
						// Show ajax communication started
						element.ajaxStart( function(){
							element.css({'opacity' : '0.25'});
							element.unbind('ajaxStart');
						});
					
						// Show ajax communication finished
						element.ajaxComplete( function(){
							element.css({'opacity' : '1'});
							element.unbind('ajaxComplete');
						});
						
						var mgid = $(this).next().val();
						
						if ( $(this).attr("checked") ){
							// start emailing
							follow.emailMe(mgid, "start", element);
							return false;
							
						} else {
							// stop emailing
							follow.emailMe(mgid, "stop", element);
							return false;
						}
					});
				});
			}
		},
		
		
		
		
		followButton: function(id, mgid, followType, followAfterInit){ // Optional Arguments { offsetX: , offsetY: , allowFlip: , fixedPostion: }
			// test feed to see if it's active
			var activeFeed = follow._checkFollowFeed();
			
			var followText = "";
			
			// default positioning values for pop-up balloon
			var settings = $.extend({
										offsetX: -50,
										offsetY: 14,
										allowFlip: false,
										fixedPostion: 'top-left',
										fontCase: '' 				// 'upper', 'lower'
									}
									,arguments[2]);
			
			
			// if feed is inactive stop ajax call and bind error pop-up to link
			if ( activeFeed == false ){
				notFollowing();
				return false;
			}
			
			if(followType!=null && followType=="friend")
			{
				//alert("is a friend")
				var following = $.followManager.getRelationship({
					mgid: mgid,
					envUrl: follow._feedURL,
					successCallback: successFriend//,
					//failureCallback: notFriend
				});
				
			} else {
//***** add buttons to the update list **************************************************************************/
// using size value to pass mgid. it's kinda hacky but works and not a conflict for buttons since they don't use a size value.
				//follow._addFollowFeedElement( id, 'button', false, mgid );

				//alert('is content');
				var following = $.followManager.isFollowing({
					mgid: mgid,
					envUrl: follow._feedURL,
					successCallback: successFollow,
					failureCallback: notFollowing
				});
			}
			//function notFriend(data){ alert("EPIC FAIL! data is:\n"+data); }
			function successFriend(data){
				if ( data.followStatus['error'] == "ERROR:Fluxuser is null" || follow._loggedIn == false ){
				
				document.location = "http://www.parentsconnect.com/home/index.jhtml";		
				
				} else { // NO ERRORS SO PROCEED...
					follow._loggedIn = true;
					
						followText = "";
						if(data.followStatus['connectionType'] == "FRIEND"){
							//alert("you are already friends");
							//JUST SAY YOU ARE FRIENDS
							$("#friend .friendUnfriend span").html("You are Friends"); 
							
							var curURL = window.location.href + "#friends-tab";
							$("#friend-link").attr("href", curURL);
							
							
							$(".friendUnfriend").click( function(){
								// show friends tab
								$("#friends-tab").addClass("active");
								$("#activity-tab").removeClass("active");
								$("#bio-tab").removeClass("active");
								$("#board-tab").removeClass("active");
								$("#friends-tab").click();
							});
							
							
						} else if (data.followStatus['connectionType'] == "OUTGOING_FRIEND_REQUEST") {
							//alert("YOU HAVE ALREADY ASKED THEM")
							//YOU HAVE ALREADY ASKED THEM
							
							// 1) CREATE TOOLTIP BALLOON WITH THE CORRECT DIV CLASS
							$(".friendUnfriend").tooltip({
								id: "follow-popup",
								contentTitle: false,
								contentSelector: ".already-asked", //where to clone content from
								followMouse: false,
								allowAccess: true,
								lockToElement: '.friendUnfriend',
								lockTo: 'top',
								delay: 0,
								offsetX: settings.offsetX,
								offsetY: settings.offsetY,
								openMethod: 'click',
								allowFlip: settings.allowFlip,
								fixedPostion: settings.fixedPostion
							});
							
							// 2) BIND CLICKS
							// CANCEL IS EASY - UNBIND AND HIDE
							$(".friendUnfriend .cancel").click( function(){
								$(document).unbind();
								$("#follow-popup").hide();
							});
							
							
							
						} else if (data.followStatus['connectionType'] == "INCOMING_FRIEND_REQUEST" || data.followStatus['connectionType'] == "NONE") {
							//THEY HAVE ASKED YOU OR YOU ARE STRANGERS - SAME POPUP EXPERIENCE/DIFFERENT RESULTS
							$(".friendUnfriend").tooltip({
								id: "follow-popup",
								contentTitle: false,
								contentSelector: ".add-friend", //where to clone content from
								followMouse: false,
								allowAccess: true,
								lockToElement: '.friendUnfriend',
								lockTo: 'top',
								delay: 0,
								offsetX: settings.offsetX,
								offsetY: settings.offsetY,
								openMethod: 'click',
								allowFlip: settings.allowFlip,
								fixedPostion: settings.fixedPostion
							});
							
							
							// 2) BIND CLICKS
								// a) CANCEL IS EASY - UNBIND AND HIDE
								$(".add-friend .cancel").click( function(){
									$(document).unbind();
									$("#follow-popup").hide();
								});
							
							
								// b) BIND CONFIRM BUTTON - 
								$(".add-friend .confirm").click( function(){
									//$(document).unbind();
									//$("#follow-popup").hide();
									
									// i) DIM SPAN COPY WHILE AJAX LOADS
									$(".followUnfollow span").ajaxStart( function(){
										$(this).css({'opacity' : '0.5'});
									});
									
									// ii) UN-DIM WHEN AJAX COMPLETES
									$(".followUnfollow span").ajaxComplete( function(){
										$(this).css({'opacity' : '1'});
									});
									
									// iii) assemble all data
									var msg = $("#follow-popup #tooltip-content textarea").val();					
									var mgid = $("#friend-mgid").val();
									
									// iv) TRIGGER CALL TO FRIEND
									follow.startFriending(mgid, msg);
									
									
								}); // END $(".unfollowPopUp .confirm").click( function(){	
							
							
							
							
						} // END if(data.followStatus['connectionType'] == "FRIEND"){
						




						
					
				} //END if ( data.followStatus['@error'] == "ERROR:Fluxuser is null" || follow._loggedIn == false ){				
			} //END successFriend(data)
			
			
			
			
			
			function successFollow(data){
				// [DEBUG] -- if debug is enabled report feed response to console -- [DEBUG]
				follow._debugMode("Follow Button: ", data);
				
			
			  if(  data.followStatus['error'] == "no_results" ){ return; } // item is unfollowable
				if ( data.followStatus['error'] == "ERROR:Fluxuser is null" || follow._loggedIn == false ){
				
					followText = "Follow";
					
					// Adjust Font Case
					if ( settings.fontCase == "upper" ){ followText = followText.toUpperCase(); } else if ( settings.fontCase == "lower" ) { followText = followText.toLowerCase(); }
				
					follow.error("loggedOut", "");
					$(".followUnfollow").each( function(){
						$(this).html("<span>" + followText + "</span>").unbind().click( function(){
							requiredLogin(this,'left');
							return false;
						});
					});
					
				} else {
					
					follow._loggedIn = true;
					
//console.log(data);

					followText = ( data.followStatus['following'] == true) ? "Unfollow" : "Follow";
					
					// Adjust Font Case
					if ( settings.fontCase == "upper" ){ followText = followText.toUpperCase(); } else if ( settings.fontCase == "lower" ) { followText = followText.toLowerCase(); }
					
					var popUp = '<span>' + followText + '</span>'+
								'<div class="unfollowPopUp" style="display: none;">'+
									'<div class="comment">'+
										'Are you sure you want to stop following this? '+
									'</div>'+
									'<div class="buttons">'+
										'<div class="cancel no">cancel</div>'+
										'<div class="confirm yes">confirm</div>'+
									'</div>'+
								'</div>'+
								'<div class="followPopUp" style="display: none;">'+
									'<div class="comment">'+
										'Do you want us to send you a happy, little email '+
										'to let you know when someone comments on this?'+
									'</div>'+
									'<div class="buttons">'+
										'<div class="cancel no">cancel</div>'+
										'<div class="confirm yes">confirm</div>'+
									'</div>'+
								'</div>';
				
					// Initialize HTML / Pop-Up
					if ( followText.toLowerCase() == "unfollow" ){
					
						$(".followUnfollow").html(popUp).addClass("unfollowing").tooltip({
							id: "follow-popup",
							contentTitle: false,
							contentSelector: ".unfollowPopUp",
							followMouse: false,
							allowAccess: true,
							lockToElement: '.followUnfollow',
							lockTo: 'top',
							delay: 0,
							offsetX: settings.offsetX,
							offsetY: settings.offsetY,
							openMethod: 'click',
							allowFlip: settings.allowFlip,
							fixedPostion: settings.fixedPostion
						});
						
					} else {
					
						$(".followUnfollow").html(popUp).tooltip({
							id: "follow-popup",
							contentTitle: false,
							contentSelector: ".followPopUp",
							followMouse: false,
							allowAccess: true,
							lockToElement: '.followPopUp',
							lockTo: 'top',
							delay: 0,
							offsetX: settings.offsetX,
							offsetY: settings.offsetY,
							openMethod: 'click',
							allowFlip: settings.allowFlip,
							fixedPostion: settings.fixedPostion
						});
						
					}
					
					// Bind Clicks
					$(".unfollowPopUp .cancel").click( function(){
						$(document).unbind();
						$("#follow-popup").hide();
					});
					
					$(".unfollowPopUp .confirm").click( function(){
						$(document).unbind();
						$("#follow-popup").hide();
						
						// Show ajax communication started
						$(".followUnfollow span").ajaxStart( function(){
							$(this).css({'opacity' : '0.5'});
						});
						
						// Show ajax communication finished
						$(".followUnfollow span").ajaxComplete( function(){
							$(this).css({'opacity' : '1'});
						});
						
						follow.stopFollowing(mgid);
						
						if ( follow._stopFeedActions ){
							follow._stopFeedActions = false;
							return false;
						}
						
						followText = "Follow";
						
						// Adjust Font Case
						if ( settings.fontCase == "upper" ){ followText = followText.toUpperCase(); } else if ( settings.fontCase == "lower" ) { followText = followText.toLowerCase(); }
						
						
						$(".followUnfollow span").html(followText).parent().removeClass("unfollowing").unbind().tooltip({
							id: "follow-popup",
							contentTitle: false,
							contentSelector: ".followPopUp",
							followMouse: false,
							allowAccess: true,
							lockToElement: '.followPopUp',
							lockTo: 'top',
							delay: 0,
							offsetX: settings.offsetX,
							offsetY: settings.offsetY,
							openMethod: 'click',
							allowFlip: settings.allowFlip,
							fixedPostion: settings.fixedPostion
						});
						
					});
					
					$(".followPopUp .cancel").click( function(){
						
						// Show ajax communication started
						$(".followUnfollow span").ajaxStart( function(){
							$(this).css({'opacity' : '0.5'});
						});
						
						// Show ajax communication finished
						$(".followUnfollow span").ajaxComplete( function(){
							$(this).css({'opacity' : '1'});
						});
						
						// make follow call
						follow.startFollowing(mgid, false);
						
						if ( follow._stopFeedActions ){
							follow._stopFeedActions = false;
							return false;
						}
						
						$(document).unbind();
						$("#follow-popup").hide();
						
						followText = "Unfollow";
						
						// Adjust Font Case
						if ( settings.fontCase == "upper" ){ followText = followText.toUpperCase(); } else if ( settings.fontCase == "lower" ) { followText = followText.toLowerCase(); }
						
						$(".followUnfollow span").html(followText).parent().addClass("unfollowing").unbind().tooltip({
							id: "follow-popup",
							contentTitle: false,
							contentSelector: ".unfollowPopUp",
							followMouse: false,
							allowAccess: true,
							lockToElement: '.followPopUp',
							lockTo: 'top',
							delay: 0,
							offsetX: settings.offsetX,
							offsetY: settings.offsetY,
							openMethod: 'click',
							allowFlip: settings.allowFlip,
							fixedPostion: settings.fixedPostion
						});
						
					});
					
					$(".followPopUp .confirm").click( function(){
						// Show ajax communication started
						$(".followUnfollow span").ajaxStart( function(){
							$(this).css({'opacity' : '0.5'});
						});
						
						// Show ajax communication finished
						$(".followUnfollow span").ajaxComplete( function(){
							$(this).css({'opacity' : '1'});
						});
						
						// make follow call
						follow.startFollowing(mgid, true);
						
						if ( follow._stopFeedActions ){
							follow._stopFeedActions = false;
							return false;
						}
						
						$(document).unbind();
						$("#follow-popup").hide();
						
						
						followText = "Unfollow";
						
						// Adjust Font Case
						if ( settings.fontCase == "upper" ){ followText = followText.toUpperCase(); } else if ( settings.fontCase == "lower" ) { followText = followText.toLowerCase(); }
						
						
						$(".followUnfollow span").html(followText).parent().addClass("unfollowing").unbind().tooltip({
							id: "follow-popup",
							contentTitle: false,
							contentSelector: ".unfollowPopUp",
							followMouse: false,
							allowAccess: true,
							lockToElement: '.followPopUp',
							lockTo: 'top',
							delay: 0,
							offsetX: settings.offsetX,
							offsetY: settings.offsetY,
							openMethod: 'click',
							allowFlip: settings.allowFlip,
							fixedPostion: settings.fixedPostion
						});
						
					});

					if (followAfterInit)
					{
						if($(id+" span:eq(0)") && ((id=="#follow1" && $("#follow02").html() == null) || (id!="#follow1")))
						{
							var isFollowItemA = $(id+" span:eq(0)").html() + '';
						    if (isFollowItemA.toLowerCase().indexOf('un')==-1){    
							$(id+" span:eq(0)").click();
						    $(".followPopUp .confirm").click();
						    }
						}
					}
				}
			}
			
			function notFollowing(){
				// Call to load button failed. Remove the button
				//$(".followUnfollow").remove();
				
				followText = "Follow";
					
				// Adjust Font Case
				if ( settings.fontCase == "upper" ){ followText = followText.toUpperCase(); } else if ( settings.fontCase == "lower" ) { followText = followText.toLowerCase(); }
				
				// ajax failed bind error pop-up
				var popUp = '<span>' + followText + '</span>'+
							'<div class="followError" style="display: none;">'+
								'<div class="close">close [x]</div>'+
								'<div class="comment">'+
									'Hi there! We&lsquo;re experiencing technical difficulties. Go and get yourself a nice '+
									'frosty beverage and then try again!'+
								'</div>'+
							'</div>';
				
				$(".followUnfollow").html(popUp).unbind().tooltip({
					id: "follow-popup",
					contentTitle: false,
					contentSelector: ".followError",
					followMouse: false,
					allowAccess: true,
					lockToElement: '.followPopUp',
					lockTo: 'top',
					delay: 0,
					offsetX: settings.offsetX,
					offsetY: settings.offsetY,
					openMethod: 'click',
					allowFlip: settings.allowFlip,
					fixedPostion: settings.fixedPostion
				});
				
				// Bind Click
				$(".followError .close").click( function(){
					$(document).unbind();
					$("#follow-popup").hide();
				});
			}
		}, //END [around line 629] followButton: function(){ 
			
		
		stopFollowingAllElement: function(ele){
			
			var popUp = '<div class="unfollowAllPopUp" style="display: none;">'+
							'<div class="comment">'+
								'Are you sure you want to stop following everything?'+
							'</div>'+
							'<div class="buttons">'+
								'<div class="cancel no">cancel</div>'+
								'<div class="confirm yes">confirm</div>'+
							'</div>'+
						'</div>';
			
			ele.append(popUp).tooltip({
				id: "follow-popup",
				contentTitle: false,
				contentSelector: ".unfollowAllPopUp",
				followMouse: false,
				allowAccess: true,
				lockToElement: '#stop-following-all',
				delay: 0,
				offsetX: -310,
				offsetY: 0,
				openMethod: 'click',
				allowFlip: false,
				fixedPostion: 'top-right'
			});
			
			$(".unfollowAllPopUp .cancel").click( function(){
				$(document).unbind();
				$("#follow-popup").hide();
			});
			
			$(".unfollowAllPopUp .confirm").click( function(){
				
				follow.stopFollowingAll();
				
				$(this).ajaxComplete( function(){
					if ( follow._stopFeedActions ){
						follow._stopFeedActions = false;
						return false;
					}
					
					$(document).unbind();
					$("#follow-popup").hide();
				});
			});
		},
		
		emailMe: function(id, process, target){
			
			if( process == "start"){ // Start Emailing
				var eamilUpdate = $.followManager.startEmailNotifications({
					mgid: id,
					envUrl: follow._feedURL,
					successCallback: startedEmailing
					//failureCallback: ,
				});	
			} else { // Stop Emailing
				var eamilUpdate = $.followManager.stopEmailNotifications ({
					mgid: id,
					envUrl: follow._feedURL,
					successCallback: stoppedEmailing
					//failureCallback: ,
				});	
			}
			
			function startedEmailing(){
				target.attr("checked", "checked");
			}
			
			function stoppedEmailing(){
				target.attr("checked", "");
			}
			
		},
		
		pagination: function(feedType){
			
			/* pagination HTML structure template
			
				<div class="sif-pagination clearfix">
					<ul>
						<li class="prev-page selected">prev</li>
						<li><font class="divider">|</font></li>
						<li class="page">Page</li>
						<li>
							<ul class="page-slide">
								<li class="first link selected"><span>1</span>,</li>
								<li class="link"><span>2</span>,</li>
								<li class="last link"><span>3</span></li>
							</ul>
							
					*** if pageMax > pageFlow add the following	***
						<li>...</li>
						<li class="end link"><span>[pageMax]</span></li>
							
						</li>
						<li><font class="divider">|</font></li>
						<li class="next-page">next</li>
					</ul>
				</div>
				
			*/
			
			// p | 5 , 6 , 7 ... 9 | n
			
			// set default pagination values
			var pageMax = follow._pageCount;
			var pageFlow = pageMax > follow._paginationFlow ? follow._paginationFlow : pageMax;
			var pageFlowStart = 1;
			var pageFlowEnd = (pageFlowStart + pageFlow) - 1;
			var curPage = follow._currentPage;
			var selIndex = 1;
			
			
			/*console.log( 
				"Page MAX: " + pageMax +
				" | Page Start: " + pageFlowStart +
				" | Page Flow: " + pageFlow +
				" | Page End: " + pageFlowEnd +
				" | Current Page: " + curPage +
				" | Selected Page:  " + selIndex +
				" | Feed Type:  " + feedType
			);*/
			
			
			if ( $(".sif-pagination ul").size() > 0 ){
				
				//console.log("== REBUILDING RULES ==");
				
				// get selected inex
				$(".page-slide").each( function(){
					var sel = $(this).find(".selected"); 		// target selected page
					selIndex = ($(this).children().index(sel) + 1);
					
					//console.log("selected index: " + selIndex);
				});
				
				if ( selIndex > 0 ){
					// update page flow start and end
					pageFlowStart = curPage - (selIndex - 1);
					pageFlowEnd = (pageFlowStart + pageFlow) - 1;
					
					//console.log("page flow start: " + pageFlowStart);
				} else {
					// selected element is the end page
					selIndex = pageMax;
					if ( (pageMax - pageFlow) > 0 ){ pageFlowStart = (pageMax - pageFlow); } else { 1; }
					if ( pageMax == pageFlow ){ pageFlowEnd = pageMax; } else { pageFlowEnd = (pageMax - 1); }
				}
				
				
			}
			
			// [DEBUG] -- if debug is enabled report feed response to console -- [DEBUG]
			follow._debugMode("Page MAX:  ", pageMax);
			follow._debugMode("Page Start:  ", pageFlowStart);
			follow._debugMode("Page Flow:  ", pageFlow);
			follow._debugMode("Page End:  ", pageFlowEnd);
			follow._debugMode("Current Page:  ", curPage);
			follow._debugMode("Selected Page:  ", selIndex);
			
			
			$(".sif-pagination").each(function(){
				
				var pages = ""; // pagination to append to container
				
				for ( i=pageFlowStart; i <= pageFlowEnd; i++ ){
				
					if ( i == pageFlowStart && i == curPage ){
					
						pages += '<ul><li class="prev-page selected"><span>Previous</span></li>'+
									'<li><font class="divider">|</font></li>'+
									'<li><ul class="page-slide"><li class="first link selected"><span>'+ i +'</span></li>';
						
					} else if ( i == pageFlowStart ){
					
						pages += '<ul><li class="prev-page"><span>Previous</span></li>'+
									'<li><font class="divider">|</font></li>'+
									'<li><ul class="page-slide"><li class="first link"><span>'+ i +'</span></li>';
					
					} else if ( i == pageFlowEnd && i == curPage ){
					
						pages += '<li class="last link selected"><span>'+ i +'</span></li></ul>';
					
					} else if ( i == pageFlowEnd ) {
						
						pages += '<li class="last link"><span>'+ i +'</span></li></ul>';
						
					} else if ( i == curPage ) {
						
						pages += '<li class="link selected"><span>'+ i +'</span></li>';
						
					} else {
						
						pages += '<li class="link"><span>'+ i +'</span></li>';
						
					}
				}
				
				// append end page or just next button
				if ( pageMax > pageFlowEnd ){
					
					if ( curPage == pageMax ){
					
						pages += '<li>...</li><li class="end link selected"><span>' + pageMax + '</span>'+
							'</li><li><font class="divider">|</font></li><li class="next-page selected"><span>Next</span></li></ul>';
					
					} else {
					
						pages += '<li>...</li><li class="end link"><span>' + pageMax + '</span>'+
							'</li><li><font class="divider">|</font></li><li class="next-page"><span>Next</span></li></ul>';
							
					}

					
				} else {
					
					if ( curPage == pageMax ){
						
						pages += '</li><li><font class="divider">|</font></li><li class="next-page selected"><span>Next</span></li></ul>';
					
					} else {
						
						pages += '</li><li><font class="divider">|</font></li><li class="next-page"><span>Next</span></li></ul>';
						
					}
					
				}
				
				$(this).html(pages); // add pages to pagination
				
				// Append devider on depending on where it's positioned
				if ( $(this).hasClass("content-separator-top") ){
					
					$(this).append('<div class="separator">&nbsp;</div>');
					
				} else if ( $(this).hasClass("content-separator-bottom") ){
					
					$(this).prepend('<div class="separator">&nbsp;</div>');
				}
				
			});
			
			
			// attach page functionality
			$(".prev-page").unbind().click( function(){
				if ( !$(this).hasClass("selected") ){
					// goto previous page
					var prev = follow._currentPage - 1;
					follow.paginationUpdate($(this), prev, feedType);
				}
			});
			

			$(".next-page").unbind().click( function(){
				if ( !$(this).hasClass("selected") ){
					// goto next page
					var next = follow._currentPage + 1;
					follow.paginationUpdate($(this), next, feedType);
				}
			});

			$(".link").unbind().click( function(){
				var page = parseInt($(this).children().html());
				follow.paginationUpdate($(this), page, feedType);
			});
			
		},
		
		paginationUpdate: function(selected, index, feedType){
			
			// global element values
			var pageMax = follow._pageCount;
			var selectedPage = selected;
			var selectedIndex = index;
			var nextPage = (selectedIndex + 1);
			var prevPage = (selectedIndex - 1);
			
			
			// individual pagination values
			var sl = $(".page-slide li").length;
			var slc = $(".page-slide").length;
			var y = selectedIndex - Math.round(sl / slc);
			var x = y;
			
			/*
			console.log( 
				"GLOBAL :: Current Page: " + follow._currentPage +
				" | Selected Page: " + selectedIndex +
				" | Selected Array Index: " + index + " - " + pageMax +
				" | Max Pages: " + pageMax +
				" | Next Page: " + nextPage
			);*/
			
			
			if ( (selected.hasClass("last") && index < (pageMax - 1)) || 
				(selected.hasClass("next-page") && $(".page-slide li.selected").next().hasClass("last")) && index < (pageMax - 1) 
				
				){ // This will act like next page function since it will up roll the pages

				/*console.log( 
					"NEXT :: Current Page: " + follow._currentPage +
					" | Selected Page: " + selectedIndex +
					" | Max Pages: " + pageMax +
					" | Next Page: " + nextPage
				);*/
				
				
				// adjust pagination styles
				$(".page-slide").each( function(){
					var i = selectedIndex - parseInt($(this).find("li.first").text());
					$(this).find("li").eq(i).prev().addClass("selected").removeClass("link").siblings().addClass("link").removeClass("selected");
				});
				
				// increase numbers
				$(".page-slide li span").each( function(){
					$(this).text(parseInt($(this).text()) + 1);
				});
				
				// remove selected from end if it is selected
				if ( $(".sif-pagination .end").hasClass("selected") ){
					$(".sif-pagination .end").removeClass("selected").addClass("link");
				}
				
				// keep track of the next and prev buttons and when limits are hit turn them off
				selectedIndex > 1 ? $(".sif-pagination .prev-page").removeClass("selected") : $(".sif-pagination .prev-page").addClass("selected");
				selectedIndex < pageMax ? $(".sif-pagination .next-page").removeClass("selected") : $(".sif-pagination .next-page").addClass("selected");
				
				// update selected page to current page
				follow._currentPage = index;
				
				// select feed type to update
				switch(feedType){
				
					case "content-list":
						follow.getFeed("#sif-content-item-container", "full", false, follow._pageSize);
						break;
				
					case "friend-list":
						//console.log("Friend Page Click");
						if ( follow._currentUser != undefined && follow._currentUser != "" ){ 
							//console.log(follow._currentUser);
							follow.getFeed("#list-of-friends", "this-persons-friend-list", false, follow._pageSize, follow._currentUser);
						}else {
							follow.getFeed("#list-of-friends", "friend-list", false, follow._pageSize);
						}
						break;
					
				}
				
				
				
			} else if ( selected.hasClass("first") && index > 1  || 
				(selected.hasClass("prev-page") && $(".page-slide li.selected").prev().hasClass("first")) && index > 1 ){ // This will act like previous page function since it will down roll the pages

				/*console.log( 
					"PREV ::  Current Page: " + follow._currentPage +
					" | Selected Page: " + selectedIndex +
					" | Max Pages: " + pageMax +
					" | Next Page: " + nextPage
				);*/
				
				// adjust pagination styles
				$(".page-slide").each( function(){
					var i = selectedIndex - parseInt($(this).find("li.first").text());
				
					$(this).find("li").eq(i).next().addClass("selected").removeClass("link").siblings().addClass("link").removeClass("selected");
				});
				
				// decrease numbers
				$(".page-slide li span").each( function(){
					$(this).text(parseInt($(this).text()) - 1);
				});
				
				// remove selected from end if it is selected
				if ( $(".sif-pagination .end").hasClass("selected") ){
					$(".sif-pagination .end").removeClass("selected").addClass("link");
				}
				
				// keep track of the next and prev buttons and when limits are hit turn them off
				selectedIndex > 1 ? $(".sif-pagination .prev-page").removeClass("selected") : $(".sif-pagination .prev-page").addClass("selected");
				selectedIndex < pageMax ? $(".sif-pagination .next-page").removeClass("selected") : $(".sif-pagination .next-page").addClass("selected");
				
				// update selected page to current page
				follow._currentPage = index;
				
				
				// select feed type to update
				switch(feedType){
				
					case "content-list":
						follow.getFeed("#sif-content-item-container", "full", false, follow._pageSize);
						break;
				
					case "friend-list":
						//console.log("Friend Page Click");
						if ( follow._currentUser != undefined && follow._currentUser != "" ){ 
							//console.log(follow._currentUser);
							follow.getFeed("#list-of-friends", "this-persons-friend-list", false, follow._pageSize, follow._currentUser);
						}else {
							follow.getFeed("#list-of-friends", "friend-list", false, follow._pageSize);
						}
						break;
					
				}
				
			} else if ( follow._currentPage != index && index <= pageMax || selected.hasClass("end") && index == pageMax ){

				/*console.log( 
					"GOTO :: Current Page: " + follow._currentPage +
					" | Selected Page: " + selectedIndex +
					" | Pages to select from: " + ( ($(".page-slide li").length) / ($(".page-slide").length)) +
					" | Max Pages: " + pageMax +
					" | Next Page: " + nextPage
				);*/
				
				// adjust pagination styles
				if ( selected.hasClass("end") === false ){
					$(".page-slide").each( function(){
						var i = selectedIndex - parseInt($(this).find("li.first").text());
						
						$(this).find("li").eq(i).addClass("selected").removeClass("link").siblings().addClass("link").removeClass("selected");
					});
					
				} else {
					// increase all number to match end of list selection
					$(".page-slide").each( function(){
						
						var sliderFlow = follow._paginationFlow;
						
						$(this).find("li span").each( function() {
							
							$(this).html(selectedIndex - sliderFlow);
							sliderFlow--;
							
						});
					});
					
					$(".page-slide").each( function(){
						// make all page-slide pages links and remove selected class
						$(this).find("li").addClass("link").removeClass("selected");
					});
					
				}
				
				
				if ( selectedIndex == pageMax && $(".sif-pagination .end").hasClass("link") ){
					// next tabbing to page max
					$(".sif-pagination .end").addClass("selected").removeClass("link");
					
					// make all page-slide pages links and remove selected class
					$(".page-slide").each( function(){
						$(this).find("li").addClass("link").removeClass("selected");
					});
				} else {
					// remove selected from end if it is selected
					$(".sif-pagination .end").removeClass("selected").addClass("link");
				}
				
				// keep track of the next and prev buttons and when limits are hit turn them off
				selectedIndex > 1 ? $(".sif-pagination .prev-page").removeClass("selected") : $(".sif-pagination .prev-page").addClass("selected");
				selectedIndex < pageMax ? $(".sif-pagination .next-page").removeClass("selected") : $(".sif-pagination .next-page").addClass("selected");
				
				// update selected page to current page
				follow._currentPage = index;
				
				/*
				console.log( 
					"GOTO :: Current Page: " + follow._currentPage +
					" | Selected Page: " + selectedIndex +
					" | Pages to select from: " + ( ($(".page-slide li").length) / ($(".page-slide").length)) +
					" | Max Pages: " + pageMax +
					" | Next Page: " + nextPage
				);*/
				
				
				// select feed type to update
				switch(feedType){
				
					case "content-list":
						follow.getFeed("#sif-content-item-container", "full", false, follow._pageSize);
						break;
				
					case "friend-list":
						//console.log("Friend Page Click");
						if ( follow._currentUser != undefined && follow._currentUser != "" ){ 
							//console.log(follow._currentUser);
							follow.getFeed("#list-of-friends", "this-persons-friend-list", false, follow._pageSize, follow._currentUser);
						}else {
							follow.getFeed("#list-of-friends", "friend-list", false, follow._pageSize);
						}
						break;
					
				}
			}
			
		},
		
		convertDate: function(d){
			var m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
			var p = d.split("-");
			return (m[(parseInt( p[1], 10 )-1)] + " " + parseInt( p[2], 10 ) + " " + parseInt( p[0], 10 ) );
		},
		
		error: function(msg, element){

			var followManagerDefault = 	'<p class="intro">You&lsquo;re not following anything right now.</p>'+
										'<p class="direction">Click around the site to find things you like...and then follow them!</p>';
			
			var moduleDefault = '<p>'+
									'To un-follow something click the X. To follow more stuff, get clicking! '+
								'</p>';
								
			var moduleEmpty = '<p>Every time you write on a board, comment on an article, or add something to the site, it goes here.</p>'+
								'<ul>'+
									'<li><img src="/assets/me/follow/arrow-magenta-lg.gif"> To un-follow something click on the X.</li>'+
									'<li><img src="/assets/me/follow/arrow-magenta-lg.gif"> If you want email updates on the stuff you&lsquo;re '+
									'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;following, check "email me!"</li>'+
									'<li><img src="/assets/me/follow/arrow-magenta-lg.gif"> To stop the emails, uncheck the box. </li>'+
								'</ul>'+
								'<p>So what are you waiting for? Get Following! </p>';
			
			var FeedError = '<p>'+
								'Hi there! We&lsquo;re experiencing technical difficulties. Go and get yourself a nice '+
								'frosty beverage and then try again!'+
							'</p>';
			
			switch(msg){
				case "clickFeedError":
					
					// ajax failed bind error pop-up
					var popUp = '<div class="close">close [x]</div>'+
									'<div class="comment">'+
										'Hi there! We&lsquo;re experiencing technical difficulties. Go and get yourself a nice '+
										'frosty beverage and then try again!'+
									'</div>'+
								'</div>';
					
					$("#follow-popup .content").html(popUp);
					
					// Bind Click
					$("#follow-popup .close").click( function(){
						$(document).unbind();
						$("#follow-popup").hide();
						
						if ( $(".sif-follow-x a").size() > 0 ){
							$(".sif-follow-x a").removeClass("unfollow-active");
						}
						
					});
					
				break;
				
				case "feedInitError":
				
					// feed initialize error
					if ( $("#sif-content-module-container").size() > 0 ){
						$("#sif-content-module-container").empty();
						$("#sif-desc").html(FeedError);
					}
					
					if ( $("#sif-content-item-container").size() > 0 ){
						$("#sif-content-item-container").empty();
						$("#sif-content-item-container").html(FeedError);
					}
					
					if ( $("#friends-tab-content").size() > 0 ){
						$("#friends-tab-content").empty();
						$("#friends-tab-content").html(FeedError);
					}
					
				break;
				
				
				case "loggedOut":
					// Update Module with Defalut Text
					if ( $("#sif-content-module-container").size() > 0 ){
						$("#sif-content-module-container").empty();
						$("#sif-desc").html(moduleEmpty);
					}
					
				break;
				case "ERROR:":
					// Update Module with Defalut Text
					if ( $("#sif-content-module-container").size() > 0 ){
						$("#sif-content-module-container").empty();
						$("#sif-desc").html(moduleEmpty);
					}
					
				break;
				
				case "emptyFollowList":
					// update manage follow list with defalut text
					if ( $("#sif-content-item-container").size() > 0 ){
						$("#sif-content-item-container").html(followManagerDefault);
					}
					
					
					// update module with defalut text
					if ( $("#sif-content-module-container").size() > 0 ){
						$("#sif-content-module-container").empty();
						$("#sif-desc").html(followManagerDefault);
						if ( $("#manage-container").size() > 0 ){ $("#manage-container").empty(); }
					}
					
				break;
			}
			
		},

		makeFriendAction: function(){
			// test feed to see if it's active
			var activeFeed = follow._checkFollowFeed();
			
			var settings = $.extend({
							offsetX: -310,
							offsetY: 14,
							allowFlip: false,
							fixedPostion: 'top-right'
						}
						,arguments[0]);
			
			var mostRecentlyFriendedMGID = "";
			var addFriendPopup = $("#addFriendPopup");
			var addFriendPopupContent = $("#addFriendPopupContent");			

			// if feed is inactive stop ajax call and report error to user
			if ( activeFeed == false ){
				
				// ajax failed bind error pop-up
				var popUp = '<div class="friendError" style="display: none;">'+
								'<div class="close">close [x]</div>'+
								'<div class="comment">'+
									'Hi there! We&lsquo;re experiencing technical difficulties. Go and get yourself a nice '+
									'frosty beverage and then try again!'+
								'</div>'+
							'</div>';
				
				$(".avatar-actions .friend").append(popUp);
				
				$(".avatar-actions .friend").bind("click",function(event){
					event.preventDefault();
				});
				
				$(".avatar-actions .friend").tooltip({
					id: "follow-popup",
					contentTitle: false,
					contentSelector: ".friendError",
					followMouse: false,
					allowAccess: true,
					lockToElement: '.followPopUp',
					lockTo: 'top',
					delay: 0,
					offsetX: settings.offsetX,
					offsetY: settings.offsetY,
					openMethod: 'click',
					allowFlip: settings.allowFlip,
					fixedPostion: settings.fixedPostion
				});
				
				// Bind Click
				$(".friendError .close").click( function(){
					$(document).unbind();
					$("#follow-popup").hide();
				});
				
				
				return false;
			}

			zIndex = 2;
			$(".avatar-actions a.friend.loggedIn.unbound, .avatar-actions span.friend.loggedIn.unbound").each(function(){
				$(this).removeClass("unbound");
			}).bind("click",function(event){
				event.preventDefault();
				$("#addFriendPopup").css("display","none");
				zIndex += 1;
				$(this).parent().css("zIndex",zIndex);//stacking contexts
				addFriendPopup.appendTo($(this).parent());
				mostRecentlyFriendedMGID = $(this).attr("id").replace("friend-button-","");
				$("#hovering-avatar-action").css("display","none");

				$.followManager.getRelationship({
					envUrl: follow._feedURL,
					mgid: mostRecentlyFriendedMGID,
					successCallback: getRelationshipSuccessHandler,
					failureCallback: function(){ alert('feed failed');}
				});
			});

			$("#addFriendPopupCloseButton").bind("click",function(event){
				$("#addFriendPopup").css("display","none");
			});
			
			
			var startFriendingSuccessHandler = function(data){
				if(data.followStatus.error){
					alert("There was an error processing your request.\n\n" + data.followStatus.error);
				}else{
					var username = addFriendPopup.parent().parent().parent().find("a.username").text();
					addFriendPopupContent.html("Your friend request is on its way!<br/>We'll letcha know when<br/><b>"+username+"</b> accepts it.");
					addFriendPopup.css("display","block");
				}
			}
			var acceptFriendingSuccessHandler = function(data){
				if(data.followStatus.error){
					alert("There was an error processing your request.\n\n" + data.followStatus.error);
				}else{
					addFriendPopupContent.html("Great minds think alike!  This<br/>person sent you a friend request<br/>too! Since you both like each other<br/>- you're now officially friends!");
					addFriendPopup.css("display","block");
				}
			}
			var getRelationshipSuccessHandler = function(data){

				if(data && data.followStatus){
		  			if(data.followStatus.error){
		  				alert("There was an error processing your request.\n\n" + data.followStatus.error);
		  			}else{
		  				var friendSpan = addFriendPopup.parent().find("span.friend.loggedIn");
						var currentMGID;						
						if (friendSpan){
							currentMGID = friendSpan.attr("id").replace("friend-button-","");
						} else {
							currentMGID = addFriendPopup.parent().find("a.friend.loggedIn").attr("id").replace("friend-button-","");
						}
		  				if(currentMGID === mostRecentlyFriendedMGID){
				  			if(data.followStatus.connectionType === "NONE"){
				  				var username = addFriendPopup.parent().parent().parent().find("a.username").text();
				  				addFriendPopupContent.html(username + " has to confirm you as a friend. Okie Doke!?<br/><br/>" +
				  					"Why not write a little personal message? (It's optional!)" +
			  						"<div id='buttonsHolder'>" +
			  							"<div><textarea id='requestMessage'></textarea></div>" + 
				  						"<div id='confirmButton'>send</div>" +
					  				"</div>"
			  					);
								addFriendPopup.css("display","block");
								$("#addFriendPopup #confirmButton").bind("click",function(event){
									var msg = $("#addFriendPopup #buttonsHolder #requestMessage").val();
									$.followManager.startFriending({
					  					mgid: currentMGID,
					  					msg: msg,
					  					type:"friend_request",
					  					service: "friending",
					  					envUrl: follow._feedURL,
					  					successCallback: startFriendingSuccessHandler
					  				});
									event.preventDefault();
								});
				  			}else if(data.followStatus.connectionType === "OUTGOING_FRIEND_REQUEST"){
				  				addFriendPopupContent.html("You already sent this awesome<br/> person a friend request!");
				  				addFriendPopup.css("display","block");
				  			}else if(data.followStatus.connectionType === "INCOMING_FRIEND_REQUEST"){
			  					$.followManager.startFriending({
				  					mgid: currentMGID,
				  					type:"friend",
				  					service: "friending",
				  					envUrl: follow._feedURL,
				  					successCallback: acceptFriendingSuccessHandler
				  				});
				  			}else if(data.followStatus.connectionType === "FRIEND"){
				  				addFriendPopupContent.text("Hey!  We're already friends!");
				  				addFriendPopup.css("display","block");
				  			}
			  			}
		  			}
		  		}
			};
		}
	};






