(function(){
	window.FBManager = function(settings){ this.init(settings); };
	
	FBManager.prototype.init = function(settings)
	{
		this.options = {};
		jQuery.extend(this.options, settings);
		
		//FBManager variables
		this._bAsyncIsLoaded = false;	//Will be set to true after _asyncLoaded() is called, when false, callbacks will be queued, when true, they'll be executed
		this._aFunctionsOnLoad = [];	//An array of callbacks while waiting for _bAsynchIsLoaded to be set to true
		this._FBInitialized = false;
		this._FBAsyncDeclared = false;
		this._FBUserRetrieved = false;
		
		this.FBUserSession
		
		if(!!this.options.onAsyncLoaded)
		{
			switch(typeof this.options.onAsyncLoaded)
			{
				case 'function': this.onAsyncLoaded(this.options.onAsyncLoaded); break;
				case 'object': 				
					for(var i=0;i<this.options.onAsyncLoaded.length;i++)
					{
						if(typeof(this.options.onAsyncLoaded[i]) == 'function') this.onAsyncLoaded(this.options.onAsyncLoaded[i]);
					}
					break;
			}
		} 
		this._FBInitialize();
	};
	
	
	FBManager.prototype._FBInitialize = function()
	{	
		if(!!this.options.FBAppId && !this._FBInitialized)
		{
			this.declareFbAsyncInit();
			this._appendFBJS();	
			this._FBInitialized = true;
		}
	};
	
	
	FBManager.prototype.declareFbAsyncInit = function() 
	{
		var me = this;
		
		jQuery(window).load(function(){
			
			if(!this._FBAsyncDeclared)
			{
				//window.fbAsynchInit is required - it's a callback that the FB Api looks for
				window.fbAsyncInit = function () 
				{
					if(jQuery('#fb-root').length == 0) jQuery('body').prepend('<div id="fb-root"></div>');
					
					FB.init(
					{
						appId: me.options.FBAppId,
						status: false, // check login status
						cookie: true, // enable cookies to allow the server to access the session
						xfbml: true  // parse XFBML
					});
					me._asyncLoaded();
				};
				this._FBAsyncDeclared = true;
			}
		});
	};
	
	
	FBManager.prototype._appendFBJS = function()
	{
		
		//After connect.facebook.net/en_US/all.js is called, fbAsyncInit() is fired - forcing this until after 
		//		window.load ensures that the page load won't be delayed if some delay on FB's side -- downside 
		//		is like buttons will show up after page is rendered.
		jQuery(window).load(function () 
		{
			window.setTimeout(function () 
			{
				var e = document.createElement('script');
				e.setAttribute('type', 'text/javascript');
				e.setAttribute('src', document.location.protocol + '//connect.facebook.net/en_US/all.js');
				e.setAttribute('async', 'true');
				document.getElementsByTagName('head')[0].appendChild(e);
			}, 100);
		});  
	};
	
	
	//Queues a callback for execution after FB _asynchLoaded is true - or if it's already true, simply executes it.
	FBManager.prototype.onAsyncLoaded = function (callback) 
	{
        if (typeof callback == 'function') 
		{
            if 		( this._bAsyncIsLoaded) { callback(); } 
			else 	{ this._aFunctionsOnLoad.push(callback); }
        }
    };	
	
	
	//Sets flag for FB API helper files loaded, and executes any queued callback functions
	FBManager.prototype._asyncLoaded = function()
	{
		this._bAsyncIsLoaded = true;
		for (var i = 0; i < this._aFunctionsOnLoad.length; i++) { this._aFunctionsOnLoad[i](); }
	};
	
	
	FBManager.prototype.getUserDetails = function(success, failure){
		var me = this;
		FB.getLoginStatus(function(response){
			if (response.session || response.status == 'notConnected') {
				me._FBUserRetrieved = true;
				me.FBUserSession = response.session;
				if(typeof success == 'function') success(me);
			} else {
				me._FBUserRetrieved = false;
				if(typeof failure == 'function') failure(me);
			}
		}, true);
	}
	
	
	//If we didn't get a FBAppId with the initial settings, this function allows it to be set, and then initializes the FB JS.
	FBManager.setFBAppId = function(appId)
	{
		this.options.FBAppId = appId;
		this.declareFbAsyncInit();
		this._appendFBJS();	
	};
	
	
	FBManager.prototype.appendIFrame = function(iFrameSettings)
	{
		//TODO:  Add Channel URL method of including iFrame
	
		iFrameSettings = iFrameSettings || {};
		iFrameSettings.width = iFrameSettings.width || 292;
		iFrameSettings.showFaces = iFrameSettings.showFaces || 'false';
		iFrameSettings.action = iFrameSettings.action || 'like';
		iFrameSettings.colorScheme = iFrameSettings.colorScheme || 'light';
		iFrameSettings.font = iFrameSettings.font  || 'Arial';
		iFrameSettings.height = iFrameSettings.height || 35;
		iFrameSettings.ref = iFrameSettings.ref || ''; //EX:  'Acura.com_global_footer';
		iFrameSettings.layout = iFrameSettings.layout || 'standard';
		iFrameSettings.send = iFrameSettings.send || 'false';
		iFrameSettings.markupMode = iFrameSettings.markupMode || 'replace';
		
		iFrameSettings.iFrameOrXFBML = iFrameSettings.iFrameOrXFBML || 'iframe';
		
		//FB doesn't handle IE7 well, so "recommend" formatting gets distorted
		if (jQuery('body').hasClass('lteIE7')) iFrameSettings.action = 'like';	
		
		if(!this.options.FBAppId || !iFrameSettings.likeURL || !iFrameSettings.containerElem){
			if(window.console)console.log('ERROR!');
			return false;
			//throw error, break
		}
		
		var markup
		
		switch(iFrameSettings.iFrameOrXFBML){
			case 'iframe':
				markup = '<iframe src="' + document.location.protocol + '//www.facebook.com/plugins/like.php?app_id=' + 
							this.FBAppId + '&amp;href=' + iFrameSettings.likeURL + '&amp;send=' + iFrameSettings.send + 
							'&amp;layout=' + iFrameSettings.layout + '&amp;width=' + iFrameSettings.width + '&amp;show_faces=' + 
							iFrameSettings.showFaces + '&amp;action=' + iFrameSettings.action + '&amp;colorscheme=' + 
							iFrameSettings.colorScheme + '&amp;font=' + iFrameSettings.font + '&amp;height=' + iFrameSettings.height + 
							'&amp;ref=' + iFrameSettings.ref + '" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:' + 
							iFrameSettings.width + 'px; height:' + iFrameSettings.height + 'px;"></iframe>';
				break;
			case 'xfbml':
				markup = '<fb:like data-href="' + iFrameSettings.likeURL + '" data-send="' + iFrameSettings.send + 
							'" data-height="' + iFrameSettings.height + '" data-width="' + iFrameSettings.width + '" data-show_faces="' + 
							iFrameSettings.showFaces + '" data-layout="' + iFrameSettings.layout + '" data-action="' + 
							iFrameSettings.action + '" data-font="' + iFrameSettings.font + '" data-colorscheme="' + 
							iFrameSettings.colorscheme + '" ref="' + iFrameSettings.ref + '"></fb:like>';
				break;
		}
		
		switch(iFrameSettings.markupMode){
			case('append'): 
				jQuery(iFrameSettings.containerElem).append(markup);
				break;
			case('prepend'): 
				jQuery(iFrameSettings.containerElem).prepend(markup);
				break;
			case('replace'): 
				jQuery(iFrameSettings.containerElem).html(markup);
				break;
		}
		
		if(iFrameSettings.callback && typeof iFrameSettings.callback == 'function' && typeof iFrameSettings.callbackDelay == 'number'){
			window.setTimeout(function () {
				iFrameSettings.callback();
			}, iFrameSettings.callbackDelay);
		}
	}
	
	
})();




