function CFb()
{
	this.user = null;
	this.friends = null;

	this.photo = new CFBPhoto(this); //user's picture
	this.photoPermission = false;

	this.target = new CFBTarget(this);

	this.reqs = new CReqs(this);
	this.messageTimer = null;

	this.init = function()
	{
		var self = this;

		game.showLoader();

		this.messageTimer = setInterval(function(){ with(self) hideGame(); }, 250);

		FB.init(c.fb_api_key, 'xd_receiver.htm');

		FB.ensureInit(function(){
			FB.Connect.get_status().waitUntilReady(function(status)
			{
				switch(status)
				{
					case FB.ConnectState.appNotAuthorized:
					case FB.ConnectState.userNotLoggedIn:

						game.response("userAuth", 0);

						with(self)
						{
							target.selectUid(target.uid);

							if(target.uid == null)
								mE("user").hide();

							mE("menu,game,footer").hide();

							show();
						}
				}
			});

			FB.Connect.ifUserConnected(function(){
				game.fb.getData();

				FB.Facebook.apiClient.users_hasAppPermission("user_photos", function(result)
				{
					if(result)
						game.fb.photoPermission = true;
				}
				);

			});
		});
	}

	this.connect = function()
	{
		var self = this;

		FB.Connect.requireSession(function(){
			FB.Facebook.apiClient.users_hasAppPermission("user_photos", function(result)
			{
				if(result)
					game.fb.photoPermission = true;
				else
					FB.Connect.showPermissionDialog("user_photos", function(result)
					{
						if(result)
							game.fb.photoPermission = true;
						else
							game.fb.photoPermission = false;
					});
			});
		}, null, true);

		this.hide();
	}

	this.logout = function()
	{
		//if(game.messages.isVisible())
		//	return;

		game.messages.hide();

		FB.Connect.logout();

		this.user = null;
		this.friends = null;

		this.target.uid = null;

		mE("user-image,user-info").content("");
		mE("user").hide();

		game.response("userAuth", 0);
		game.menu.render();
	}

	this.getData = function()
	{
		var self = this;

		this.hide();

		var me = FB.Connect.get_loggedInUser();

		//load user info
		//var q = "SELECT uid, first_name, last_name, name, pic, pic_big, pic_square, sex, profile_url FROM user WHERE uid="+me;
		//FB.Facebook.apiClient.fql_query(q, function(data){ self.userCallback(self, data); });

		this.getInfo();

		//load friend info
		//var q = "SELECT uid, first_name, last_name, name, pic, pic_big, pic_square, sex, profile_url FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1="+me+") ORDER BY last_name";
		//FB.Facebook.apiClient.fql_query(q, function(data){ self.friendsCallback(self, data); });

		this.getFriends();

		if(this.target.uid == null)
			this.target.show();
		else
			this.target.selectUid(this.target.uid);
	}
	/*
	this.userCallback = function(self, data)
	{
		with(self)
		{
			if(data != null && data.length == 1)
				user = data[0];
			else
				user = null;

      	game.hideLoader();
			game.menu.render();

			renderBar();
			mE("target-change-control").show("inline");

			game.stats.init();

		  game.response("userAuth", 1);
		}
	}
	*/
	this.renderBar = function()
	{
		if(this.user == null)
		{
			this.getData();
			return;
		}

		var pic = "";
		if(this.user.pic_square)
			pic = "<a target=\"_new\" href=\"http://www.facebook.com/#!/editapps.php?ref=mb\"><img src=\""+this.user.pic_square+"\" alt=\"Facebook\" /></a>";

		mE("user-image").content(pic);

		var nextLevel = "";

		if(game.stats.getLevel() < game.stats.maxLevel)
			nextLevel = "<div id=\"user-info-next-level\">"+l.get("menu-next-level", [])+": <span id=\"user-next-level\">"+game.stats.getScoreToNextLevel()+"</span></div>";

		mE("user-info").content(this.user.name+"<br />"+l.get("menu-level", [])+": <span id=\"user-level\">"+game.stats.getLevel()+"</span> "+l.get("menu-score", [])+": <span id=\"user-score\">"+game.stats.getScore()+"</span>"+nextLevel);

		if(!game.messages.isVisible() && game.menu.getSelected("game"))
			mE("user").show();
	}
/*
	this.friendsCallback = function(self, data)
	{
		with(self)
		{
			friends = data;

			//target.check();
		}
	}
*/
	this.show = function()
	{
		game.hideLoader();

		if(!c.fb_app)
		{
			game.menu.select('game');

			var content = "";

			content += "<h1>"+l.get("share-head", [])+"</h1>";
			content += "<p>"+l.get("share-text1", [])+"</p>";
			content += "<div class=\"sharing-controls\"><a href=\"javascript:game.fb.connect()\" /><img src=\"images/login-fb.gif\" alt=\"Facebook Connect\"></a><input type=\"button\" value=\""+l.get("share-no", [])+"\" onclick=\"game.fb.hide()\" /></div>";

			game.messages.show("connect", content);
		}
	}

	this.hide = function()
	{
		game.messages.hide("connect");

		mE("menu,game").show();
	}

	this.userDetails = function(uids, callback)
	{
		var q = "SELECT uid, last_name, pic_square, pic_big FROM user WHERE "+uids;
		FB.Facebook.apiClient.fql_query(q, callback);
	}

	this.hideGame = function()
	{
		var u = game.get();
		if(u)
		{
			var fb = gE('RES_ID_fb_pop_dialog_table');
			if(fb || game.messages.isVisible())
			{
				mE("user,footer").hide();

				game.hidden = 1;

				u.style.width = "1px";
				u.style.height = "1px";

				gE("game").className = "hidden";

				//window.scroll(0,0);
			}
			else if(!game.forcedHide && game.hidden == 1)
			{
				if(game.fb.user != null || game.fb.target.uid != null)
					mE("user").show();

				mE("footer").show();

				game.hidden = 0;

				u.style.width = c.unity.width+"px";
				u.style.height = c.unity.height+"px";

				gE("game").className = "";

				window.scroll(0,0);
			}
			else if(!fb && !game.messages.isVisible())
				mE("footer").show();
		}
	}

	this.getShareLink = function(maze, target)
	{
		if(maze && target)
			return "http://"+c.domain+"/share.php?stage=stage4&target="+target+"&maze="+maze;
		else if(maze)
			return "http://"+c.domain+"/share.php?stage=stage4&maze="+maze;
		else if(target)
			return "http://"+c.domain+"/share.php?stage=stage4&target="+target;

		return "http://"+c.domain+"/share.php?stage=stage4";
	}

	//set counter
	/*
	this.incrementCounter = function(uid)
	{
		if(this.user)
			FB.Facebook.apiClient.callMethod("dashboard.incrementCount", {'uid':uid}, function(){});
	}
	*/

	//publish activity
	this.publishActivity = function(message, linkText, link)
	{
		if(this.user)
		{
			var image = 'http://'+c.domain+'/stage1/images/fb/new.jpg';

			//FB.Facebook.apiClient.callMethod("dashboard.addNews", {'uid':this.user.uid,'news':[{'message':message, 'action_link':{'text':linkText, 'href':link}}], 'image':image}, function(){});
			FB.Facebook.apiClient.callMethod("dashboard.publishActivity", {'activity':{'message':message, 'action_link':{'text':linkText, 'href':link}}}, function(){});
		}
	}

	//get difficulty settings for any user
	this.getDifficultyMods = function(uid)
	{
		this.reqs.post("user.getDifficultyMods", '{"uid":"'+uid+'"}', "getDifficultyMods", null);
	}

	//save this user's difficulty settings
	this.setDifficultyMods = function(data)
	{
		this.reqs.post("user.setDifficultyMods", JSON.stringify(data), "setDifficultyMods", null);
	}

	this.getFriends = function()
	{
		this.reqs.get("user.getFriends", "getFriends", null);
	}

	this.getInfo = function()
	{
		this.reqs.get("user.getInfo", "getInfo", null);
	}

	this.requestCallback = function(self, type, data)
	{
		with(self)
		{
			switch(type)
			{
				case "getDifficultyMods":
					difficultyMods = data;

					if(difficultyMods != null)
					{
						var content = "";

						content += l.get("difficulty-enemy-sensitivity", [floatToPct(difficultyMods.enemy_sensitivity)])+" ";
						content += l.get("difficulty-enemy-count", [difficultyMods.enemy_count])+"<br />";
						content += l.get("difficulty-enemy-speed", [floatToPct(difficultyMods.enemy_speed)])+" ";
						content += l.get("difficulty-enemy-elite", [floatToPct(difficultyMods.enemy_elite)]);

						mE("user-target-difficulty").content(content);
					}

					game.response("setTargetDifficulty", JSON.stringify(data));
				break;

				case "getFriends":
					friends = data;
				break;

				case "getInfo":
					if(data != null)
					{
						user = data;

						if(!data.difficulty_mods)
							game.response("setUserDifficulty", "null");
						else
							game.response("setUserDifficulty", JSON.stringify(data.difficulty_mods));

						if(data.messages_special != null)
						{
							for(var i = 0; i < data.messages_special.length; i++)
							{
								if(data.messages_special[i].lang != l.selected.language)
									continue;

								var content = "";

								content += "<h2 style=\"text-align: center;\">"+l.get("special-message-head", [])+"</h2>";
								content += "<div style=\"padding-top: 5px; padding-bottom: 5px;\">"+data.messages_special[i].message+"</div>";
								content += "<div style=\"text-align: center;\"><input type=\"button\" value=\""+l.get("special-message-close", [])+"\" onclick=\"game.messages.hide('special-message')\" /></div>";

								game.messages.show("special-message", content);
							}
						}

						if(data.asset == false && photoPermission)
							photo.show();

						if(data.meddled == true)
							photo.changed();
					}
					else
					{
						connect();
						//window.location.reload();
						return;
					}

					game.hideLoader();
					game.menu.render();

					renderBar();
					mE("target-change-control").show("inline");

					game.stats.init();

					game.response("userAuth", 1);
				break;
			}
		}
	}
}

function CFBTarget(parent)
{
	this.parent = parent;

	this.reqs = new CReqs(this);

	this.uid = null;

	this.selectUid = function(uid)
	{
		if(uid == "" || uid == null)
			return;

		this.uid = uid;

		var pic = "";
		if(game.fb.friends != null)
		{
			for(var i = 0; i < game.fb.friends.length; i++)
			{
				if(game.fb.friends[i].uid == uid)
				{
					pic = "<img src=\""+game.fb.friends[i].pic_square+"\" alt=\"game.fb.friends[i].name\" />";
					break;
				}
			}
		}

		var q = "SELECT last_name FROM user WHERE uid="+uid;
		FB.Facebook.apiClient.fql_query(q, function(data, pic){ if(data){ mE("target-name").content(data[0].last_name); if(pic != ""){ mE("user-target-image").content(pic); }else{ mE("user-target-image").hide(); }}});

		mE("target-change-control").content(l.get("target-change", []));

		game.fb.getDifficultyMods(uid);

		this.hide();
	}

	this.selectFriend = function(uid, name, timedMessage)
	{
		this.uid = uid;

		game.fb.getDifficultyMods(uid);

		var pic = "";
		if(game.fb.friends != null)
		{
			for(var i = 0; i < game.fb.friends.length; i++)
			{
				if(game.fb.friends[i].uid == uid)
				{
					if(game.fb.friends[i].pic_square != "")
						pic = "<img src=\""+game.fb.friends[i].pic_square+"\" alt=\""+game.fb.friends[i].name+"\" />";

					break;
				}
			}
		}

		if(pic != "")
		{
			mE("user-target-image").content(pic);
			mE("user-target-image").show();
		}
		else
			mE("user-target-image").hide();

		mE("target-name").content(name);

		mE("target-change-control").content(l.get("target-change", []));

		this.hide();

		if(timedMessage)
			game.messages.showTimed("target-name", 3000, "<h2 style=\"text-align: center;\">"+l.get("target-your", [])+"</h2><h3 style=\"text-align: center;\">"+name+"</h3><div style=\"text-align: center;\"><input type=\"button\" value=\""+l.get("asset-close", [])+"\" onclick=\"game.messages.hide('target-name')\" /></div>");
	}

	this.meddle = function()
	{
		if(this.uid)
			this.reqs.post("photo.meddle", '{"target":"'+this.uid+'"}', null, null);
	}

	this.show = function()
	{
		var data = game.fb.friends;

		if(data == null)
			return;

		var content = "";
		for(var i = 0; i < data.length; i++)
		{
			var pic = "";

			if(!data[i].pic_square)
				pic = "images/facebook_icon.jpg";
			else
				pic = data[i].pic_square;

			var score = "";
			if(data[i].score)
				score = l.get("target-score", [addCommas(data[i].score)]);

			content += "<a href=\"javascript:game.fb.target.selectFriend("+data[i].uid+", '"+data[i].name.replace("'", "\\'")+"', 0)\"><img src=\""+pic+"\" alt=\""+data[i].name+"\" /><br />"+data[i].name+"<br />"+score+"</a>";
		}

		var close = "";

		if(this.uid != null)
			close = "<div style=\"text-align: center; margin-top: 5px;\"><input type=\"button\" onclick=\"game.messages.hide('target')\" value=\""+l.get("target-close", [])+"\" /></div>";

		game.messages.show("target", "<div id=\"target-friends\"><h2>"+l.get("target-select", [])+"</h2><div class=\"friends\">"+ content + "</div>"+close+"</div>");
	}

	this.hide = function()
	{
		game.messages.hide("target");
	}

	this.shareFriend = function(target)
	{
		var link = "http://"+c.domain+"/share.php?stage=stage4&territory="+c.unity.territory+"&target="+FB.Connect.get_loggedInUser();

		var msg = "";

		var attachment =
			{
			'name': 'INCEPTION: MIND CRIME',
			'href': link,
			'caption': l.get("fb-asset1-text1", []),
			'description': l.get("fb-asset1-text2", []),
			/*
			'properties':
				{
				'category':
					{
					'text': 'humor',
					'href': 'http://bit.ly/KYbaN'
					},
				'ratings': '5 stars'
				},
			*/
			'media':
				[{
				'type': 'image',
				'src': 'http://'+c.domain+'/stage1/images/fb/new.jpg',
				'href': link
				}]
			};

		var actionLinks = '[{"text":"'+l.get("fb-share-play", [])+'", "href":"'+link+'"}]';
		var prompt = l.get("fb-asset1-text3", []);

		FB.Connect.streamPublish(msg, attachment, actionLinks, target, prompt, game.fb.shareCallback, true, null);
	}

	this.shareMaze = function(target, mazeId)
	{
		var link = "http://"+c.domain+"/share.php?stage=stage4&territory="+c.unity.territory+"&maze="+mazeId;

		var msg = "";

		var attachment =
			{
			'name': 'INCEPTION: MIND CRIME',
			'href': link,
			'caption': l.get("fb-share-text4", []),
			'description': l.get("fb-asset2-text2", []),
			/*
			'properties':
				{
				'category':
					{
					'text': 'humor',
					'href': 'http://bit.ly/KYbaN'
					},
				'ratings': '5 stars'
				},
			*/
			'media':
				[{
				'type': 'image',
				'src': 'http://'+c.domain+'/stage1/images/fb/new.jpg',
				'href': link
				}]
			};

		var actionLinks = '[{"text":"'+l.get("fb-share-play", [])+'", "href":"'+link+'"}]';
		var prompt = l.get("fb-asset2-text3", []);

		FB.Connect.streamPublish(msg, attachment, actionLinks, target, prompt, game.fb.shareCallback, true, null);
	}

	this.check = function()
	{
    if(this.uid == null)
      this.show();
  }
}
