// Global VARs
var api						= null;	// OLD - Not used anymore
var loggedInUserID			= null;
var userProfileData			= null;
var profileData				= null;
var friendsData				= null;
var mbfids					= null;
var viewData				= null;

var friendsRatingsLoaded	= false;
var uid			= null;

var maxDelayForPermsRequest	= 2;
var got_perms				= null;
var submitScore 			= null;
var loginRequiredForGame	= null;

// Global Functions
var loginWidgetSequenceOne		= null;
var loginWidgetSequenceTwo		= null;
var loginWidgetSequenceThree	= null;
var loginWidgetSequenceFinal	= null;

var buildProfileSequenceOne		= null;
var buildProfileSequenceFinal	= null;

var viewSequenceOne				= null;
var viewSequenceFinal			= null;

var pageload 					= true;
//-----------------------------------------------------------

// Activated on FB login from FB.init. First in the load sequence
function mymbLogin() // AKA: initConnectedUserLoginWidget
{
	//console.debug('MYMB FUNCTION INITIATED');
 
	// If MB_AskForPerms cookie not set... set it!
	if( $.cookie('MB_AskForPerms') == null ) {
		$.cookie('MB_AskForPerms', maxDelayForPermsRequest);  
	}

	// Get logged in user data, use the cached data if available
	// OLD FB
	// api = FB.Facebook.apiClient; // Activate FB API client should only need to be done once here
	// api.users_getLoggedInUser(function(uid){loginWidgetSequenceOne(uid);});
	FB.api('/me', function(response) {
		loggedInUser = response;
		loginWidgetSequenceOne(loggedInUser.id);
	});	
	
	// Show give logout button and get users FBID - Load Stage 2
	loginWidgetSequenceOne = function(uid){
		loggedInUserID = uid;

		//console.log('SEQUENCE ONE REACHED');
		$('#action_panel').removeClass('logged_out').addClass('logged_in');
	    
	    if(mymblocater ==  'initGame') {
	    	$("#login_text").hide();
	    	$('#fb-loader').show();
		}
	    
	    checkMBCookies(uid, loginWidgetSequenceTwo);
	}

	// Get all required infomation from FB for logged in user - Load Stage 3
	loginWidgetSequenceTwo = function(){
		//console.log('SEQUENCE TWO REACHED');

		// Get user infomation, use the cached data if available
		if(userProfileData == null){
			// OLD FB
			// api.users_getInfo(loggedInUserID, 'name,pic_square,pic_big,first_name', function(userData){loginWidgetSequenceThree(userData);});
			//console.log('Getting /me...');
			FB.api('/me', function(response) {
				//console.log('FB Query...');
				
				var query = FB.Data.query('select name, pic_square, pic_big, first_name, email from user where uid={0}', response.id);
				query.wait(function(rows) {
					/* --- EXTENDED PERMISSIONS... */
					if( rows[0].email != null ) {
											
						//console.log('Got email and MB_JustGotPerms: ' + $.cookie('MB_JustGotPerms') );
						if( got_perms || $.cookie('MB_JustGotPerms') ) {
							$.cookie('MB_JustGotPerms', null);
							$.cookie('MB_JustGotPerms', null, {path:'/'});
							//console.log('doLogEmail(' + rows[0].email + ');');
							// Should only be done immediately after the user has given us permissions
							if( submitScore )
								console.log('mymbLogin.. submitScore TRUE');
							else
								console.log('mymbLogin.. submitScore FALSE');
										
							doLogEmail(response.id, rows[0].email, submitScore);
						}else{
							
						}
						
						if( mymblocater == 'initGame' ) {	// In game page
							if( loginRequiredForGame && submitScore == true ) {
								console.log('...sendGameCredentials(' + rows[0].first_name+', email: '+rows[0].email+');');
								//sendGameCredentials(rows[0].email, submitScore);
								//if( $.cookie('MB_JustGotPerms') == null) {
									sendGameCredentials(rows[0].first_name, submitScore);
								//}
							}
						}
						
					}else {
						//console.log('1. MB_AskForPerms : ' + $.cookie('MB_AskForPerms' ));
						var updateAskForPerms = (($.cookie('MB_AskForPerms')-1)<0) ? maxDelayForPermsRequest : ($.cookie('MB_AskForPerms') - 1);
						//$.cookie('MB_AskForPerms', updateAskForPerms);
						//}
					
						//console.log('2. MB_AskForPerms : ' + $.cookie('MB_AskForPerms') );
					}
					/* --- EXT PERMs --- */
					got_perms = null;
					$.cookie('MB_JustGotPerms', null);
					$.cookie('MB_JustGotPerms', null, {path:'/'});
					loginWidgetSequenceThree(rows);
				});

			});
			
		}else{
			loginWidgetSequenceThree(userProfileData);
		}
	}

	// This is temp code put in here to remove features. See comented code below to get the old code back.
	loginWidgetSequenceThree = function(userData)
	{
		profile = userData[0];
		
		$('#action_panel div.mymb.logged_in > span').text(profile.first_name);
		$('#action_panel div.mymb img.profile').attr("src", profile.pic_square);
		$('#action_panel div.profile img.profile').attr("src", profile.pic_big);
		
		// Is there anything else to run?
		if(mymblocater == 'initProfile'){
			initProfile();
		}else if(mymblocater == 'initView'){
			initView();
		}else if(mymblocater == 'initFriends'){
			initFriends();
		}else if(mymblocater == 'initHustler'){
			buildScoresStats(); // This is for BBHustler
		}else if(mymblocater == 'homepage'){
			initHPFriendsGameRating();
		}
	}

	// Start building up the profile page - Load Final
//	loginWidgetSequenceThree = function(userData)
//	{
//		userProfileData = userData;
//
//		//console.log('SEQUENCE THREE REACHED'+mbid);
//
//		var name = userData[0].first_name;
//		var pic  = userData[0].pic_square;
//		$('#login-picture').attr("src",pic);
//		$('#login-name').html(name);
//		$('#login-name').append(mbid);
//
//		var noCache = Math.round(Math.random() * 1000);
//
//		// use the cached data if available
//		if(profileData == null){
//			$.getJSON( "/user/profile/"+mbid+"?"+noCache, null, loginWidgetSequenceFinal);
//		}else{
//			loginWidgetSequenceFinal(profileData);
//		}
//	}

	// Work out medals and finaly show profile widget - Done - Noe run anyrhing else you have to
//	loginWidgetSequenceFinal = function(data)
//	{
//		profileData = data;
//
//		//console.log('SEQUENCE FINAL REACHED'+mbid);
//
//		// Get user total awards
//		var awardsEntry = '';
//		for( var i in data['awards']['medals'] )
//		{
//			$('#login-award_'+i).html(data['awards']['medals'][i]);
//		}
//
//		$('#login-loader').hide();
//		$('#login-profile').fadeIn(550);
//
//		// Is there anything else to run?
//		if(mymblocater == 'initProfile'){
//			initProfile();
//		}else if(mymblocater == 'initView'){
//			initView();
//		}else if(mymblocater == 'initFriends'){
//			initFriends();
//		}
//	}
}

// Used to create users profiles for viewing, trigered by the mymbLogin function above
function initView()
{
	//console.log('INIT VIEW');

	// No need to cache this will be unique to each user
	// OLD FB
	// api.users_getInfo(viewUID, 'uid,first_name,name,pic,pic_square', function(userdata){viewSequenceOne(userdata);});
	var query = FB.Data.query('select uid,first_name,name,pic,pic_square from user where uid={0}', viewUID);
	query.wait(function(rows) {
		viewSequenceOne(rows);
	});

	viewSequenceOne = function(userdata)
	{
		//console.log('VIEW SEQUENCE ONE REACHED');

		viewData = userdata;

		$('#profile_loggedin').fadeIn(550);
		$('#profilePicture').attr("src",userdata[0].pic);
		$('#profileName').html(userdata[0].name);
		$('.profile_boxout_mid h1').append(userdata[0].name);

		var noCache = Math.round(Math.random() * 1000);
		$.getJSON( "/user/profile/"+viewMBID+"?"+noCache, null, viewSequenceFianl);
	}

	viewSequenceFianl = function(data)
	{
		//console.log('VIEW SEQUENCE FINAL REACHED');

		// Get user total awards
		var awardsEntry = '';
		for(var i in data['awards']['medals']){
			$('#award_'+i).append(data['awards']['medals'][i]);
		}

		// Calculate Rank and Whereami
		//$('#profileRank').append(data['awards']['rank']);
		//$('#whereami').attr("href","/medals/site/alltime/"+(Math.floor(data['awards']['rank'] / 100) + 1) +"#"+viewMBID);

		for( var i in data['games']){
			gameInfo = data['games'][i];

			if(gameInfo.user[viewMBID] != undefined && gameInfo['user'][viewMBID]['score'] > 0){
				// Make Game Container
				gameEntry = '<div class="game_container">';

				// Make Game Info Title and Image
				gameEntry += '<div class="game_info">';
				gameEntry += '<a href="/games/'+i+'"><img src="/games/screenshots/'+i+'.gif" /></a>';
				gameEntry += '<a href="/games/'+i+'">'+gameInfo["title"]+'</a>';
				gameEntry += '</div>';

				// Make Friends List for Game
				thisScore = gameInfo['user'][viewMBID]['score'];
				thisfbid = viewUID;

				gameEntry += "<div class='game_scores'><ul>";
				gameEntry += "<li><a href='/profile/"+viewMBID+"' class='userThumb'><img src='"+viewData[0].pic_square+"' /></a>"; // Profile Image
				if(gameInfo['user'][viewMBID]['award']){
					gameEntry += " <img src='/layout/award_"+gameInfo['user'][viewMBID]['award']+".png' id='award-pic' />"; // Awards
				}
				gameEntry += " <a href='/profile/"+viewMBID+"' id='name'>"+viewData[0].first_name+"</a><span>"+thisScore+"</span></li>";
				gameEntry += '</ul>';
				gameEntry += '</div><div class="clear_both"></div>'; // End Game Scores
				gameEntry += '</div>'; // End Game Container

				$('#profile_gameslist').append(gameEntry);
			}
		}

		$('#selenium').html('1');
	}
}

// Used to create the profile page, trigered by the mymbLogin function above
function initProfile()
{
	//console.log('INIT BUILD '+mbid);

	$('#not-logged-in').hide();
	$('#profile-loader').fadeIn(300);
	$('#your_profile_games').fadeIn(300);

	mbfids = $.cookie("MBFRIENDS_FBS");

	// use the cached data if available
	if(friendsData == null){
		// OLD FB
		// api.users_getInfo(loggedInUserID+mbfids, 'uid,first_name,name,pic,pic_square', function(userdata){buildProfileSequenceOne(userdata);});
		FB.api({method:'fql.query',
				query: 'SELECT uid,first_name,name,pic,pic_square FROM user WHERE uid IN ('+loggedInUserID+mbfids+')'},
			function(userdata) {
				buildProfileSequenceOne(userdata);
			}
		);
	}else{
		buildProfileSequenceOne(friendsData);
	}

	buildProfileSequenceOne = function(userdata)
	{
		//console.log('BUILD SEQUENCE ONE REACHED'+mbid);

		friendsData = userdata;
		getUserData(userdata); // Proccess profile data in to array

		$('#profile_loggedin').fadeIn(550);
		$('#profileName').html(userDataStorage[loggedInUserID].name);
		$('#profilePicture').attr("src",userDataStorage[loggedInUserID].pic);
		$('#profile-loader').fadeOut(300);

		// Get games and awards
		if(profileData == null){
			var noCache = Math.round(Math.random() * 1000);
			$.getJSON( "/user/profile/"+mbid+"?"+noCache, null, buildProfileSequenceFinal);
		}else{
			buildProfileSequenceFinal(profileData);
		}
	}

	// this function does the actual work. It can take data from either the ajax call, or the cached data.
	buildProfileSequenceFinal = function(data, textStatus)
	{
		//console.log('BUILD SEQUENCE FINAL REACHED'+mbid);

		profileData = data;

		//Get user total awards
		var awardsEntry = '';
		for( var i in data['awards']['medals'] )
		{
			$('#award_'+i).html(data['awards']['medals'][i]);
		}

		//Calculate Rank and Whereami
		// $('#profileRank').append(data['awards']['rank']);
		$('#whereami').attr("href","/medals/site/alltime/"+(Math.floor(data['awards']['rank'] / 100) + 1) +"#"+mbid);

		for( var i in data['games'])
		{
			gameInfo = data['games'][i];

			// Make Game Container
			gameEntry = '<div class="game_container">';

			// Make Game Info Title and Image
			gameEntry += '<div class="game_info">';
			gameEntry += '<a href="/games/'+i+'"><img src="/games/screenshots/'+i+'.gif" /></a>';
			gameEntry += '<a href="/games/'+i+'">'+gameInfo["title"]+'</a>';
			gameEntry += '</div>';

			// Make Friends List for Game
			var l = 0;
			for(var frmbid in gameInfo['user'])
			{
				thisScore = gameInfo['user'][frmbid]['score'];
				thisfbid = (frmbid == mbid) ? loggedInUserID : MBIDtoFBID(frmbid) ;

				////console.log(frmbid+' == '+mbid);
				////console.log(thisfbid);
				////console.log(loggedInUserID);

				if(l == 0)
				{
					gameEntry += "<div class='game_scores'><ul>";
				}
				if(l == 3)
				{
					gameEntry += '</ul><div class="game_more" id="'+i+'-game_more"><ul>';
				}
				l++;

				gameEntry += "<li><span class='count'>"+l+"</span><a href='/profile/"+frmbid+"' class='userThumb'><img src='"+userDataStorage[thisfbid].pic_square+"' /></a>"; // Profile Image

				if(gameInfo['user'][frmbid]['award'])
				{
					gameEntry += " <img src='/layout/award_"+gameInfo['user'][frmbid]['award']+".png' id='award-pic' />"; // Awards
				}

				gameEntry += " <a href='/profile/"+frmbid+"' id='name'>"+userDataStorage[thisfbid].first_name+"</a><span>"+ thisScore+"</span>";

				if(frmbid == mbid){
					gameEntry += '<a href="#" onClick="postScoreToWall(\''+i+'\', \''+gameInfo["title"]+'\', '+thisScore+');return false;" class="postowall"><img src="/layout/fb_share_button.png" /></a>';
				}

				gameEntry += "</li>";
			}

			if(l <= 0)
			{
				gameEntry += "<li>You've not played any games since logging into MyMB. When you start playing and recording scores, you'll be able to keep track of how you stack up against your friends.</li>";
			}

			if(l > 3)
			{
				gameEntry += '</ul></div><a href="#" onclick="slidit(\''+i+'\');return false;" class="game_more_button">more</a>'; // End More Slide Out
			}
			else
			{
				gameEntry += '</ul>';
			}

			gameEntry += '</div><div class="clear_both"></div>'; // End Game Scores
			gameEntry += '</div>'; // End Game Container

			$('#profile_gameslist').append(gameEntry);
		}

		$('#selenium').html('1');
	}
}

// Used to create the profile page, trigered by the mymbLogin function above
function initFriends()
{
	var mbfids  = $.cookie("MBFRIENDS_FBS");
	var mbids	= JSON.parse(unescape($.cookie("MBFRIENDS")));
	
	//console.log('initFriends...');
/*
	//OLD FB
	api.users_getInfo(loggedInUserID+mbfids, 'uid,first_name,name,pic,pic_square', function(userdata)
	{
		for(var user in userdata){
			if(loggedInUserID != userdata[user].uid){
				friend = '<li><a href="/profile/'+mbids[userdata[user].uid]+'"><img src="'+userdata[user].pic+'" />'+userdata[user].name+'</a></li>';
				$('#friends').append(friend);
			}
		}

		if(userdata.length <= 1){
			$('#alt-message').show();
		}

		$('#selenium').html('1');
	});
*/
	FB.api({method:'fql.query',
		query: 'SELECT uid,first_name,name,pic,pic_square FROM user WHERE uid IN ('+loggedInUserID+mbfids+')'},
		function(userdata) {
			for(var user in userdata){
				if(loggedInUserID != userdata[user].uid){
					friend = '<li><a href="/profile/'+mbids[userdata[user].uid]+'"><img src="'+userdata[user].pic+'" />'+userdata[user].name+'</a></li>';
					$('#friends').append(friend);
				}
			}
			if(userdata.length <= 1){ $('#alt-message').show(); }

			$('#selenium').html('1');
		}
	);
}

// Used to log you out, trigered by FB logout
function mymbLogout()
{
	FB.logout(function(response)
	{
	    // user is logged out
	    // redirect to local logout script
			
		if(loggedInUserID != undefined){
			//console.log('cleaning the last');
	
			api				= null;
			loggedInUserID	= null;
			userProfileData	= null;
			profileData		= null;
			friendsData		= null;
			mbfids			= null;
			viewData		= null;
			aFBIDtoMBID		= -1;
			aMBIDtoFBID		= -1;
			userDataStorage = new Object();
			mbid			= null;
	
			//Hide profile panel if displayed.
			$('#action_panel div.profile > div').css('display') === 'block'
				&& $('#action_panel div.mymb.logged_in a[rel=profile]').click();
			
			//Switch action panel state to logged out.
			$('#action_panel').removeClass('logged_in').addClass('logged_out');

			$('#login-name').html('');
			$('#login-award_gold').html('');
			$('#login-award_silver').html('');
			$('#login-award_bronze').html('');
			$('#login-loader').hide();
	
			// Is there anything else to run?
			if(mymblocater == 'initProfile'){
				profileLogout();
			}else if(mymblocater == 'homepage'){
				hpGameLogout();
			}
	
			$('#selenium').html('0');
		}
		
	});

	$('#login-button').show();

	checkMBCookies(false);
}

function profileLogout()
{
	$('#your_profile_games').hide();

	$('#profile_loggedin').hide();
	$('#profileName').html('');
	$('#profilePicture').attr('');

	$('#award_gold').html('');
	$('#award_silver').html('');
	$('#award_bronze').html('');

	$('#profile_gameslist').html('');

	$('#not-logged-in').show();
}

function hpGameLogout()
{
    $("#friends-ratings").slideUp("slow");  
}

function initHPFriendsGameRating()
{
	if( $("#friends-game-rating").html() == "" && !friendsRatingsLoaded ) {
	    $.ajax({type: "GET",url: "/games/latestfriendsgameratings/ajax",dataType: "html",
			success: function(data){
				$("#friends-game-rating").html(data);
				mousebreaker_tooltip('#friends-game-rating ul li.friends-game-rating','tooltipforfriends', function(){
					var ele = $(".tooltip_friends_ratings");
					if( data.indexOf("<!-- No friends ratings -->", 0) != "1" ) {
						console.log("Have friend rating");
						$("#friends-ratings").slideDown("slow");	// Show friend's grid
						friendsRatingsLoaded = true;
						for(i=0; i < ele.length; i++) {
							var usethis = "tooltipforfriends"+i;
							var ele2 = $(usethis);
							// OLD FB: FB.XFBML.Host.parseDomElement(document.getElementById(usethis));
							FB.XFBML.parse(document.getElementById(usethis));
						}
						if( ele.length > 5 ) {
							$('#friends-game-rating-carousel-nav .fgrcnext').removeClass('disabled');
						}
						$(function() {
							$(".friends-game-rating-carousel").jCarouselLite({ visible: 5, btnNext: ".fgrcnext", btnPrev: ".fgrcprev", scroll:5, speed:900, circular: false });
						});
					}else { console.log("No friend rating"); }
				});
			}
		});
	}
}
