/**
 * PrivacyModule
 * @author Jae Cho
 * This module has three main contents:
 * 1. profile privacy
 * 2. game score option
 * 3. blocked user lists
 *
 */
function PrivacyModule() {

	/** name of the module */
	this._name=PrivacyModule.NAME;

	this._uuid =  null;

	this._profilePrivacy = "Friends";
	this._namePrivacy = "Everyone";
    this._agePrivacy = "OnlyMe";
	this._genderPrivacy = "OnlyMe";
	this._permPriv = false;	// under 16
	this._defaultScoreSetting = "Auto";
	this._scoreSettings = [];
	this._games = null;
	this._currentGame = null;

	// facebook settings
	this._facebookPublishReviews = false;
	this._facebookPublishRatings = false;
	this._facebookPublishFavorites = false;
	this._facebookPublishHighScores = false;
	this._isFacebookOnly = false; 
	this._facebookId = 0;
	com.ag.loginFB.uid = 0;
	this._formSubmitted = null;
	this._omnitureEventString = null;
	this._facebookUnlinkSuccessMessage = "";
	this._submitBool = true; // used as a switch for turning off form submission while waiting for callback

	this._dlg = null;
	this._dlgControl = null;

	this._PROFILE = {};
    this._NAME = {};
	this._AGE = {};
	this._GENDER = {};
	this._GAME = {};
	this._FACEBOOK_PUBLISH = {};
	this._FACEBOOK_FRIEND_AUTO_CONNECT = {};

	this._PROFILE["Everyone"] = { title: "Everyone", value: "Everyone", desc : "Anyone on the site can see user's full profile" };
	this._PROFILE["Friends"] = { title: "Only Friends", value: "Friends", desc : "Only Friends can see full profile. Non-Friends see limited view of profile" };
    this._NAME["Everyone"] = { title: "Everyone", value: "Everyone", desc : "Anyone on the site can see your name" };
    this._NAME["OnlyMe"] = { title: "Only Me", value: "OnlyMe", desc : "Only you can see your name" };
	this._AGE["Everyone"] = { title: "Everyone", value: "Everyone", desc : "Anyone on the site can see your age" };
	this._AGE["Friends"] = { title: "Only Friends", value: "Friends", desc : "Only Friends can see your age" };
	this._AGE["OnlyMe"] = { title: "Only Me", value: "OnlyMe", desc : "Only you can see your age" };
	this._GENDER["Everyone"] = { title: "Everyone", value: "Everyone", desc : "Anyone on the site can see your gender" };
	this._GENDER["Friends"]= { title: "Only Friends", value: "Friends", desc : "Only Friends can see your gender" };
	this._GENDER["OnlyMe"]= { title: "Only Me", value: "OnlyMe", desc : "Only you can see your gender" };
	this._GAME["Ask"]= { title: "ASK ME if I want to save my score", value: "Ask"};
	this._GAME["Auto"] = { title: "AUTOMATICALLY save my score", value: "Auto"};
	this._FACEBOOK_PUBLISH[true] = { title: "Enabled", value: true, desc : "Allow me to post my {0} to my Facebook wall" };
	this._FACEBOOK_PUBLISH[false] = { title: "Disabled", value: false, desc : "Do not post my {0} to my Facebook wall" };
	this._FACEBOOK_FRIEND_AUTO_CONNECT[true] = { title: "Enabled", value: true, desc : "Add my Facebook Friends who are also playing on AddictingGames.com to my AddictingGames friends list." };
	this._FACEBOOK_FRIEND_AUTO_CONNECT[false] = { title: "Disabled", value: false, desc : "Add my Facebook Friends who are also playing on AddictingGames.com to my AddictingGames friends list." };

	this._profileOptionsReg = [ this._PROFILE["Everyone"], this._PROFILE["Friends"] ];
	this._profileOptionsMnr = [ this._PROFILE["Friends"] ];
	this._profileOptions = this._profileOptionsMnr;
    this._nameOptions = [ this._NAME["Everyone"], this._NAME["OnlyMe"] ];
	this._ageOptionsReg = [ this._AGE["Everyone"], this._AGE["Friends"], this._AGE["OnlyMe"] ];
	this._ageOptionsMnr = [ this._AGE["Friends"], this._AGE["OnlyMe"] ];
	this._ageOptions = this._ageOptionsMnr;
	this._genderOptions = [ this._GENDER["Everyone"], this._GENDER["Friends"], this._GENDER["OnlyMe"] ];
	this._gameOptions = [ this._GAME["Ask"], this._GAME["Auto"]];
	this._facebookPublishOptions = [ this._FACEBOOK_PUBLISH[true], this._FACEBOOK_PUBLISH[false]];
	this._facebookAutoConnectOptions = [ this._FACEBOOK_FRIEND_AUTO_CONNECT[true], this._FACEBOOK_FRIEND_AUTO_CONNECT[false]];

	/** initialize the module. child modules should imlement this method to
	 * intiialize UI state and bind actions to elements.
	 */
	this.initialize = function()
	{
		this._cont = $("#privacyMod");
		this._dlg = this._cont.find("#pmDialog");
		this._dlgControl = new DialogControl("#pmDialog");

		this._uuid =  this._page.getLoggedInUserUuid();

		this._cont.find("#pmProfile").find("a").click(bindContext(this, this._showProfileDlg));
        this._cont.find("#pmName").find("a").click(bindContext(this, this._showNameDlg));
		this._cont.find("#pmAge").find("a").click(bindContext(this, this._showAgeDlg));
		this._cont.find("#pmGender").find("a").click(bindContext(this, this._showGenderDlg));
		this._cont.find("#pmGameDefault").find("a").click(bindContext(this, this._showDefaultGameDlg));

		this._cont.find("#pmFacebookFriendAutoconnect").find("a").click(bindContext(this, this._showFacebookAutoConnectDlg));
		this._cont.find("#pmFacebookPublishReviews").find("a").click(bindContext(this, this._showFacebookPublishReviewsDlg));
		this._cont.find("#pmFacebookPublishRatings").find("a").click(bindContext(this, this._showFacebookPublishRatingsDlg));
		this._cont.find("#pmFacebookPublishFavorites").find("a").click(bindContext(this, this._showFacebookPublishFavoritesDlg));
//		this._cont.find("#pmFacebookPublishHighScores").find("a").click(bindContext(this, this._showFacebookPublishHighScoresDlg));
		// unlink facebook-account form: update FB-only account, unlink FB-only account, unlink AG account
		this._cont.find("#facebookUnlinkForm").submit(bindContext(this,this._submitUnlinkForm));
		this._cont.find("#facebookUnlinkNoUpdate").click(bindContext(this,this._handleUnlinkNoUpdate));
		this._cont.find("#facebookUnlinkExistingAccount").click(bindContext(this, this._handleUnlinkExitingAccount));

		this._dlg.find("#pmDlgCancel").bind("click", this, function(e) {
			e.preventDefault();
			var mod = e.data;
			mod._dlgControl.hideDialog();
		});

		// show / hide unlink-facebook-account form
		$(".accWidget .edit a:not(#pmDlgSave,#pmDlgCancel),#facebookUnlinkLink").click(bindContext(this, function(e){
			e.preventDefault();
			this._showEdit(e.target);
		}));
		$(".accWidget .cancelEdit").click(bindContext(this, function(e){
			e.preventDefault();
			this._showDisplay(e.target);
		}));
		$("#cancelEditOk").click(bindContext(this, this._unlinkFacebookAccount));

		// populate drop downs
		this._populateDOB();
//		this._populateCountry();
//		this._populateState();

		// is user facebook-only
		var params = {};
		var uuid = LoginModule.getSessionUserUuid();
		if (uuid) params.uuid = uuid;

		if ( LoginModule.getSessionFacebookOnly() == 'true' ) {
			$( "#facebookUnlinkForm" ).show();
			$( "#facebookUnlinkExistingAccountLink" ).hide();
			$( "#fbUnlinkText" ).show();
			$( "#fbUnlinkExistingText" ).hide();
		} else {
			$( "#facebookUnlinkForm" ).hide();
			$( "#facebookUnlinkExistingAccountLink" ).show();
			$( "#fbUnlinkText" ).hide();
			$( "#fbUnlinkExistingText" ).show();
		}

		if ( LoginModule.getSessionFacebookId() > 0 ) {
			$( ".facebookSetting" ).show();
		} else {
			$( ".facebookSetting" ).hide();
		}

		$( "#fbUserName" ).text( LoginModule.getSessionFacebookName() );
		$( "#agUserName").text( LoginModule.getSessionUsername() );

		this._showFacebookAutoConnect();

	};

	/** list of initial AJAX request that needs to be made when a module loads */
	this.getInitRequests = function() {
		return [
			{ "methodName" : "profileService.getPrivateProfile" },
			{ "methodName" : "highScoreService.getDefaultHighScoreSetting","userUuid": this._uuid },
			{ "methodName" : "profileService.getFacebookPrefs","userUuid": this._uuid },
			{ "methodName" : "profileService.getBlockedUsers" }
		];
	};

	/** handle array of response object - this is to be defined by child class
	 * @name name of parameter
	 * @value list of response objects
	 */
	this.handleResObjects = function(resObjects) {
		var gameIndex = 0;

		for (var i = 0; i < resObjects.length; i++) {
			var res = resObjects[i];
			if (res.methodName == "profileService.getPrivateProfile") {
				this._handlePrivateProfileRes(res.response);
			} else if (res.methodName == "highScoreService.getDefaultHighScoreSetting") {
				this._handleDefaultGamePrivacyRes(res.response);
			} else if (res.methodName == "highScoreService.getHighScoreSetting") {
				this._handleGetHighScoreSetting(res.response, gameIndex++);
			} else if (res.methodName == "profileService.getBlockedUsers") {
				this._handleBlockedUsersRes(res.response);
			}else if (res.methodName == "highScoreService.getGamesPlayed"){
				this._handleGetHighScoreGamesRes(res.response);
			}else if (res.methodName =="highScoreService.setHighScoreSetting"){
				this._getGamePrivacySettings();
			}else if (res.methodName =="profileService.getFacebookPrefs"){
				this._facebookPublishReviews = res.response.facebookPublishReviews;
				this._facebookPublishRatings = res.response.facebookPublishRatings;
				this._facebookPublishFavorites = res.response.facebookPublishFavorites;
				this._facebookPublishHighScores = res.response.facebookPublishHighScores;
				this._showFacebookPublishReviews();
				this._showFacebookPublishRatings();
				this._showFacebookPublishFavorites();
//				this._showFacebookPublishHighScores();
			}
		}
	};

	/** update the page with profile privacy */
	this._handlePrivateProfileRes = function(res)
	{
		if (res.needInfoToFriend) {
			this._cont.find("#pmProfile").find("a").hide();
			this._profileOptions = this._profileOptionsMnr;
			this._ageOptions = this._ageOptionsMnr;
		} else {
			this._profileOptions = this._profileOptionsReg;
			this._ageOptions = this._ageOptionsReg;
		}


		if (res.privateProfile){
			this._profilePrivacy = "Friends";
		}else{
			this._profilePrivacy = "Everyone";
		}

		this._showProfile();

        this._namePrivacy = res.namePrivacy;
		this._permPriv = res.maintainPrivacy;
        this._showName();

		this._agePrivacy = res.agePrivacy;
		this._showAge();

		this._genderPrivacy = res.genderPrivacy;
		this._showGender();

		this._dlgControl.hideDialog();
		this._profileWaitHandler();

	};

	this._profileWaitHandler = function(){
		$("#profileWait").closest(".account_main").hide();
		this._cont.show();
	};

	this._showProfile = function() {
		var option = this._PROFILE[this._profilePrivacy];
		if (option) {
			var cont = this._cont.find("#pmProfile");
			cont.find(".formValueSpan").html(option.title);
			cont.find(".formInfo").html(option.desc);
		}
	};
	this._showProfileDlg  = function()
	{
		var callback = bindContext(this, this._handleProfileSet);
		this._showPrivacyDlg("Profile Privacy", this._profileOptions, this._profilePrivacy, callback);
	};
	this._handleProfileSet = function(e) {
		e.preventDefault();
		this._profilePrivacy = this._selectedPrivacyValue;

		var isPrivateProfile = true;
		if (this._profilePrivacy == "Everyone") {
			isPrivateProfile = false;
		}

		this._page.makeModuleAjaxCall(this,
			[{ "methodName" : "profileService.setPrivacy", "privateProfile" : isPrivateProfile },
			 { "methodName" : "profileService.getPrivateProfile" }
			]);
	};

    this._showNameDlg = function() {
        var callback = bindContext(this, this._handleNameSet);
        this._showPrivacyDlg("Name Privacy", this._nameOptions, this._namePrivacy, callback);
    };
    this._showName = function()
    {
		if ( this._permPriv )
		{
			this._cont.find("#pmName").hide();
			return;
		}

        var option = this._NAME[this._namePrivacy];
        if (option) {
            var cont = this._cont.find("#pmName");
            cont.find(".formValueSpan").html(option.title);
            cont.find(".formInfo").html(option.desc);
        }
    };
    this._handleNameSet = function(e) {
        e.preventDefault();
        this._dlgControl.hideDialog();
        this._page.makeModuleAjaxCall(this,
             [{ "methodName" : "profileService.setPrivacy", "namePrivacy" : this._selectedPrivacyValue },
              { "methodName" : "profileService.getPrivateProfile" }]);
    };

	this._showAgeDlg = function() {
		var callback = bindContext(this, this._handleAgeSet);
		this._showPrivacyDlg("Age Privacy", this._ageOptions, this._agePrivacy, callback);
	};
	this._showAge = function()
	{
		var option = this._AGE[this._agePrivacy];
		if (option) {
			var cont = this._cont.find("#pmAge");
			cont.find(".formValueSpan").html(option.title);
			cont.find(".formInfo").html(option.desc);
		}
	};
	this._handleAgeSet = function(e) {
		e.preventDefault();
		this._dlgControl.hideDialog();
		this._page.makeModuleAjaxCall(this,
			 [{ "methodName" : "profileService.setPrivacy", "agePrivacy" : this._selectedPrivacyValue },
			  { "methodName" : "profileService.getPrivateProfile" }]);
	};

	this._showGender = function()
	{
		var option = this._GENDER[this._genderPrivacy];
		if (option) {
			var cont = this._cont.find("#pmGender");
			cont.find(".formValueSpan").html(option.title);
			cont.find(".formInfo").html(option.desc);
		}
	};
	this._showGenderDlg = function() {
		var callback = bindContext(this, this._handleGenderSet);
		this._showPrivacyDlg("Gender Privacy", this._genderOptions, this._genderPrivacy, callback);
	};
	this._handleGenderSet = function(e) {
		e.preventDefault();
		this._dlgControl.hideDialog();
		this._page.makeModuleAjaxCall(this,
			 [{ "methodName" : "profileService.setPrivacy", "genderPrivacy" : this._selectedPrivacyValue },
			  { "methodName" : "profileService.getPrivateProfile" }]);
	};

	/** update the page with profile privacy */
	this._handleDefaultGamePrivacyRes = function(res)
	{
		this._setGameDesc(null);
		this._defaultScoreSetting = res.scoreSetting;
		var option = this._GAME[this._defaultScoreSetting];
		if (option) {
			var cont = this._cont.find("#pmGameDefault");
			cont.find(".formValueSpan").html(option.title);
			cont.find(".formInfo").html(option.desc);
		}
		this._getGamePrivacySettings();
	};
	this._getGamePrivacySettings = function(){
		 var req =[{ "ajaxPath" : "/jscores/get",
					"methodName": "highScoreService.getGamesPlayed",
					"userUuid": this._uuid, "startIndex":0,
					"resultSize":10 }];

		 this._page.makeModuleAjaxCall(this, req);
	};
	this._showDefaultGameDlg = function() {

		this._setGameDesc(null);
		var gameOptions = [ this._GAME["Ask"], this._GAME["Auto"]];

		var callback = bindContext(this, this._handleDefaultGamePrivacySet);
		this._showPrivacyDlg("Default High Score Setting", gameOptions,
				this._defaultScoreSetting, callback);
	};

	this._handleDefaultGamePrivacySet = function(e) {
		e.preventDefault();
		this._dlgControl.hideDialog();
		this._page.makeModuleAjaxCall(this,
			 [{ "methodName" : "highScoreService.setDefaultHighScoreSetting", "scoreSetting" :  this._selectedPrivacyValue,"userUuid": this._uuid },
			  { "methodName" : "highScoreService.getDefaultHighScoreSetting","userUuid": this._uuid }]);
	};
	 this._handleGamePrivacySet = function(gameId,e) {
		e.preventDefault();
		this._dlgControl.hideDialog();
		this._page.makeModuleAjaxCall(this,
			 [{ "methodName" : "highScoreService.setHighScoreSetting", "scoreSetting" :  this._selectedPrivacyValue,"userUuid": this._uuid, "gameId":gameId }]);
	};

	this._handleGetHighScoreGamesRes = function(res)
	{
		this._games = res.games;

		var req = [];

		for (var i = 0; i < this._games.length; i++) {
			req[i] = { "methodName" : "highScoreService.getHighScoreSetting", "gameId" : this._games[i].id,"userUuid": this._uuid };
		}
		this._page.makeModuleAjaxCall(this, req);
	};

	this._showGameDlg = function(gameId,gameName) {
	   var callback = bindContext(this, this._handleGamePrivacySet,[gameId]);

	   this._setGameDesc(gameName);

	   var gameOptions = [ this._GAME["Ask"], this._GAME["Auto"]];

		this._showPrivacyDlg(gameName + " High Score Setting", gameOptions,
			   this._scoreSettings[gameId], callback);
	};

	this._setGameDesc = function(gameName){
	   if (gameName){
		   this._GAME["Ask"].desc =
				"When I play " + gameName + ", always ask me before saving my high score. " +
				"Other people on the site will see my score for " + gameName +
				", only if I choose to save it.";

		   this._GAME["Auto"].desc =
				"Every time I play " + gameName + ", automatically save my best score. " +
				"Anyone on the site can view my " + gameName + " high score.";
	   }else{
			this._GAME["Ask"].desc =
				"For new games that I play, always ask me before saving my high score. " +
				"Other people on the site will see my score, only if I choose to save it.";

			this._GAME["Auto"].desc =
				"For new games that I play, automatically save my best score. " +
				"Anyone on the site can view these high scores.";
	   }

	};

	this._handleGetHighScoreSetting = function(res, gameIndex)
	{
		var game = this._games[gameIndex];

		var gamePrivacy = res.scoreSetting;

		this._setGameDesc(game.name);

		var option = this._GAME[gamePrivacy];
		if (!option || !game) return;

		this._scoreSettings[game.id] = gamePrivacy;

		var cont = this._cont.find("#pmGame_" +  game.id);
		if (!cont.length)
		{
			var listCont = this._cont.find("#pmGameList");
			listCont.append(
				"<div id='pmGame_" + game.id + "' class='formElement'>" +
					"<div class='formLabel float'>" + game.name + ":</div>" +
					"<div class='formValue float'><span class='formValueSpan'></span>&nbsp;<a>edit</a><br/>" +
						"<div class='formInfo'></div>" +
					"</div>" +
				"<br class='clearFloat' />");
			cont = this._cont.find("#pmGame_" +  game.id);
			cont.find("a").click(bindContext(this, this._showGameDlg, [game.id,game.name]));
		}

		cont.find(".formValueSpan").html(option.title);
		cont.find(".formInfo").html(option.desc);
	};

	this._handleBlockedUsersRes = function(res)
	{
		var profiles = res.blockedUsers;

		var cont = this._cont.find("#pmBlockedUserList");
		cont.empty();

		if (!profiles || !profiles.length) {
			cont.html("You have not blocked any AG members");
			return;
		}

		for (var i = 0; i < profiles.length; i++) {
			var profile = profiles[i];
			var profileDivContent =
					"<div class='profileSm'>" +
						"<a href='/profile/" + profile.profilePath + "'>" +
							"<img class='profileImgSm' src='" + ProfileUtil.getImg({userId: profile.userId,userPicSet: profile.userPicSet,size:"small"}) + "'/>" +
						"</a>" +
						"<div>" +
							"<a href='/profile/" + profile.profilePath + "'>" + profile.userName + "</a><br/>" +
							"<a userId='" + profile.userId + "'>unblock</a><br />" +
						"</div>" +
					"</div>";

			cont.append(profileDivContent);

			cont.find("a[userId=" + profile.userId + "]").bind("click", this, function(e) {
				var mod = e.data;
				mod._unblockUser(parseInt($(this).attr("userId")));
			});

			if ((i + 1) % 5 == 0 || i + 1 == profiles.length) {
				var dividerContent = "<div class='clearfix'></div>";
				cont.append(dividerContent);
			}
		}
	};

	this._unblockUser = function(userId)
	{
		this._page.makeModuleAjaxCall(this,
			 [{ "methodName" : "profileService.unblockUser", "userId" :  userId },
			  { "methodName" : "profileService.getBlockedUsers" }]);
	};

	// ********************************
	// *** FACEBOOK FUNCTIONS ***
	// ********************************

	// *** DISPLAY / UPDATE FACEBOOK SETTTINGS ***
	this._showFacebookAutoConnect = function() {
		var autoConnect = LoginModule.getSessionFacebookFriendAutoConnect();
		var option = this._FACEBOOK_FRIEND_AUTO_CONNECT[autoConnect];
		if (option) {
			var cont = this._cont.find("#pmFacebookFriendAutoconnect");
			cont.find(".formValueSpan").html(option.title);
			cont.find(".formInfo").html(option.desc);
		}

	}


	// facebook friend auto-connect
	this._showFacebookAutoConnectDlg = function() {
		var autoConnect = LoginModule.getSessionFacebookFriendAutoConnect();
		var callback = bindContext(this, this._handleFacebookAutoConnectSet);
		this._showPrivacyDlg("Facebook Friend Auto-connect Settings", this._facebookAutoConnectOptions, autoConnect, callback);
	};
	this._handleFacebookAutoConnectSet = function(e) {
		var params = {};
		params.uuid = LoginModule.getSessionUserUuid();
		params.isFacebookAutoConnectFriends = this._selectedPrivacyValue;
		e.preventDefault();
		this._dlgControl.hideDialog();
		this._makeRestRequest("/facebook/updateAutoConnectToggle", "POST", params, this._handleFacebookAutoConnectReturn);
	};
	this._handleFacebookAutoConnectReturn = function() {
		this._showFacebookAutoConnect();
	}

	// facebook publish reviews
	this._showFacebookPublishReviews = function() {
		var option = this._FACEBOOK_PUBLISH[this._facebookPublishReviews];
		if (option) {
			var cont = this._cont.find("#pmFacebookPublishReviews");
			cont.find(".formValueSpan").html(option.title);
			cont.find(".formInfo").html(option.desc.replace("{0}", "reviews"));
		}
	};
	this._showFacebookPublishReviewsDlg = function() {
		var callback = bindContext(this, this._handleFacebookPublishReviewsSet);
		this._showPrivacyDlg("Facebook Publish Settings", this._facebookPublishOptions, this._facebookPublishReviews, callback, "reviews");
	};
	this._handleFacebookPublishReviewsSet = function(e) {
		e.preventDefault();
		this._dlgControl.hideDialog();
		this._page.makeModuleAjaxCall(this,
			[{ "methodName" : "profileService.setFacebookPublishReviews", "facebookPublishReviews" : this._selectedPrivacyValue, "userUuid": this._uuid },
			 { "methodName" : "profileService.getFacebookPrefs", "userUuid": this._uuid }]);
	};

	// facebook publish ratings
	this._showFacebookPublishRatings = function(){
		var option = this._FACEBOOK_PUBLISH[this._facebookPublishRatings];
		if (option) {
			var cont = this._cont.find("#pmFacebookPublishRatings");
			cont.find(".formValueSpan").html(option.title);
			cont.find(".formInfo").html(option.desc.replace("{0}", "ratings"));
		}
	};
	this._showFacebookPublishRatingsDlg = function() {
		var callback = bindContext(this, this._handleFacebookPublishRatingsSet);
		this._showPrivacyDlg("Facebook Publish Settings", this._facebookPublishOptions, this._facebookPublishRatings, callback, "ratings");
	};
	this._handleFacebookPublishRatingsSet = function(e) {
		e.preventDefault();
		this._dlgControl.hideDialog();
		this._page.makeModuleAjaxCall(this,
			[{ "methodName" : "profileService.setFacebookPublishRatings", "facebookPublishRatings" : this._selectedPrivacyValue, "userUuid": this._uuid },
			 { "methodName" : "profileService.getFacebookPrefs", "userUuid": this._uuid }]);
	};

	// facebook publish favorites
	this._showFacebookPublishFavorites = function(){
		var option = this._FACEBOOK_PUBLISH[this._facebookPublishFavorites];
		if (option) {
			var cont = this._cont.find("#pmFacebookPublishFavorites");
			cont.find(".formValueSpan").html(option.title);
			cont.find(".formInfo").html(option.desc.replace("{0}", "favorites"));
		}
	};
	this._showFacebookPublishFavoritesDlg = function() {
		var callback = bindContext(this, this._handleFacebookPublishFavoritesSet);
		this._showPrivacyDlg("Facebook Publish Settings", this._facebookPublishOptions, this._facebookPublishFavorites, callback, "favorites");
	};
	this._handleFacebookPublishFavoritesSet = function(e) {
		e.preventDefault();
		this._dlgControl.hideDialog();
		this._page.makeModuleAjaxCall(this,
			 [{ "methodName" : "profileService.setFacebookPublishFavorites", "facebookPublishFavorites" : this._selectedPrivacyValue, "userUuid": this._uuid },
			  { "methodName" : "profileService.getFacebookPrefs", "userUuid": this._uuid }]);
	};

/*
	// facebook publish high scores
	this._showFacebookPublishHighScores = function(){
		var option = this._FACEBOOK_PUBLISH[this._facebookPublishHighScores];
		if (option) {
			var cont = this._cont.find("#pmFacebookPublishHighScores");
			cont.find(".formValueSpan").html(option.title);
			cont.find(".formInfo").html(option.desc.replace("{0}", "high scores"));
		}
	};
	this._showFacebookPublishHighScoresDlg = function() {
		var callback = bindContext(this, this._handleFacebookPublishHighScoresSet);
		this._showPrivacyDlg("Facebook Publish Settings", this._facebookPublishOptions, this._facebookPublishHighScores, callback, "high scores");
	};
	this._handleFacebookPublishHighScoresSet = function(e) {
		e.preventDefault();
		this._dlgControl.hideDialog();
		this._page.makeModuleAjaxCall(this,
			 [{ "methodName" : "profileService.setFacebookPublishHighScores", "facebookPublishHighScores" : this._selectedPrivacyValue, "userUuid": this._uuid },
			  { "methodName" : "profileService.getFacebookPrefs", "userUuid": this._uuid }]);
	};
*/

	// ********************************
	// *** UNLINK FACEBOOK ACCOUNT ***
	// ********************************

	// *** ACCOUNT WIDGET DISPLAY FOR UNLINKING FACEBOOK ***

	this._showEdit = function(div){
		var cont = $(div).closest(".accWidget");
		cont.hide().next().show();
	};

	this._showDisplay = function(div){
		var cont = $(div).closest(".accWidget");
		cont.hide().prev().show();
	};

	// *** POPULATE DROP DOWNS FOR UPDATING AG ACCOUNT ***

	this._populateDOB = function(){

		// populate days 1-28
		for (var day=1; day<29; day++) {
			$("#privacyMod").find("#day").addOption(day,day);
		}
		// populate months
		$.each(RegisterModule.MONTHS, function(index, value) {
			$("#privacyMod").find("#month").addOption(index,value);
		});

		// populate years
		var year=Number(eval(RegisterModule.STARTYEAR));
		for (var endYear = Number(eval(RegisterModule.ENDINGYEAR)); year <= endYear ; --endYear) {
			$("#privacyMod").find("#year").addOption(endYear,endYear);
		}
	};

//	this._populateState = function(){
//		$.each(RegisterModule.STATES, function(index, value) {
//			$("#privacyMod").find("#states").addOption(value.code,value.state);
//		});
//	};
//
//	this._populateCountry = function(){
//		$.each(RegisterModule.COUNTRIES, function(index, value) {
//			$("#privacyMod").find("#countries").addOption(value.code,value.country);
//		});
//	};

	// *** UPDATE AG ACCOUNT / UNLINK FACEBOOK ACCOUNT ***

	this._clearErrors = function(){
		$("#privacyMod").find(".errorMsg").hide().empty();
	};

	// unlink facebook from existing AG account
	this._handleUnlinkExitingAccount = function(e) {
		this._omnitureEventString = "fbc_unlink_trash";
		this._handleRemoveFacebook(e);
	}

	// unlink facebook from FB-only *without* updating account info
	this._handleUnlinkNoUpdate = function(e) {
		this._omnitureEventString = "fbc_unlink_linked";
		this._handleRemoveFacebook(e);
	}

	// remove facebook connection without updating account info
	this._handleRemoveFacebook = function(e) {
		e.preventDefault();
		this._clearErrors();
		var params = {};
		params.uuid = this._uuid;
		this._makeRestRequest("/facebook/unlink", "POST", params, this._handleCompleteUnlink);
	}

	this._submitUnlinkForm = function(e){
		if(this._submitBool) {
			e.preventDefault();
			this._clearErrors();
			this._formSubmitted = $("#facebookUnlinkForm");
			this._disableForm();
			this._processCompleteAGAccount();
		}
	};

	// unlink FB-only account and update account info
	this._processCompleteAGAccount = function(){
		var params = {};
		this._clearErrors();

		params.isAccountUpdate = true;
		params.uuid = this._uuid;
		params.email = $("#email").val();
		params.password = $("#privacyMod").find("#password").val();
		params.country = $("#privacyMod").find("#countries").val();
		params.state = $("#privacyMod").find("#states").val();
		params.dobDay = $("#privacyMod").find("#day").val();
		params.dobMonth = $("#privacyMod").find("#month").val();
		params.dobYear = $("#privacyMod").find("#year").val();
		params.tos = ( $("#privacyMod").find("#tos:checked").val() != null ) ? "true" : '';
		params.subscribe = ( $("#privacyMod").find("#register_subscribe:checked").val() != null ) ? "true" : '';
		this._omnitureEventString = "fbc_unlink_update";
		this._facebookUnlinkSuccessMessage = "Your AddictingGames account is no longer linked to your Facebook account.";
		this._makeRestRequest("/facebook/unlink", "POST", params, this._handleCompleteUnlink);
	};

	// after unlink ajax call
	this._handleCompleteUnlink = function(res){

		// logout
		var loginModule = g_page.getModule("LoginModule");
		loginModule.logout();
		
		// send omniture event - if string has been set
		if ( this._omnitureEventString != null ) {
			sendLinkEvent(this._omnitureEventString);
			this._omnitureEventString = null;
		}

		// show success message - if message isnt empty
		if ( this._facebookUnlinkSuccessMessage != "" ) {
			alert( this._facebookUnlinkSuccessMessage );
		}
	};

	this._handleFieldErrors = function(obj) {
		this._clearErrors();
		for (var fielderror in obj){
		   this._formSubmitted.find(".errorMsg").prepend('<div class="validation-message">'+obj[fielderror].message+'</div>');
		}
		this._formSubmitted.find(".errorMsg").show();
		this._enableForm();
	};
	this._handleGeneralErrors = function(obj){
		this._clearErrors();
		if (typeof obj == "string"){
		   this._formSubmitted.find(".errorMsg").append('<div class="validation-message">'+obj+'</div>');
		} else {
			for (var generalerror in obj){
				this._formSubmitted.find(".errorMsg").append('<div class="validation-message">'+obj[generalerror].message+'</div>');
			}
		}
		this._formSubmitted.find(".errorMsg").show();
		this._enableForm();
	};


	this._disableForm = function() {
		var elm = this._formSubmitted.find(".button_primary");
		// style button as disabled
		elm.addClass("button_primary_disabled");
		// disable form submit flag
		this._submitBool = false;
	};
	this._enableForm = function() {
		var elm = this._formSubmitted.find(".button_primary");
		// restore enabled button
		elm.removeClass("button_primary_disabled");
		// enable form submit flag
		this._submitBool = true;
	};

	/**
	 * customize the privacy dialog for the given privacy setting and display it
	 * @param title title for the dialog
	 * @param options available options for the privacy
	 * @param selectedVal currently selected value
	 * @param callbackMethod method to call when save button is clicked
	 * @param textReplace optional argument to replace text in the options description
	 */
	this._showPrivacyDlg = function(title, options, selectedVal, callbackMethod, textReplace)
	{
		this._dlg.find(".dialogue_top").find("h1").html(title);

		var form = this._dlg.find("#pmDlgForm");
		form.empty();

		for (var i = 0; i < options.length; i++)
		{
			var option = options[i];
            var optionDesc = (textReplace) ? option.desc.replace("{0}", textReplace) : option.desc;
			form.append(
				"<h3>" +
					"<input name='privacy' value='" + option.value + "' type='radio'/>&nbsp;" +
					option.title +
				"</h3>" +
				"<p class='radioSubText'>" + optionDesc + "</p>"
			);
		}

		this._dlg.find("input[value=" + selectedVal + "]").attr("checked", true);
		this._selectedPrivacyValue = selectedVal;

		this._dlg.find("input").bind("change", this, function(e) {
			var mod = e.data;
			if ($(this).attr("checked")) {
				mod._selectedPrivacyValue = $(this).val();
			}
		});

		this._dlg.find("#pmDlgSave").unbind().click(callbackMethod);
		this._dlgControl.showDialog();
	};
}

PrivacyModule.prototype = new Module();

PrivacyModule.NAME = "PrivacyModule";

