window.FBUnity = {
    init: function(isPlayer, connectFacebookUrl, locale, debug, initParams, status) {
        FBUnity.isPlayer = isPlayer;
        // make element for js sdk
        if(!document.getElementById('fb-root')) {
            var fbroot = document.createElement('div');
            fbroot.id = 'fb-root';
            var body = document.getElementsByTagName('body')[0];
            body.insertBefore(fbroot, body.children[0]);
        }

        // load js sdk
        var js, id = 'facebook-jssdk', ref = document.getElementsByTagName('script')[0];
        if (document.getElementById(id)) {return;}
        js = document.createElement('script'); js.id = id; js.async = true;
        js.src = connectFacebookUrl + '/' + locale + '/sdk' + (debug ? '/debug' : '') + '.js';
        ref.parentNode.insertBefore(js, ref);
        // once jssdk is loaded, init
        window.fbAsyncInit = function () {
            initParams = JSON.parse(initParams);
            initParams.hideFlashCallback = FBUnity.onHideUnity;
            FB.init(initParams);
            // send url to unity - needed for deep linking
            FBUnity.sendMessage('OnUrlResponse', location.href);
            if (status) {
                FBUnity.onInitWithStatus();
            } else {
                FBUnity.onInit();
            }
        };
    },

    sendMessage: function(method, param) {
        if (!FBUnity.isPlayer) {
            SendMessage('FacebookJsBridge', method, param);
        } else {
            u.getUnity().SendMessage('FacebookJsBridge', method, param);
        }
    },
    
    login: function(scope, callback_id) {
        FB.login(FBUnity.loginCallback.bind(null, callback_id), scope ? {scope: scope, auth_type: 'rerequest', return_scopes: true} : {return_scopes: true});
    },
    
    loginCallback: function(callback_id, response) {
        response = {'callback_id': callback_id, 'response': response};
        FBUnity.sendMessage('OnLoginComplete', JSON.stringify(response));
    },
    
    onInitWithStatus: function() {
        var timeoutHandler = setTimeout(function() { requestFailed(); }, 3000);

    	function requestFailed() {
    		FBUnity.onInit();
        }

    	// try to get the login status right after init'ing
    	FB.getLoginStatus(function(response) {
    		clearTimeout(timeoutHandler);
    		FBUnity.onInit(response);
    	});
    },

    onInit: function(response) {
    	var jsonResponse = "";
    	if(response && response.authResponse) {
    		jsonResponse = JSON.stringify(response);
    	}
    	
    	FBUnity.sendMessage('OnInitComplete', jsonResponse);
    	FB.Event.subscribe('auth.authResponseChange', function(r){ FBUnity.onAuthResponseChange(r) });
    },

    onAuthResponseChange: function(response) {
        FBUnity.sendMessage('OnFacebookAuthResponseChange', response ? JSON.stringify(response) : '');
    },

    apiCallback: function(query, response) {
    	response = {'query': query, 'response': response};
    	FBUnity.sendMessage('OnFacebookAPIResponse', JSON.stringify(response));
    },

    api: function(query) {
    	FB.api(query, FBUnity.apiCallback.bind(null , query));
    },

    activateApp: function() {
        FB.AppEvents.activateApp();
    },

    uiCallback: function(uid, callbackMethodName, response) {
    	response = {'callback_id': uid, 'response': response};
    	FBUnity.sendMessage(callbackMethodName, JSON.stringify(response));
    },

    logout: function() {
    	FB.logout();
    },

    logAppEvent: function(eventName, valueToSum, parameters) {
    	FB.AppEvents.logEvent(
    		eventName,
    		valueToSum,
    		JSON.parse(parameters)
    	);
    },

    logPurchase: function(purchaseAmount, currency, parameters) {
    	FB.AppEvents.logPurchase(
    		purchaseAmount,
    		currency,
    		JSON.parse(parameters)
    	);
    },

    ui: function(x, uid, callbackMethodName) {
    	x = JSON.parse(x);
    	FB.ui(x, FBUnity.uiCallback.bind(null, uid, callbackMethodName));
    },

    
    hideUnity: function(direction) {
    	direction = direction || 'hide';
    	//TODO support this for webgl
    	var unityDiv = jQuery(u.getUnity());

    	if(direction == 'hide') {
    		FBUnity.sendMessage('OnFacebookFocus', 'hide');
    	} else /*show*/ {
    		FBUnity.sendMessage('OnFacebookFocus', 'show');

    		if (FBUnity.showScreenshotBackground.savedBackground) {
    			/*
    			if(fbShowScreenshotBackground.savedBackground == 'sentinel') {
    				jQuery('body').css('background', null);
    			} else {
    				jQuery('body').css('background', fbShowScreenshotBackground.savedBackground);
    			}
    			*/
    		}

    		hideUnity.savedCSS = FBUnity.showScreenshotBackground.savedBackground = null;
    	}
    },
    
    showScreenshotBackground: function(pngbytes) /*and hide unity*/ {
        // window.screenxX and window.screenY = browser position
        // window.screen.height and window.screen.width = screen size
        // findPos, above, locates the iframe within the browser
        /*
        if (!fbShowScreenshotBackground.savedBackground)
            fbShowScreenshotBackground.savedBackground = jQuery('body').css('background') || "sentinel";

        jQuery('body').css('background-image', 'url(data:image/png;base64,'+pngbytes+')');
        jQuery('body').css(
            'background-position',
            -(screenPosition.iframeX)+'px '+
            -(screenPosition.iframeY)+'px'
        );
        jQuery('body').css('background-size', '100%');
        jquery('body').css('background-repeat', 'no-repeat');
        // TODO: Zoom detection
        */
    },
    
    onHideUnity: function(info) {
      if(info.state == 'opened') {
        FBUnity.sendMessage('OnFacebookFocus', 'hide');
      } else {
        FBUnity.sendMessage('OnFacebookFocus', 'show');
      }
    }
};    

if(!screenPosition) {
    var body = document.getElementsByTagName('body')[0];
    var screenPosition = {omo : body.onmouseover || function(){}, iframeX: 0, iframeY: 0};
    body.onmouseover = function(e) {
        // Distance from top of screen to top of client area
        screenPosition.iframeX = e.screenX - e.clientX;
        screenPosition.iframeY = e.screenY - e.clientY;

        screenPosition.omo(e);
    }
}
