// ---------------------------------------- helper junk
var FBConnectImodLoggingURL = '';
var DEBUGMODE = false;
if ((typeof imod != 'undefined') && imod.Browser.Request.Querystring["debug"] == "1") {
    DEBUGMODE = true;
}

//http://jira/browse/ENC-2223 disable writing to the console if we're not in debug mode.  
//  fixes obscure instances when the console log is overlayed on the screen the user sees
//  http://digitalize.ca/tag/console-log/
//if (typeof (console) === 'undefined') {
//    console = {}
//}

//if (!DEBUGMODE || typeof (console.log) === 'undefined') {
//    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function () { };
//   }

  
// this can be overwritten if necessary
function refresh_page(prmExtraQS)
{
	if (window.console != null) console.log('refresh_page(' + prmExtraQS + ')');
	if (prmExtraQS == null) prmExtraQS = '';
	if (window.location.search.indexOf("fbdebug") > -1) 
	{
		alert('refresh with optional QS: ' + prmExtraQS);
	}
	else
	{
		if (window.location.search.indexOf("fbrefresh") > -1)
		{
			if (window.console != null) console.log('avoiding dupe refresh');
		}
		else
		{
			var newWindowLocation = window.location.href + prmExtraQS;
			newWindowLocation = newWindowLocation.replace('logout=1', '');
			window.location = newWindowLocation;
		}
	}
} // refresh_page

function ocs_logout()
{
	if (window.console != null) console.log('ocs_logout');
	if (window.location.search.indexOf("fbdebug") > -1) 
	{
		alert('redirect to logout');
	}
	else 
	{
		window.location.search = "logout=1";
	}
}

// http://www.quirksmode.org/js/cookies.html
function createCookie(name, value, days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name, "", -1);
}

function xmlhttpPost(strURL)
{
	if (window.console != null) console.log('xmlhttpPost to ' + strURL);
	var xmlHttpReq = false;
	if (window.XMLHttpRequest)
	{
		xmlHttpReq = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlHttpReq.open('GET', strURL, true);
	xmlHttpReq.onreadystatechange = function()
	{
		if (xmlHttpReq.readyState == 4)
		{
			if (window.console != null) console.log('ajax post success');
		}
	}
	xmlHttpReq.send(null);
} // xmlhttpPost


// ---------------------------------------- state detection

// Ensure Facebook app is initialized and call callback afterward
function ensure_init(callback) 
{
	if (window.console != null) console.log('START ensure_init');
	
	if(!window.api_key) 
	{
		window.alert("api_key is not set");
	}

	if(window.is_initialized) 
	{
		if (window.console != null) console.log('callback');
		callback();
	} 
	else 
	{
		if (window.console != null) console.log('FB_RequireFeatures');
		FB_RequireFeatures(["XFBML"], 
			function() 
			{
				//FB.FBDebug.isEnabled = true;
			    //FB.FBDebug.LogLevel = 4;
			    var xdReceiver = "/controls/facebook_ui/xd_receiver.htm";
			    if (document.location.protocol == "https:") xdReceiver = "/controls/facebook_ui/xd_receiver_ssl.htm";
				FB.Facebook.init(window.api_key, xdReceiver, { "reloadIfSessionStateChanged": true });
				window.is_initialized = true;
				callback();
			});
	}

	if (window.console != null) console.log('END ensure_init');
} // ensure_init

// SSO functionality - detect if they logged in or out of FB
function facebook_onload() 
{
	if (window.console != null) console.log('START facebook_onload...');

	// user state is either: has a session, or does not.
	// if the state has changed, detect that and reload.
	ensure_init(function()
	{
		setTimeout(function()
		{
			var already_logged_into_facebook = readCookie("imod_fb_sso");
			var is_now_logged_into_facebook = readCookie(window.api_key + "_user");
			if (window.console != null) console.log('already_logged_into_facebook=' + already_logged_into_facebook + ', is_now_logged_into_facebook=' + is_now_logged_into_facebook);
			if (window.location.search.indexOf("fbdebug") > -1)
			{
				alert('imod=' + already_logged_into_facebook + ', facebook=' + is_now_logged_into_facebook);
			}

			// 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)
			{
				if (window.console != null) console.log('login state unchanged');
				return;
			}

			// did they log out, or switch users
			if (!is_now_logged_into_facebook || ((already_logged_into_facebook != null) && (already_logged_into_facebook != is_now_logged_into_facebook)))
			{
				if (window.console != null) console.log('force logout');
				eraseCookie("imod_fb_sso");
				ocs_logout();
			}
			else
			{
				// they logged in, refresh to pick up the state change
				refresh_page("&fbrefresh=1");
			}
		}, 800);
	});

	if (window.console != null) console.log('END facebook_onload');
} // facebook_onload


// ---------------------------------------- feed functions
//**facebook's showFeedDialog set to be deprecated 12/20/09**
function facebook_publish_feed_story(form_bundle_id, template_data) 
{
	if (window.console != null) 
	{
		console.log('START facebook_publish_feed_story');
		console.log('form_bundle_id=' + form_bundle_id);
		console.log('template_data=\n' + template_data);
	}
	
	// Load the feed form
	ensure_init(function() {
	    if (window.console != null) console.log('calling showFeedDialog...');
	    FB.Connect.showFeedDialog(form_bundle_id,
	                                template_data,
	                                null,
	                                null,
	                                FB.FeedStorySize.shortStory,
	                                FB.RequireConnect.promptConnect,
	                                facebook_publish_callback);

	});
	
	if (window.console != null) console.log('END facebook_publish_feed_story');
} // facebook_publish_feed_story

function facebook_publish_stream(attachment, action) {
    if (window.console != null) {
        console.log('START facebook_publish_stream');
        console.log('attachment=\n' + attachment);
        console.log('action_link=\n' + action);        
    }

    // Load the feed form
    ensure_init(function() {
//*sample attachment object and action link to pass to streamPublish*
//        attachment = { 'name': 'This is the Name',
//            'href': 'http://fbconnect3.imodules.com/',
//            'description': '$$CLASS_NOTE_TEXT$$',
//            'caption': '{*actor*} posted in Career at Marco Dev.',
//            'properties': [{ 'text': 'HOLLA', 'href': 'http://www.imodules.com' },
//	                        { 'text': 'can i get a', 'href': 'http://www.google.com' },
//	                        { 'text': 'woot woot', 'href': 'http://www.google.com'}],
//	                        'media': [{ 'type': 'image', 'src': 'http://icanhascheezburger.files.wordpress.com/2009/03/funny-pictures-kitten-finished-his-milk-and-wants-a-cookie.jpg', 'href': 'http://icanhascheezburger.com/2009/03/30/funny-pictures-awlll-gone-cookie-now/' },
//                                      { 'type': 'image', 'src': 'http://photos.icanhascheezburger.com/completestore/2009/1/18/128768048603560273.jpg', 'href': 'http://ihasahotdog.com/upcoming/?pid=20869' }
//                                     ]
//        };

//        var actionLink = [{ "text": "Watch Video", "href": "http://www.myvideosite/videopage.html" }];
//        
        if (window.console != null) console.log('calling streamPublish...');
        FB.Connect.streamPublish('',
	                            attachment,
	                            action,
	                            '',
                                '',
                                facebook_publish_callback,
                                false,
                                null);


    });

    if (window.console != null) console.log('END facebook_publish_stream');
} // facebook_publish_stream

function facebook_publish_callback(response)
{
	// logging in the hopes that eventually we'll get a response that tells us of success status
	if (window.console != null) 
	{
		console.log('facebook_publish_callback');				
		if (response != null)
		{
			console.log('response=\n' + response);
		}
		else
		{
			console.log('no response');
		}
	} // console
	
	// if there is any logging to do, trigger it
	if ((FBConnectImodLoggingURL != null) && (FBConnectImodLoggingURL.length > 0)) {
		xmlhttpPost(FBConnectImodLoggingURL);
	}
	else if ((typeof imodLoggingURL != 'undefined') && (imodLoggingURL != null) && (imodLoggingURL.length > 0)) {
		xmlhttpPost(imodLoggingURL);
	}
	else {
		console.log('could not execute logging post');
	}

	// if there is a publish button, hide it and show any resulting verbiage
	var divFacebookPublish = document.getElementById('divFacebookPublish');
	if (divFacebookPublish != null) 
	{
		divFacebookPublish.style.display = 'none';

		var divFacebookPublished = document.getElementById('divFacebookPublished');
		if (divFacebookPublished != null) divFacebookPublished.style.display = '';
	}
} // facebook_publish_callback


// ---------------------------------------- login/logout functions

function LogoutOfFacebook(prmEventObject)
{
	imod.dom.PreventDefault(prmEventObject);
	ensure_init(function()
	{
		if (window.console != null) console.log("LogoutOfFacebook: logging out of facebook...");
		FB.Connect.logout(function() { AfterFacebookLogout(); })
		if (window.console != null) console.log("called it.");
	});
}

function AfterFacebookLogout(prmSuccess)
{
	if (window.console != null) console.log("AfterFacebookLogout: You were logged out of Facebook.");
	//document.forms[0].submit();
	ocs_logout();
}

function LogoutOfFacebookOnly()
{
	ensure_init(function()
	{
		if (window.console != null) console.log("LogoutOfFacebookOnly: logging out of facebook(2)...");
		FB.Connect.logout(function () { if (window.console != null) console.log("LogoutOfFacebookOnly: logged out."); })
	});
}

function divFBLoginContainer_show()
{
	var fbbutton = document.getElementById('divFBLoginContainer');
	if (fbbutton != null) fbbutton.style.visibility = "visible";
}

function showDocAfterRender()
{
	ensure_init(function()
	{
		//FB.XFBML.Host.get_areElementsReady().waitUntilReady(divFBLoginContainer_show);
		divFBLoginContainer_show();
	});
}

/*
* Onclick handler for "facebook login" button. This will register
* a handler for when the session becomes available, and then
* start the process of getting a user's session (via popup, ajax
* dialog, or just checking that they are already authenticated).
*
*/
function facebook_button_onclick(link_to_current_user)
{
	ensure_init(function()
	{
		// hitting FB and then redirecting is slow, don't leave the login junk up long enough for them to think something's wrong
		FB.Facebook.get_sessionState().waitUntilReady(function()
		{
			facebook_session_is_ready(link_to_current_user);
		});
		//FB.Connect.requireSession();
	});
}

/*
* "Session Ready" handler. This is called when the facebook
* session becomes ready after the user clicks the "Facebook login" button.
* In a more complex app, this could be used to do some in-page
* replacements and avoid a full page refresh. For now, just
* notify the server the user is logged in, and redirect to home.
*
* @param link_to_current_user  if the facebook session should be
*                              linked to a currently logged in user, or used
*                              to create a new account anyway
*/
function facebook_session_is_ready(link_to_current_user)
{
	var user = FB.Facebook.apiClient.get_session().uid;

	if (!user)
	{
		// probably should give some indication of failure to the user
		alert("Facebook returned an error and the login may have failed.");
		return;
	}

	var divLogin = document.getElementById('divLogin');
	if (divLogin != null) divLogin.style.display = 'none';
	var divFacebookLoader = document.getElementById('divFacebookLoader');
	if (divFacebookLoader != null) divFacebookLoader.style.display = '';

	// set a cookie on our end so we can support SSO to detect if they log out of FB first
	createCookie("imod_fb_sso", user);

	refresh_page();
}


if (window.IModController) IModController.scriptLoadedNotification("/controls/facebook_ui/fbconnect_1_2.js");
