function fbw()
{
	var authorized = 0;
	var connected = 0;
	var xreqs = new reqs();
		
	this.init = function(sAuth)
	{	
		authorized = sAuth;
		
		this.initFB();
	}
	
	this.initFB = function()
	{
		this.showLoader();
		
		FB.init(xconfig.apiKey, 'xd_receiver.htm');

/*
		FB.ensureInit(function(){
			FB.Connect.ifUserConnected(xfb.login, xfb.notConnected);
		});
*/		
		FB.ensureInit(function(){
			FB.Connect.get_status().waitUntilReady(function(status)
			{
				switch(status)
				{
					case FB.ConnectState.appNotAuthorized:
					case FB.ConnectState.userNotLoggedIn:
						xfb.notConnected();
				}
			});
			
			FB.Connect.ifUserConnected(function(){ xfb.loginTimer(); });
		});
	}

	this.connect = function(callback)
	{			
		FB.Connect.requireSession(callback, null, true);
	}
	
	this.notConnected = function()
	{
		this.hideLoader();

    xunity.fbStatusChange();

		if(authorized)
			this.auth();
	}
	
	this.getConnected = function()
	{
		return connected;
	}
	
	this.loginTimer = function()
	{
		//check for facebook cookies and then log user in
		var cookie = getCookie(xconfig.apiKey+"_user");
		if(cookie == "")
		{
			setTimeout(function(){ xfb.loginTimer(); }, 100);
			return;
		}
		
		this.login();
			
		this.hideLoader();
	}

	//login with facebook
	this.login = function()
	{
		xreqs.get("?cmd=fb.login", xfb.postLogin);
	}
	
	this.postLogin = function()
	{
		connected = 1;
		xunity.fbStatusChange();
		xfb.auth();
	}
		
	//notconnected users use this
	/*
	this.register = function()
	{			
		xreqs.get("?cmd=user.register", function(){ xfb.auth(); });
	}
	*/
	
	this.auth = function()
	{
		this.hideLoader();
		this.showInfo();
		
		xunity.show();
	}
		
	//general logout from the site
	this.logout = function()
	{
    FB.Connect.logout();

		xreqs.get("?cmd=user.logout", null);
		
		authorized = 0;
		connected = 0;
		
		xunity.fbStatusChange();
		
		this.hideInfo();
	}
		
	this.hideLoader = function()
	{
		gE('loader').style.display = "none";
	}
	
	this.showLoader = function()
	{
		gE('loader').style.display = "block";
	}
	
	this.hideInfo = function()
	{
		gE('info').style.display = "none";
	}
	
	this.showInfo = function()
	{
		if(!connected)
			gE('info-fb').style.display = "none";
		else
			gE('info-fb').style.display = "block";
		
		gE('info').style.display = "block";
	}

	this.wallPost = function(msg, attachment, links, target, prompt)
	{
		if(!connected)
		{
			this.connect(function(){ xfb.wallPost(messsage, attachment, links, target, prompt); });
			return;
		}
		
		FB.Connect.streamPublish(msg, attachment, links, target, prompt, xfb.wallPostCallback, true, null);
	}
	
	this.wallPostCallback = function(postId, exception)
	{
		xunity.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");
	  }
	  */
	}
}

var xfb = new fbw();
