$(document).ready(function() {
	// Get the name of the user on the profile page
	if(window.location['pathname'] == '/myplay/profile'){
		FB.api('/me?fields=first_name,last_name', function(response) {
			$('#profile_user_first_name').html(response['first_name']);
			$('#profile_user_last_name').html(response['last_name']);
		});
	}
});

/*
 * The facebook_onload statement is printed out in the PHP. If the user's logged in
 * status has changed since the last page load, then refresh the page to pick up
 * the change.
 *
 * This helps enforce the concept of "single sign on", so that if a user is signed into
 * Facebook when they visit your site, they will be automatically logged in -
 * without any need to click the login button.
 *
 * @param already_logged_into_facebook  reports whether the server thinks the user
 *                                      is logged in, based on their cookies
 *
 */
function facebook_onload( already_logged_into_facebook )
{
	//console.log("facebook_onload "+already_logged_into_facebook);
	// user state is either: has a session, or does not.
	// if the state has changed, detect that and reload.
	
	FB.getLoginStatus( function( response )
	{
		var is_now_logged_into_facebook = response.status === 'connected';

		// if the new state is the same as the old (i.e., nothing changed)
		// then do nothing
		if( is_now_logged_into_facebook === already_logged_into_facebook )
		{
			return;
		}

		// otherwise, refresh to pick up the state change
		facebook_onlogin();
	});
	
}

function facebook_onlogin(refresh, callback) { 
	//console.log("facebook_onlogin "+refresh);
	// Get first name of the user
	FB.api('/me?fields=first_name', function(response) {
		var name = {};
		name.first_name = response['first_name'];
		
		// Log in
		$.getJSON("/myplay/fblogin", name, function(data){
			if(data.error) {
		      alert(data.error);
		      return;
		    }
	        if($(".welcome-overlay").length==0) { 
	        	$("#login-menu").html(data.loginmenu);
	           	$("#playfeed").html(data.playfeed);
	  	        if(data.login_prompt) {
	  	        	$("body").append(data.login_prompt);
	  	        	dimPage();
	       	    }
	            var playlistCount = $.cookie('playlist');
	            if(playlistCount) {
	            	$("#main-menu .myplay a").html( $.i18n._('My Play') + ' (' + playlistCount + ')');
					$("#main-menu .myplay").addClass('active'); 
				}
				// Change perhaps? Regexp the whole url, now we're assuming a certain no of slashes    
	            strUrl = document.location.href;
	            var Variables = strUrl.split("/");
	   
	            if (Variables[4] == 'register' || Variables[4] == 'login') {
	               window.location="/myplay";
	            }
	            
	            if(callback && typeof(callback) === "function") callback();
	            
	            if (refresh) {
	              	window.location.reload();
	            }
	       }
	
		});
	});
}

/*
 * Our <fb:login-button> specifies this function in its onlogin attribute,
 * which is triggered after the user authenticates the app in the Connect
 * dialog and the Facebook session has been set in the cookies.
 */
function facebook_onlogin_ready()
{
	// In this app, we redirect the user back to index.php. The server will read
	// the cookie and see that the user is logged in, and will deliver a new page
	// with content appropriate for a logged-in user.
	//
	// However, a more complex app could use this function to do AJAX calls
	// and/or in-place replacement of page contents to avoid a full page refresh.
	//refresh_page();
	//facebook_login();
	//alert('onlogin ready');
}

/*
 * 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()
{
	window.location = 'index.php';
}

function facebook_login_box() {
	//console.log("facebook_login_box");
	
	//Call login and upon successul login ON SITE do the same as doLogin() in general.js
	facebook_login(false, function(){
		hideLogin();
		$('#loginboxUrl').trigger('click');
	});
	
}
function facebook_login(refresh, callback) {
	//console.log("facebook_login "+refresh);
	FB.getLoginStatus(function(response) {
		if(response.status !== 'connected') {
			FB.login(function(resp){
				if(resp.authResponse) {
					facebook_onlogin(refresh, callback);
				}
			});
		}else{
			facebook_onlogin(refresh);
		}
	});
}

/*FB.Event.subscribe('auth.login', function(response){
	console.log("AUTH.LOGIN");
	if(response.authResponse)
		facebook_onlogin();
});*/

function facebook_logout()
{
	//console.log("facebook_logout");
	FB.getLoginStatus(function(response) {
		if(response.status === 'connected') {
			FB.logout( function() { window.location="/myplay/logout"; });
		}else{
			window.location="/myplay/logout";
		}
	});
}

function facebook_connect() {
	//console.log("facebook_connect");
	FB.getLoginStatus(function(response) {
		if(response.status === 'connected') {
			facebook_onlogin(true);
		}else{
			facebook_login(true);
		}
	});
}

function facebook_disconnect() {
	//console.log("facebook_disconnect");
	FB.getLoginStatus(function(response) {
		if(response.status === 'connected') {
			FB.logout( function() { window.location="/myplay/facebookDisconnect"; });
		}else{
			window.location="/myplay/facebookDisconnect";
		}
	});
}
