function afterGrantAccess(uid)
{
	save_session();
}

function save_session()
{
	var user_id = '';
	var access_token = '';
	
    FB.getLoginStatus(function(response) 
    {
	    if (response.authResponse) 
	    {
	      // logged in and connected user
	      
	      //alert(response.authResponse.userID);
	      
	      user_id = response.authResponse.userID
	      access_token = response.authResponse.accessToken;
	      
	    } else {
	      // no user session available, someone you dont know
	      var authresponse = FB.getAuthResponse();
	      
	      user_id = authresponse.userID
	      access_token = authresponse.accessToken;
	      
	    }
	});
    
    $.ajax(
    {
        type: "POST",
        url: '/ajax.php',
        data:{
    		sessionKey:access_token,
    		uid:user_id,
    		form_event:'fb_store_session'
    		},
        dataType: "text",
        async: false,
        time: 10,
        success: function( msg )
        {
    		if(msg == 'falsefalse')
    		{
    			if(typeof account_not_created == 'function') {
    				return account_not_created();
    			}
    		}
    		else
    		{
    			window.location = window.location;
    		}
    		$('#fb_connect').hide();
    		$('#fb_disconnect').show();
        }
    });
    return false;
}

function facebook_disconnect()
{
	var user_id = '';
	var access_token = '';
	
    FB.getLoginStatus(function(response) 
    {
	    if (response.authResponse) 
	    {
	      // logged in and connected user
	      
	      //alert(response.authResponse.userID);
	      
	      user_id = response.authResponse.userID
	      access_token = response.authResponse.accessToken;
	      
	    } else {
	      // no user session available, someone you dont know
	      var authresponse = FB.getAuthResponse();
	      
	      user_id = authresponse.userID
	      access_token = authresponse.accessToken;
	      
	    }
	});
    
    $.ajax(
    {
        type: "POST",
        url: '/ajax.php',
        data:{
    		sessionKey:access_token,
    		uid:user_id,
    		form_event:'fb_destroy_session'
    		},
        dataType: "text",
        async: false,
        time: 10,
        success: function( msg )
        {
    		$('#fb_connect').show();
        	$('#fb_disconnect').hide();
        }
    });

	return false;
}

function facebook_permission_granted()
{
	save_session();
	refresh_page();
}

function facebook_permission_denied()
{
	alert('This application requires offline access to run, you may want to perform manual registration.');
}

/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page() {
  //
}

function facebook_registration_connect() 
{
	var uid = FB.Connect.get_loggedInUser(); 
	save_session(uid);
	
	get_user_info(uid);
	/*
	var permission = "offline_access";
	FB.Facebook.apiClient.users_hasAppPermission(permission,
		function(result) {
			if(result)
			{
				//Do nothing
				var uid = FB.Connect.get_loggedInUser();
      			//Cool we have permission
      			get_user_info(uid);
			}
			else
			{
		      	FB.Connect.showPermissionDialog(permission,function () {
		      		if(permission)
		      		{
		      			var uid = FB.Connect.get_loggedInUser();
		      			//Cool we have permission
		      			get_user_info(uid);
		      		}
		      		else
		      		{
		      			//Just use the facebook proxy
		      			alert('Permission required for facebook features');
		      		}
		      	});
			}
	});
	*/
	 	//alert(c['current_location']['city']);
}


function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function get_user_info(uid)
{
	$('#fb_uid').val(uid);
	
	$('#fb_connect').hide();
	$('#fb_disconnect').show();
	
	FB.api(
      {
        method: 'fql.query',
		query: "SELECT uid,birthday_date,current_location,first_name,last_name,"
					+"hometown_location,sex,education_history,name,email,interests,about_me"
					+", family"
					+" FROM user WHERE uid =" + uid, 
		},
	function(result) {
		var res = result; 
		
		var res_dump = dump(res);

		var c = res[0];
		
		if(isset(c['birthday_date']) && c['birthday_date'] != null)
		{
		 	var date = c['birthday_date'].split('/');
		 	var birth_day = date[1];
		 	var birth_month = date[0];
	
		 	$('#birth_day').val(parseInt(birth_day));
		 	$('#birth_month').val(parseInt(birth_month));
		}
	
		if(isset(c['first_name']))
		{
	 		$('#first_name').val(c['first_name']);
	 		$('#preferred_name').val(c['first_name']);
		}
	
		if(isset(c['last_name']))
		{
	 		$('#last_name').val(c['last_name']);
		}
	
		if(isset(c['email']))
		{
	 		$('#email').val(c['email']);
		}
	
		if(isset(c['sex']))
		{
		 	if(c['sex'] == "male")
		 	{
		 		$('#gender_male').attr("checked","checked");
		 	}
		 	else
		 	{
		 		$('#gender_female').attr("checked","checked");
		 	}
		}
	
		if(isset(c['hometown_location']))
		{
			if(isset(c['hometown_location']['country']))
			{
	 			$('#country_of_origin').val(c['hometown_location']['country']);
			}
		}
	
		if(isset(c['current_location']))
		{
			if(isset(c['current_location']['city']))
			{
	 			$('#city').val(c['current_location']['city']);
			}
		}
		
	 	if(c['education_history'] != null && isset(c['education_history'][0]['name']))
	 	{
		 	$('#school_in_nz').val(c['education_history'][0]['name']);
	 	}
	/*
		var about_me = "";
		if(isset(c['about_me']))
		{
			about_me = c['about_me'];
		}
	
		if(isset(c['interests']))
		{
			about_me = "I am interested in "+c['interests'];
		}
	
		$('#about_me').val(about_me);
	*/
	});
}

/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
  // Load the feed form
          FB.Connect.showFeedDialog(form_bundle_id, template_data);
          //FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);

      // hide the "Loading feed story ..." div
      ge('feed_loading').style.visibility = "hidden";
}


function facebook_onlogin(from_click)
{
	FB.getLoginStatus(function(response) 
    {
	    if (response.status == "connected") 
	    {
	      
	      var user_id = response.session.uid
	      var access_token = response.session.access_token;
    	  var sessionKey= response.session.session_key;

		  if ( from_click )
	      {
		      $.ajax(
		      {
		            type: "POST",
		            url: '/ajax.php',
		            data:{
		        		sessionKey: sessionKey,
		        		uid: user_id,
		        		form_event:'fb_store_session'
		        		},
		            dataType: "text",
		            async: false,
		            time: 10,
		            success: function( msg )
		            {
		        		if(msg == 'falsefalse')
		        		{
		        			return account_not_created();
		        		}
		        		else
		        		{
		        			window.location = window.location;
		        		}
		        		
		        		$('#fb_connect').hide();
		        		$('#fb_disconnect').show();
		            }
		        });
	        }
			else
			{
				if (window.location.href.indexOf("Registration-Form") != -1)
				{
					get_user_info(user_id);
				}
				$('#fb-reg-btn').html('<a href="#" onclick="facebook_onlogin(true)"><img src="/images/fb_button.png" border="0" /></a>');
			}
	     }
    });
}
