


var ActiveNetwork = window.ActiveNetwork || {};

(function() {

ActiveNetwork.FacebookConnect = function(activeProperty, serviceUrl, integrateWithAus, casSession) {
	this.initialize(activeProperty, serviceUrl, integrateWithAus, casSession);
};

ActiveNetwork.FacebookConnectModal = function() {};

ActiveNetwork.CookieManager = function() {};

ActiveNetwork.FacebookConnectDisplay = function(facebookConnect) {
	this.initialize(facebookConnect);
};

(function() {
	
	ActiveNetwork.FacebookConnect.prototype = (function() {
		
		return {
			
			activeProperty: null,
			serviceUrl: null,
			integrateWithAus: true,
			casSession: null,
			user: null,
			pairedAusId: null,
			cookieManager: null,
			modal: null,
			facebookFriends: null,
			facebookFriendsModal: null,

			initialize: function(activeProperty, serviceUrl, integrateWithAus, casSession) {
				if ($("ihoops_fanbox") && $("ihoops_facebook_activity")) {
					if (Math.floor(Math.random()*2) == 0) {
						// activity
						$("ihoops_fanbox").style.display = "none";
						$("ihoops_facebook_activity").style.display = "block";
					}
					else {
						// friends
						$("ihoops_fanbox").style.display = "block";
						$("ihoops_facebook_activity").style.display = "none";
					}
				}
				
				this.activeProperty = activeProperty;
				this.serviceUrl = serviceUrl;
				this.integrateWithAus = integrateWithAus;
				this.casSession = casSession;
				this.cookieManager = new ActiveNetwork.CookieManager();
				this.modal = new ActiveNetwork.FacebookConnectModal();
				this.modal.render();
				this.facebookFriends = new Array();
				ActiveNetwork.FacebookConnect.instance = this;
				this.facebookFriendsModal = 
					new Control.Modal($('ihoops_facebook_friends_modal_list'),{
						fade: true,
						overlayOpacity: 0.75,
						position: 'center'
					});
			},

			getFacebookUserInfo: function() {
				var self = this;
				FB.getLoginStatus(function(response) {
					if (response.status == 'connected') {
						FB.api('/me', function(response) { 
							if (response.id == undefined) { }
							else { 
								self.user = response; // used for profile info rendering
								if (self.integrateWithAus) {
								    self.checkForAusId(response.id);
								}
							}
							// start profile info rendering
							Event.fire(document, "fb:loaded");
						});
					}
					else {
						Event.fire(document, "fb:loaded");
						if ($("ihoops_facebook_friends_list") != undefined) {
						    $("ihoops_facebook_friends_list").update("<p>Please log into your connected Facebook and iHoops accounts to see which of your friends are also members.</p>");
                        }
					}
				});
				
			},

			checkForAusId: function(id) {
				var self = this;
				new Ajax.Request(self.serviceUrl, { 
					method: "post", 
					parameters: { command: "getUser", id: id },
					onComplete: function(response) {
						if (response.status == 200) {
							var responseArray = response.responseText.evalJSON(false);
							try { self.pairedAusId = responseArray["ausId"]; }
							catch(e) { }
						}
						self.determineModalContent();
					}
				});
			},
			
			connectFbidWithAusid: function() {
				var self = this;
				var serializedData = Object.toJSON({id: self.user.id, ausId: this.casSession.loginData.UserID});
				new Ajax.Request(self.serviceUrl, { 
					method: "post", 
					parameters: { command: "connectUser", data: serializedData },
					onComplete: function(response) {
						if (response.status == 200)
							self.modal.updateContent('<p>Your ' + self.activeProperty + ' and Facebook accounts were successfully connected.</p>', 2);
						else 
							self.modal.updateContent('<p>Sorry, an error occured. Please try again later.</p>', 2);
					}
				});
			},
			
			disconnectFbidWithAusid: function() {
				var self = this;
				new Ajax.Request(self.serviceUrl, { 
					method: "post", 
					parameters: { command: "disconnectUser", id: self.user.id },
					onComplete: function(response) {
						if (response.status == 200) 
							self.modal.updateContent('<p>Your ' + self.activeProperty + ' and Facebook accounts are no longer connected.</p>', 2);
						else 
							self.modal.updateContent('<p>Sorry, an error occured. Please try again later.</p>', 2);
					}
				});
				self.modal.show();
			},
			
			determineModalContent: function() {
				var activeCasSession = (this.casSession.loginData.LoggedIn) ? true : false;
				
				// determine facebook ihoops friends content
				if (activeCasSession == true) this.getFacebookFriends();
				else $("ihoops_facebook_friends_list").update("<p>Please log into both your Facebook and iHoops accounts to see which of your friends are also members.</p>");

				// determine account pairing message
				if ((this.pairedAusId != null) && (activeCasSession == false)) {
					//this.askUserToLoginToActive(); // temporarily commented out on 06/29/2010
				}
				else if ((this.pairedAusId == null) && (activeCasSession == true)) {
					this.askUserToPairAccounts();
				}
				else if ((this.pairedAusId == null) && (activeCasSession == false)) {
					this.askUserToAssociateAnActiveAccount();
				}
				else {
					this.modal.updateContent('<p>Your ' + this.activeProperty + ' and Facebook accounts are already connected.</p>', 2);
				}
			},
			
			askUserToLoginToActive: function() {
				var autoPopup = this.cookieManager.readCookie("do_not_autodisplay_fbc");
				if (autoPopup != "true") this.modal.show();

				this.modal.updateContent('<p>Welcome back!  Would you like to login to ' + this.activeProperty + '?</p><div class="fbc_button"><a href="javascript:ActiveNetwork.FacebookConnect.instance.loginToActive(0);">Login</a></div>', 1);
			},
			
			loginToActive: function(newAccount) {
				this.modal.updateContent("<p>Please be patient while we load the login page</p>");
				if (newAccount == 1) this.casSession.signUp();
				else this.casSession.logIn();
			},

			askUserToPairAccounts: function() {
				// if cookie is set, just do it automatically
				var autopair = this.cookieManager.readCookie("autopair_accounts");

				if (autopair == "true") {
					this.connectFbidWithAusid();
					this.modal.show();
					this.cookieManager.eraseCookie("autopair_accounts");
				}
				else {
					var autoPopup = this.cookieManager.readCookie("do_not_autodisplay_fbc");
					if (autoPopup != "true") this.modal.show();
					this.modal.updateContent('<p>It appears that you\'re currently logged in to ' + this.activeProperty + '.  Would you like to connect your ' + this.activeProperty + ' and Facebook accounts?</p><div class="fbc_button"><a href="javascript:ActiveNetwork.FacebookConnect.instance.connectAccounts();">Yes</a></div>', 1);
				}
			},

			connectAccounts: function() {
				this.connectFbidWithAusid();
				this.modal.updateContent("<p>Connecting your accounts...</p>");
			},

			askUserToAssociateAnActiveAccount: function() {
				var autoPopup = this.cookieManager.readCookie("do_not_autodisplay_fbc");
				if (autoPopup != "true") this.modal.show();

				this.modal.updateContent('<p>Would you like to connect your Facebook account with an ' + this.activeProperty + ' account? Click the button below to login or create a new ' + this.activeProperty + ' account.</p><div class="fbc_button"><a href="javascript:ActiveNetwork.FacebookConnect.instance.associateAnActiveAccount();">Login / Register</a></div>', 1);
			},

			associateAnActiveAccount: function() {
				this.cookieManager.createCookie("autopair_accounts", "true", 0.5);
				this.modal.updateContent("<p>Please be patient while we load the login page.</p>");
				this.casSession.logIn();
			},

			askUserToLoginToFacebook: function() {
				var self = this;
				FB.login(function(response) { 
					if (response.status == 'connected') self.getFacebookUserInfo(); 
				}, 
				{scope: "user_photos"});
			},

			setFacebookAutoDisplayCookie: function(interval) {
				this.cookieManager.createCookie("do_not_autodisplay_fbc", "true", interval);
				this.modal.hide();
			},

			clearAllFacebookConnectCookies: function() {
				this.cookieManager.eraseCookie("do_not_autodisplay_fbc");
				this.cookieManager.eraseCookie("autopair_accounts");
				location.reload(true);
			},
			
			getFacebookFriends: function() {
				var self = this;
				FB.api('/me/friends/', function(response) { 
					if (response.data[0].id == undefined) { }
					else self.buildFacebookFriendsArray(response.data);
				});
			},

			buildFacebookFriendsArray: function(friendsData) {
				var self = this;
				var friendsIds = [];
				
				for (var i = 0; i < friendsData.length; i++) {
					// for comparing with active paired accounts
					friendsIds.push(friendsData[i].id);
					// for everything else
					var facebookFriend = new Array();			
					var nameParts = friendsData[i].name.split(/( )/);
					facebookFriend.id = friendsData[i].id;
					facebookFriend.name = friendsData[i].name;
					facebookFriend.firstName = nameParts[0];
					facebookFriend.lastName = nameParts[1];
					facebookFriend.pictureUrl = 'http://graph.facebook.com/' + friendsData[i].id + '/picture';
					if (facebookFriend.id != undefined) this.facebookFriends.push(facebookFriend);
				}
				//friendsIds = "[" + friendsIds.substring(0,(friendsIds.length-2)) + "]";

				new Ajax.Request(self.serviceUrl, { 
					method: "post", 
					parameters: { command: "getUsers", data: Object.toJSON(friendsIds) },
					onComplete: function(response) {
						if (response.status == 200) {
							self.displayAuthenticatedFriends(response.responseText.evalJSON(false));
						}
						else alert( "Error: " + response.status );
					}
				});
			},
			
			displayAuthenticatedFriends: function(authenticatedFriends) {
				var markup = "";
				authenticatedFriends = this.arrayShuffle(authenticatedFriends);

				if (authenticatedFriends.length > 0) {
					markup = "<p>These friends are also members of iHoops:</p>";
					for (var i = 0; (i < authenticatedFriends.length && i < 8); i++) {
						markup += '<div class="fb_friend"><img src="http://graph.facebook.com/' + authenticatedFriends[i].id + '/picture" /><span>' + this.getFriendNameById(authenticatedFriends[i].id, "first") + '</span></div>';
					}
					markup += '<p style="clear: both;"><a class="more" href="javascript:ActiveNetwork.FacebookConnect.instance.showAllFriendFansModal();">See all &raquo;</a></p>';
					this.buildAuthenticatedFriendsModal(authenticatedFriends);
				}
				else markup = "<p>None of your Facebook friends are currently members of iHoops. Invite them to join and share in the iHoops experience!</p>";

				$("ihoops_facebook_friends_list").update(markup);
			},
			
			buildAuthenticatedFriendsModal: function(authenticatedFriends) {
				var markup = '<div class="friends_modal_header"><span class="left">Facebook Friends on iHoops</span><span class="right"><a href="javascript:ActiveNetwork.FacebookConnect.instance.hideAllFriendFansModal();">close</a></span></div><div class="friend_list">';
				for (var i = 0; i < authenticatedFriends.length; i++) {
					var fbId = authenticatedFriends[i].id;
					markup += '<div class="friend"><img src="http://graph.facebook.com/' + fbId + '/picture" /><p><a href="http://www.facebook.com/profile.php?id=' + fbId + '">' + this.getFriendNameById(fbId) + "</a></p></div>";
				} 
				$("ihoops_facebook_friends_modal_list").update('</div>' + markup);
			},
			
			getFriendNameById: function(facebookId, nameFormat) {
				if (typeof nameFormat == "undefined") nameFormat = "full";
				
				for (var i = 0; i < this.facebookFriends.length; i++) {
					if (this.facebookFriends[i].id == facebookId) {
						if (nameFormat == "first") return this.facebookFriends[i].firstName;
						else if (nameFormat == "last") return this.facebookFriends[i].lastName;
						else return this.facebookFriends[i].name;
					}
				}
			},
			
			showAllFriendFansModal: function() {
				this.facebookFriendsModal.open();
			},

			hideAllFriendFansModal: function() {
				this.facebookFriendsModal.close();
			},
			
			arrayShuffle: function(o) {
				for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
				return o;
			}
			
		}
		
	}());
	
	ActiveNetwork.FacebookConnectModal.prototype = (function() {
		return {
			
			modal: null,
			
			render: function() {
				// create the div, add node to body, create the modal window object
			    var facebookModalMarkupDiv = Builder.node("div", { id: "facebook_connect_modal", className: "facebookModal", style: "display:none" });
				window.document.body.appendChild(facebookModalMarkupDiv);
				this.updateContent("<p></p>");
				this.modal = 
					new Control.Modal($('facebook_connect_modal'),{
						fade: true,
						overlayOpacity: 0.75,
						position: 'center'
					});
			},

			updateContent: function(modalMarkup, footerOptions) {
				if (typeof footerOptions == "undefined") footerOptions = 0;

				var cookieOptions = '<p class="links"><a href="javascript:ActiveNetwork.FacebookConnect.instance.setFacebookAutoDisplayCookie(1);">Remind Me Later</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:ActiveNetwork.FacebookConnect.instance.setFacebookAutoDisplayCookie(99999);">Don\'t Ask Again</a></p>';
				var closeButtonOption = '<div class="fbc_button"><a href="javascript:ActiveNetwork.FacebookConnect.instance.modal.hide()">Close</a></div>';

				if (footerOptions == 1) facebookModalMarkup = modalMarkup + cookieOptions;
				else if (footerOptions == 2) facebookModalMarkup = modalMarkup + closeButtonOption;
				else facebookModalMarkup = modalMarkup;

				$("facebook_connect_modal").update(facebookModalMarkup);
			},

			show: function() {
				this.modal.open();
			},

			hide: function() {
				this.modal.close();
			}

		}
	}());

	ActiveNetwork.CookieManager.prototype = (function() {
		return {
			
			createCookie: function(name,value,days) {
				var expires = "";
				if (days) {
					var date = new Date();
					date.setTime(date.getTime()+(days*24*60*60*1000));
					expires = "; expires="+date.toGMTString();
				}
				document.cookie = name+"="+value+expires+"; path=/";
			},

			readCookie: function(name) {
				var nameEQ = name + "=";
				var ca = document.cookie.split(';');
				for(var i=0;i < ca.length;i++) {
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
					if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
				}
				return null;
			},

			eraseCookie: function(name) {
				this.createCookie(name,"",-1);
			}

		}
	}());

  ActiveNetwork.FacebookConnectDisplay.prototype = (function() {
      return {
          
          facebookConnect: null,
      
          initialize: function(facebookConnect) {
              var self = this;
              self.facebookConnect = facebookConnect;
              Event.observe(document, "fb:loaded", function(e) {
                  self.render();
              });
              Event.observe(document, "cas:logout", function(e) {
                  self.render();
              });
          },
      
          render: function() {
              var facebookUser = this.facebookConnect.user;
              var eventArgs = {};
              if (this.facebookConnect.integrateWithAus) {
                  if (facebookUser == null && !this.facebookConnect.casSession.loginData.LoggedIn) {
                      eventArgs["facebookLoggedIn"] = false;
                      eventArgs["casLoggedIn"] = false;
                      eventArgs["displayname"] = null;
                      eventArgs["avatar"] = null;
                  }
                  if (facebookUser == null && this.facebookConnect.casSession.loginData.LoggedIn) {
                      eventArgs["facebookLoggedIn"] = false;
                      eventArgs["casLoggedIn"] = true;
                      eventArgs["displayname"] = this.facebookConnect.casSession.loginData.DisplayName;
                      eventArgs["avatar"] = this.facebookConnect.casSession.getAvatarUrl();
                  }
              }
              if (facebookUser == null) {
                  eventArgs["facebookLoggedIn"] = false;
                  eventArgs["casLoggedIn"] = false;
                  eventArgs["displayname"] = null;
                  eventArgs["avatar"] = null;
              }
              if (facebookUser != null && facebookUser.id != null) {
                  eventArgs["facebookLoggedIn"] = true;
                  eventArgs["casLoggedIn"] = false;
                  eventArgs["displayname"] = facebookUser.name;
                  eventArgs["avatar"] = "http://graph.facebook.com/" + facebookUser.id + "/picture";
                  if (this.facebookConnect.integrateWithAus && this.facebookConnect.casSession.loginData.LoggedIn) {
                      eventArgs["casLoggedIn"] = true;
                  }
              }
              Event.fire(document, "fbconnect:render", eventArgs);
          },

          setHtml: function(id, value) {
              value = (typeof(value) != undefined) ? String(value) : "";
              if ($(id)) $(id).innerHTML = value;
          },

          setImage: function(id, src) {
              if ($(id)) $(id).src = src;
          }
      }
  }());

}());

}());

