SDNA.fb = function(){};

SDNA.fb.autoLogin = function() {
	$j.ajax({ 
		type:		'POST',
		data:		{fbuid: FB.Facebook.apiClient.get_session().uid},
        url: 		'/ajax/User/FBAutoLogin.jsn/force:' + Math.random().toString(),
        cache: 		false,
        success: 	function( data ){
    		if (data.success) {
    			facebook_onlogin();
    		}
    	},
    	dataType: "json"
	});	
}

SDNA.fb.updatePermissions = function(perms) {
	if (perms != false) {
		if ($j.isArray(perms)) perms = perms.join(',');
		$j.ajax({ type: "POST", url: '/ajax/User/AddFBPermissions.jsn', data: {permissions: perms}, cache: false});
	}
}
SDNA.fb.initFacebookSettingsModal = function(html) {
	$html = $j(html);
	
	$html.find('.facebook_settings form button[name=cancel]')
		.unbind('click.cancel')
		.bind(
		'click.cancel',
		function() { window.location.reload(); }
	);
	
	$html.find('.facebook_settings form').submit(
		function(e) { 
			e.preventDefault();
			$this = $j(this);

			//save the settings
			$j.post(
				$this.attr('action'),
				$this.serialize(),
				function( response ){					
					if( response.success == true ){						
						$this.trigger('submitted');
						$j.modal.close();
						window.location.reload();
					}					
				},
				'json'
			);
		}
	);
}

SDNA.fb.onConnect = function() {
    $j.getJSON(
       '/ajax/User/ConnectWithFacebook.jsnhtm',
		 function( response ){            
            
            //setup dialog options
            var $html = $j(response.html);
            
            Window.pop( $html , {modal:true});
				
				SDNA.Event.trigger('facebook_connect', response );
				
        }        
    );
}

function facebook_onlogin() {
	location.replace("/User/facebookLogin");
}

function facebook_showPostToFB() {
	jQuery('#facebook_post_fieldset').show();
	jQuery('#facebook_loginbutton').hide();
}

SDNA.Event.create('facebook_connect');
