// FM Contest Facebook JS Auth
// Version: 2.3
// Updated: Nov 23 2010
// By: Jshaw
	// code incremented no change

FB.Event.subscribe('auth.authResponseChange', function(response) {
	
	if (response.authResponse) {
	
		if (response.status === "connected"){
					
			if(redirectUrl){
				window.location = '/action/facebooklogin/?redirectUrl=/'+redirectUrl;
			}else{
				switch(basepage){
					case 'login':
						window.location = '/action/facebooklogin/?redirectUrl=/home';
					break;
					default:
						window.location = '/action/facebooklogin/?redirectUrl=/'+basepage+'/'+subpage;
				}
			}
		}else{
			window.location = '/action/v2/logout';
		}
	}else{
	  // The user has logged out, and the cookie has been cleared
	  window.location = '/action/v2/logout';
	}
});

FB.getLoginStatus(function(response){
	
	if (response.authResponse){
            
		if (response.status === "connected"){

        	// need to check if the user is logged in to MF
    		jsonRequest('users.getLoggedInUser', {},
			    function(result) { 
			    	if(result.id == 1){
			    	
				    	if(redirectUrl){
							window.location = '/action/facebooklogin/?redirectUrl=/'+redirectUrl;
						}else{
							switch(basepage){
								case 'login':
									window.location = '/action/facebooklogin/?redirectUrl=/home';
								break;
								default:
									window.location = '/action/facebooklogin/?redirectUrl=/'+basepage+'/'+subpage;
							}
													
						}
			    	}else{
			    	
			    	}
			    },function(exception){ 
			    	//console.log(exception); 
				});
        }else {
        	logoutUser();
        }
	}else{
		//console.log("logged out of facebook");
	}
},true);

function logoutUser(){
	FB.getLoginStatus(function(response) {
  		if (response.authResponse) {
			FB.logout(function(response) {
				location.href='/action/v2/logout';
			});
		}else{
			location.href='/action/v2/logout';
  		}
	},true);
}

function loginWithFacebook() {
	FB.login(function(response) {
			if (response.authResponse) {
			if (response.perms) {
		      	// logged in and granted some permissions
			} else {
				// logged in, but did not grant any permissions
			}
		} else {
		    // user is not logged in
		}
	}, {scope:'email,publish_stream'});                    		
}

//this is sending a message if the users fb account is inactive with this site.
/*
<fm:Switch value="{$$get.user}">
	<fm:Case value="inactive">
		var dialog = {
		    method: 'fbml.dialog',
		    fbml: '<h1>Your Facebook Account on this website is currently inactive</h1>',
		    width: 400,
		    height: 100
		  };
		  FB.ui(dialog);
	</fm:Case>
</fm:Switch>
*/
