/*
 * Combines N specified functions into a single function.
 * Specified functions are executed in the order passed.
 *
 * @return function Function that calls the specified functions when invoked.
 * @author Paul Morris
 */
function combineFunctions() {
	var args = Array.prototype.slice.call(arguments); //IE can't iterate function arguments.
	
	return function() {
		for (var arg in args)
			args[arg] instanceof Function && args[arg]();
	};
}

// Functions to vars
var aFBIDtoMBID = -1;
var aMBIDtoFBID = -1;
var checkMBCookies	= null;
var userDataStorage = new Object();
var mbid			= null;

//-----------------------------------------------------------
checkMBCookies = function(uid, callback)
{
	// if you're not logged in, clear out your MBID and MBFRIENDS cookies
	if (uid==false || 
		( $.cookie('MBID_FBID') && $.cookie('MBID_FBID')!= uid) 
		){
		$.cookie('MBID', null);  
		$.cookie('MBID_SIG', null);
		$.cookie('MBID_FBID', null);
		$.cookie('MBFRIENDS', null);
		$.cookie('MBFRIENDS_SIG', null);
		$.cookie('MBFRIENDS_FBS', null);
		$.cookie('MBFRIENDS_FBS_SIG', null);
		$.cookie('MB_AskForPerms', null);
		$.cookie('MB_JustGotPerms', null);
		$.cookie('MB_GamePermRequestShown', null);
		
		// delete cookie on '/' path just to be sure
		$.cookie('MBID', null, {path:'/'});  
		$.cookie('MBID_SIG', null, {path:'/'});
		$.cookie('MBID_FBID', null, {path:'/'});
		$.cookie('MBFRIENDS', null, {path:'/'});
		$.cookie('MBFRIENDS_SIG', null, {path:'/'});
		$.cookie('MBFRIENDS_FBS', null, {path:'/'});
		$.cookie('MBFRIENDS_FBS_SIG', null, {path:'/'});
		$.cookie('MB_AskForPerms', null, {path:'/'});
		$.cookie('MB_JustGotPerms', null, {path:'/'});
		$.cookie('MB_GamePermRequestShown', null, {path:'/'});
		
//		console.log('cleared');
		return;
	}
//	console.log("cookies ok");

	// if you're logged in, and you have MBID and MBFRIENDS cookies, you're fine.
	if ($.cookie('MBID') &&
	    $.cookie('MBID_SIG') &&
	    $.cookie('MBFRIENDS') &&
	    $.cookie('MBFRIENDS_SIG') &&
	    $.cookie('MBFRIENDS_FBS') &&
	    $.cookie('MBFRIENDS_FBS_SIG'))
        {
			// now if set load the callback funcation
			//console.log('here');
			//console.log($.cookie("MBID"));
			finishBakingCookies(callback);
			return;
	}

	
	// else if you're logged in but DON'T have cookies, then let's get some
	// OLD FB
/*
 	api.friends_getAppUsers(function(friends){
			//console.log('there');
			//console.log($.cookie("MBID"));
            $.post('/user/login',{friends:JSON.stringify(friends)}, function(){finishBakingCookies(callback)}, 'JSON');
        });
*/		
	var query = FB.Data.query("select uid " +
								"from user " + 
								"where uid in " + 
									"(select uid2 from friend where uid1 = "+uid+") " + 
								"and is_app_user = 1"
								);
	query.wait(function(friends) {
		$.post('/user/login',{friends:JSON.stringify(friends).replace(/{"uid":"/gi, '').replace(/"}/gi, '')}, function(){finishBakingCookies(callback)}, 'JSON');
	});
 }

function finishBakingCookies(callback)
{
	//Raise logged in event.
	$(window).trigger('MB.login');
	
	mbid = $.cookie("MBID");

	// now if set load the callback funcation
	if(callback != null){
		callback();
	}
}

// Used on the profile pages to slide the hidden names of your friends scores up and down.
function slidit(id){
    $('#' + id + '-game_more').slideToggle('fast');
}

// Used to store user data for the profile page
function getUserData(data){
    for(var i = 0; i < data.length; i++)
    {
		userDataStorage[data[i]['uid']] = data[i];
    }
    return;
}

function MBIDtoFBID(mbid){
	// populate the global MBIFtoFBID and FBIDtoMBID hashes if
	// they're not already setup
	if (aFBIDtoMBID ==-1 || aMBIDtoFBID==-1){

		aMBIDtoFBID = new Object();
		aFBIDtoMBID = eval('('+$.cookie('MBFRIENDS')+')');

		for (var thisfbid in aFBIDtoMBID ){
			thismbid = aFBIDtoMBID[thisfbid];
			aMBIDtoFBID[thismbid] = thisfbid;
		}
	}
	return aMBIDtoFBID[mbid];
}

function postScoreToWall(gameUniuqName, gameTitle, score)
{
/*  OLD FB
	api = FB.Facebook.apiClient;
	var attachment = {'name':gameTitle,
					  'href':'http://www.mousebreaker.com/games/'+gameUniuqName,
					  'description':'My best ever score on '+gameTitle+' is '+score+'! Reckon you can beat that?',
					  'media':
						[{'type':'image',
						  'src':'http://www.mousebreaker.com/games/screenshots/'+gameUniuqName+'.gif',
						  'href':'http://www.mousebreaker.com/games/'+gameUniuqName}]
					 };

	var actionLinks = [{ 'text': 'Play '+gameTitle, 'href':'http://www.mousebreaker.com/games/'+gameUniuqName}];

	FB.Connect.streamPublish('', attachment, actionLinks, null, 'Brag about your score on Facebook...', null, true);
*/
	FB.ui( {
		method: 'feed',
		name: gameTitle,
		link: 'http://www.mousebreaker.com/games/'+gameUniuqName,
		caption: 'Play '+gameTitle,
		description: 'My best ever score on '+gameTitle+' is '+score+'! Reckon you can beat that?',
		picture: 'http://www.mousebreaker.com/games/screenshots/'+gameUniuqName+'.gif'
	},
	function(response) {
		if (response && response.post_id) {
			console.log('Post published!');
		} else {
			//console.log('Post was not published.');
		}
	}
);
	
}

function postMedalToWall(gameUniuqName, gameTitle, score, medal)
{
	$('#flashcontent').css("visibility","hidden");
	/*
	// OLD FB
	api = FB.Facebook.apiClient;
	var attachment = {'name':gameTitle,
					  'href':'http://www.mousebreaker.com/games/'+gameUniuqName,
					  'description':'I just got a '+medal+' medal for a score of '+score+' on '+gameTitle+' on Mousebreaker. Think you can beat me?',
					  'media':
						[{'type':'image',
						  'src':'http://www.mousebreaker.com/layout/award_'+medal+'.png',
						  'href':'http://www.mousebreaker.com/games/'+gameUniuqName}]
					 };

	var actionLinks = [{ 'text': 'Play '+gameTitle, 'href':'http://www.mousebreaker.com/games/'+gameUniuqName}];
	FB.Connect.streamPublish('', attachment, actionLinks, null, 'Brag about your medal on Facebook...', function(){$('#flashcontent').css("visibility","visible");}, true);
	*/
	FB.ui( {
			method: 'feed',
			name: gameTitle,
			link: 'http://www.mousebreaker.com/games/'+gameUniuqName,
			caption: 'Play '+gameTitle,
			description: 'I just got a '+medal+' medal for a score of '+score+' on '+gameTitle+' on Mousebreaker. Think you can beat me?',
			picture: 'http://www.mousebreaker.com/layout/award_'+medal+'.png'
		},
		function(response) {
			if (response && response.post_id) {
				//$('#flashcontent').css("visibility","visible");
				console.log('Post was published!');
			} else {
				//console.log('Post was not published.');
			}
			$('#flashcontent').css("visibility","visible");
		}
	);
	
	
}


function doFBLogin()
{
	FB.login(function(response) {
		if (response.authResponse) {
			console.log('logged in');
			mymbLogin();
		} else {
			// user is not logged in
			console.log('Login canceled');
		}
	}, {scope: 'email, user_birthday'});
}

/*
 * Used to check the permissons allowed
 */
function hasPermission(response, perm) {
	//--var begin = response.perms.indexOf('extended":[') + 11;
	//--var end = response.perms.indexOf(']', begin);
	var begin = response.perms.indexOf('extended":[') + 11;
	var end = response.perms.indexOf(']', begin);
	if( begin == 0 ) {
		begin = response.indexOf('perms":') + 7;
		end = response.indexOf('}', begin);
	}
	
	//--var perms = response.perms.substring(begin, end);
	var perms = response.perms.substring(begin, end);
	return (perms.indexOf(perm) != -1);
}




/* TESTING SCRIPT */

function checkiFrameAdBlocks() {
	//DOESN'T WORK!
	console.log('checkiFrameAdBlocks()...');
	var adBlocked = false;
	$(".iframe_ad").each( function(index) {
		console.log('adiFrame..');
		console.log('id: '+ $(this).attr('id')+', height: '+$(this).height());
		console.log('contents: ' + $(this).contents() );

		//if( $('iframe', this).is(':visible') ) {
/*
 		if( typeof($('iframe', this).(document).applify()) == "undefined" ) {
			//adBlocked = true;
			console.log('ADBLOCKER: iframe ad is blocked: FALSE!');
		}else {
			console.log('ADBLOCKER: iframe ad is blocked: TRUE!');
		}
*/
	});
	//DOESN'T WORK!
	if(typeof(window.applify)=="undefined")   
	{   
	    //They're blocking ads, do something else.  
		console.log('Applifier Ad Blocked!');
	} else {
		console.log('Applifier Ad NOT Blocked!');
	}
}

function detectAdBlock() {
	
	$(".img_ad").each( function(index) {
		if( $(this).height() == 0 ) {
			console.log('ADBLOCKER: Image ad is blocked: TRUE!');
		}else {
			console.log('ADBLOCKER: Image is blocked: FALSE!');
		}
	});
	
	$(".mpu_ad").each( function(index) {
		if( $(this).height() == 0 ) {
			console.log('ADBLOCKER: MPU ad is blocked: TRUE!');
		}else {
			console.log('ADBLOCKER: MPU is blocked: FALSE!');
		}
	});
	
	//setTimeout( "checkiFrameAdBlocks()", 5000);	
}
$(document).ready( function(){
	//detectAdBlock();
});
/* END TESTING SCRIPT */
