function CFb(parent)
{
	this.parent = parent;
	
	this.name = "fb";
	
	//TODO: Change this when ready to publish
	this.hostname = "www.mind-crime.com";
	this.apiKey = "ff9fc5f2dab310ac8044fa9d6dca83ed";
	
	this.connected = 0;
	this.reqs = new CReqs(this);
	
	this.username = "";
	this.picture = "";

	this.photo = new CFBPhoto(this); //user's picture
	this.target = new CFBTarget(this);
	
	this.messageTimer = setInterval("game.fb.hideGame()", 250);
	
	this.init = function()
	{
		this.parent.showLoader();
		
		FB.init(this.apiKey, 'xd_receiver.htm');

		FB.ensureInit(function(){
			FB.Connect.get_status().waitUntilReady(function(status)
			{
				switch(status)
				{
					case FB.ConnectState.appNotAuthorized:
					case FB.ConnectState.userNotLoggedIn:
						game.fb.notConnected();
				}
			});
			
			FB.Connect.ifUserConnected(function(){ game.fb.loginTimer(); });
		});
	}

	this.connect = function(callback)
	{			
		FB.Connect.requireSession(callback, null, true);
	}
	
	this.notConnected = function()
	{
		this.parent.hideLoader();		
	}
		
	this.loginTimer = function()
	{
		//check for facebook cookies and then log user in
		var cookie = getCookie(this.apiKey+"_user");
		if(cookie == "")
		{
			setTimeout(function(){ game.fb.loginTimer(); }, 100);
			return;
		}
		
		this.login();
			
		this.parent.hideLoader();
	}

	//login with facebook
	this.login = function()
	{
		this.reqs.get("fb.login", "userAuth");
	}
			
	//general logout from the site
	this.logout = function()
	{
    FB.Connect.logout();

		this.reqs.get("user.logout", "userAuth");
	}
	
	this.requestCallback = function(type, data)
	{	
		switch(type)
		{
			case "userAuth":
				var status = parseInt(data.auth);
				
				if(status == 1)
				{
					this.connected = 1;
					
					this.photo.photoLink = data.photoLink;
					
					game.stats.updateScore(data.score);
					
					game.sharing.hide();
					
					//check for the target
					this.target.check();

//					mE("target").show();

					var q = "SELECT name, pic_square FROM user WHERE uid="+FB.Connect.get_loggedInUser();
					FB.Facebook.apiClient.fql_query(q, function(data){ game.fb.username = data[0].name; game.fb.picture = data[0].pic_square; game.fb.renderBar(); });
				}
				else
				{
					this.connected = 0;
					
					game.stats.score = 0;
					
					this.target.uid = null;
					this.photo.link = null;
					this.photo.photoLink = null;
					
					mE("target").hide();
					
					game.menu.select('game');
					game.show();
				}
				
				//alert(this.connected);
				this.parent.auth(this.connected, this);
			break;
		}
	}
	
	this.share = function()
	{		
		var link = "http://"+game.fb.hostname+"/share.php?stage=stage2&maze="+game.maze.mazeId;
		
		var msg = "";
		
		var attachment =
			{
			'name': 'MIND CRIME',
			'href': link,
			'caption': '{*actor*} just created a new maze!',
			'description': 'Steal his secret idea and compete with your friends on the leaderboard!',
			/*
			'properties':
				{
				'category':
					{
					'text': 'humor',
					'href': 'http://bit.ly/KYbaN'
					},
				'ratings': '5 stars'
				},
			*/
			'media':
				[{
				'type': 'image',
				'src': 'http://'+game.fb.hostname+'/stage1/images/fb/new.jpg',
				'href': link
				}]
			};
		
		var actionLinks = '[{"text":"Play!", "href":"'+link+'"}]';
	
		var target = null;
		var prompt = "Would you like to add a message for your friends?";
			
		FB.Connect.streamPublish(msg, attachment, actionLinks, target, prompt, null, true, null);
	}
	
	this.shareCallback = function(postId, exception)
	{
    /*
		if(!game.messages.isVisible())
			game.show();
    */
		/*
		FB.Connect.showPermissionDialog("email", function(perms){
		  if(!perms)
		    alert("no permissions granted");
		  else
		  	alert("permissions granted !!!");
		});
		*/
		/*
	  if(postId && postId != "null")
		{
	    alert("post has been successful");
	  }
	  */
	}
	
	this.loadFriendDetails = function(uids, callback)
	{
		var q = "SELECT uid, name, pic_square, pic_big FROM user WHERE "+uids;
		FB.Facebook.apiClient.fql_query(q, callback);
	}
	
	this.loadUserDetails = 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.getFriends = function()
	{
		var q = "SELECT name, sex FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1="+FB.Connect.get_loggedInUser()+")";
		FB.Facebook.apiClient.fql_query(q, function(data){ game.response("getFriends", JSON.stringify(data)); });
		//FB.Facebook.apiClient.fql_query(q, function(data){ game.response("getFriends", data); });
	}
	
	this.renderBar = function()
	{
		var content = "";
		
		if(this.connected == 1)
		{
			content += "<a class=\"link\" href=\"javascript:game.authService.logout()\">Logout</a>";
			content += "<a class=\"asset\" href=\"javascript:game.authService.photo.current()\">Asset</a>";
			content += "<div class=\"username\">&nbsp;Level: <span id=\"user-level\">"+game.stats.getLevel()+"</span> Score: <span id=\"user-score\">"+game.stats.getScore()+"</span></div>";
			content += "<div class=\"username\">"+this.username+"</div>";
			content += "<a class=\"service\" href=\"javascript:game.fb.photo.show()\"><img src=\""+this.picture+"\" alt=\"Profile Image\" /></a>";
			content += "<a class=\"service\" href=\"http://www.facebook.com/editapps.php?ref=mb#!/editapps.php?v=allowed\" target=\"_new\"><img src=\"images/facebook.png\" alt=\"Facebook\" /></a>";
		}
		else
		{
			content += "<a class=\"connect\" href=\"javascript:game.sharing.show()\">Connect and share!</a>";
		}
		
		gE('user-bar').innerHTML = content;
	}
	
	this.hideGame = function()
	{
    var u = game.get();
    if(u)
    {
    	var fb = gE('RES_ID_fb_pop_dialog_table');
  		if(fb && game.messages.isVisible() != 1)
      {
        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)
  		{
        game.hidden = 0;
				
  			u.style.width = "800px";
  			u.style.height = "600px";
				
				gE("game").className = "";
				
  			window.scroll(0,0);
      }
    }
	}
}

function CFBTarget(parent)
{
	this.parent = parent;
	
	this.reqs = new CReqs(this);
	
	this.friends = new Array();
	this.uid = null;
	
	this.loadFriends = function()
	{
		var q = "SELECT uid, name, last_name, pic, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1="+FB.Connect.get_loggedInUser()+") ORDER BY last_name";
		FB.Facebook.apiClient.fql_query(q, this.loadFriendsCallback);
	}
	
	this.loadFriendsCallback = function(data)
	{
		if(data == null)
			return;
		
		var c = game.fb.target;
					
		var content = "";
		for(var i = 0; i < data.length; i++)
		{
			c.friends.push(data[i].uid);

			var pic = null;
			
			if(!data[i].pic_square)
				pic = "images/facebook_icon.jpg";
			else
				pic = data[i].pic_square;
			
			content += "<a href=\"javascript:game.fb.target.selectFriend("+data[i].uid+", '"+data[i].name.replace("'", "\\'")+"')\"><img src=\""+pic+"\" alt=\""+data[i].name+"\" /><br />"+data[i].name+"</a>";
		}
		
		game.messages.show("target", "<div id=\"target-friends\"><h2>Select your target</h2><div class=\"friends\">"+ content + "</div></div>");
		
		//TODO: Update controls
	}
	
	this.selectUid = function(uid)
	{
		this.parent.setTargetUid = null;
		this.uid = uid;
		
		var q = "SELECT name FROM user WHERE uid="+uid;
		FB.Facebook.apiClient.fql_query(q, function(data){ mE("target-name").content(data[0].name+" <a href=\"javascript:game.fb.target.show()\">Change target</a>"); });
		
		mE("target").show();

    this.hide();
	}
	
	this.selectFriend = function(uid, name)
	{
    game.maze.photoLink = "";
    
		this.uid = uid;
		
		mE("target-name").content(name+" <a href=\"javascript:game.fb.target.show()\">Change target</a>");
		mE("target").show();
		
		this.hide();
	}
	
	this.show = function()
	{
		this.loadFriends();
	}
	
	this.hide = function()
	{
		game.messages.hide("target");
	}
	
	this.shareFriend = function(target, photoLink)
	{
		//this.hide();
		
		var link = "http://"+game.fb.hostname+"/share.php?stage=stage2&target="+FB.Connect.get_loggedInUser();
		//var link = "http://"+game.fb.hostname+"/stage2";
		
		var msg = "";
		
		var attachment =
			{
			'name': 'INCEPTION: MIND CRIME',
			'href': link,
			'caption': '{*actor*} stole your asset in INCEPTION: MIND CRIME.',
			'description': 'Target them and create a maze to steal their asset and compete with your friends on the leaderboard!',
			/*
			'properties':
				{
				'category':
					{
					'text': 'humor',
					'href': 'http://bit.ly/KYbaN'
					},
				'ratings': '5 stars'
				},
			*/
			'media':
				[{
				'type': 'image',
				'src': 'http://'+game.fb.hostname+'/stage1/images/fb/new.jpg',
				'href': link
				}]
			};
		
		var actionLinks = '[{"text":"Play!", "href":"'+link+'"}]';
	
		//var target = null;
		var prompt = "Would you like to add a message for your friend?";
			
		FB.Connect.streamPublish(msg, attachment, actionLinks, target, prompt, game.fb.shareCallback, true, null);
	}
	
	this.share = function(target, photoLink)
	{
		//this.hide();
		
		var link = "http://"+game.fb.hostname+"/share.php?stage=stage2&maze="+game.maze.mazeId;
		//var link = "http://"+game.fb.hostname+"/stage2";
		
		var msg = "";
		
		var attachment =
			{
			'name': 'INCEPTION: MIND CRIME',
			'href': link,
			'caption': '{*actor*} just stole an asset in INCEPTION: MIND CRIME.',
			'description': 'Use their maze to steal an asset from your target and compete with your friends on the leaderboard!',
			/*
			'properties':
				{
				'category':
					{
					'text': 'humor',
					'href': 'http://bit.ly/KYbaN'
					},
				'ratings': '5 stars'
				},
			*/
			'media':
				[{
				'type': 'image',
				'src': 'http://'+game.fb.hostname+'/stage1/images/fb/new.jpg',
				'href': link
				}]
			};
		
		var actionLinks = '[{"text":"Play!", "href":"'+link+'"}]';
	
		//var target = null;
		var prompt = "Would you like to add a message?";
			
		FB.Connect.streamPublish(msg, attachment, actionLinks, target, prompt, game.fb.shareCallback, true, null);
	}
	
	this.check = function()
	{
    if(this.uid == null && game.setTargetUid == null)
      this.show();
  }
}

