/**
/*	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
		_sort: "RecentlyAdded",
		
		_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", "");
			}
		},
		
		getFeed: function(target, 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;
			}
			
			// add feed elements to the list
			follow._addFollowFeedElement( target, type, pagination, size );
			
			var followList = $.followManager.getContentUserIsFollowing({
				successCallback: successfulFeed,
				failureCallback: feedError,
				page: follow._currentPage,
				pageSize: size,
				sort: follow._sort,
				envUrl: follow._feedURL
			});
			
			function successfulFeed(data){
				
				// [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']);
				}
			
				follow.makeFollowFeed(data, target, type, pagination);
			}
			
			function feedError(){
				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++ ){
			
				follow.getFeed(follow._followFeedElements[i][0], follow._followFeedElements[i][1], follow._followFeedElements[i][2], follow._followFeedElements[i][3]);
				
			}
		},
		
		startFollowing: function(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: errorFollow,
				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();
				
				//console.log(data);
			}
			
			function errorFollow(){
				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;
			}
		},
		
		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['@totalItems'] > 0 ){
				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();
			} 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]['mgid'];
					  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="/assets/dailies/sharethis_logo.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['mgid'];
					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="/assets/dailies/sharethis_logo.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]['mgid'];
						
						
						// 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['mgid'];
					
					// 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.jhtml" 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){ // Optional Arguements { 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;
			}
			
			var following = $.followManager.isFollowing({
				mgid: mgid,
				envUrl: follow._feedURL,
				successCallback: successFollow,
				failureCallback: notFollowing
			});
			
			
			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;
					
					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
						});
						
					});
				}
			}
			
			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();
				});
			}
		},
		
		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(){
			
			/* 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;
			
			
			if ( $(".sif-pagination ul").size() > 0 ){
				
				// 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
			});
			
			
			// attach page functionality
			$(".prev-page").unbind().click( function(){
				if ( !$(this).hasClass("selected") ){
					// goto previous page
					var prev = follow._currentPage - 1;
					follow.paginationUpdate($(this), prev);
				}
			});
			

			$(".next-page").unbind().click( function(){
				if ( !$(this).hasClass("selected") ){
					// goto next page
					var next = follow._currentPage + 1;
					follow.paginationUpdate($(this), next);
				}
			});

			$(".link").unbind().click( function(){
				var page = parseInt($(this).children().html());
				follow.paginationUpdate($(this), page);
			});
			
		},
		
		paginationUpdate: function(selected, index){
			
			// 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 - (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;
				
				follow.getFeed("#sif-content-item-container", "full", false, follow._pageSize);
				
			} 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;
				
				follow.getFeed("#sif-content-item-container", "full", false, follow._pageSize);
				
			} 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") ){
					$(".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");
					});
					
					// remove selected from end if it is selected
					if ( $(".sif-pagination .end").hasClass("selected") ){
						$(".sif-pagination .end").removeClass("selected").addClass("link");
					}
				} else {
					// increase all number to match end of list selection
					
					$(".page-slide li span").each( function(){
						$(this).html(x);
						x++;
						x = x == selectedIndex ? y : x;
					});
					
					$(".page-slide").each( function(){
						// make all page-slide pages links and remove selected class
						$(this).find("li").addClass("link").removeClass("selected");
					});
					
					$(".sif-pagination .end").addClass("selected").removeClass("link");
				}
				
				if ( selectedIndex == pageMax && $(".sif-pagination .end").hasClass("selected") ){
					// 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");
					});
				}
				
				// 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;
				
				follow.getFeed("#sif-content-item-container", "full", false, follow._pageSize);
			}
			
		},
		
		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);
					}
					
				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 "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;
			}
			
		}

	};





