var $j = jQuery.noConflict();
var noSessionTimerId = null;
var fbConnected = false;

$j(document).ready(function() {
	FB.init(fbApiKey, "/xd_receiver.htm");
	
	FB.ensureInit(function() {
		var gotSession = false;

		// ### Register timout fallback
		var noSessionTimerId = window.setTimeout('handleWaiterTimeout();', 5000);

		// ### Check for FB-session
		FB.Facebook.get_sessionWaitable().waitUntilReady(function(session) {
			gotSession = true;
			window.clearTimeout(noSessionTimerId);
			member.uid = session.uid;
			debug('got fb session: ' + member.uid);

			//if (isPoshMember()) {
				// ### Check if FB-connected or not
				FB.Connect.ifUserConnected(function() {
					// ### Check if app-connected 
					if (isAppConnected()) {
						// ### Make sure member is connected to current logged in FB
						if (isWrongFBUser()) {
							debug('connected with other fb account');
							showConnectToFacebook();
						} else {
							// ### Everything is green
							showFacebookContent();
						}
					} else {
						debug('connected but not app-connected');
						if (member.newMember) {
							debug('new member -> create facebookmember');
							connectToFacebook();
						} else {
							// showConnectToFacebook();
							showFacebookContent();
						}
					}
				}, function() {
					// ### Not FB-connected
					showConnectToFacebook();
				});
			//} else {
				// ### Not Posh-loggedin
				//showConnectToFacebook();
			//}
		});

		// ### Handle no FB-session
		if (!gotSession && !FB.Facebook.apiClient.get_session()) {
			debug('no fb session');
			showConnectToFacebook();
		}
	});
});

function handleWaiterTimeout() {
	// ### Reset fb-session waiter
	FB.Facebook.get_sessionWaitable().resetChange();
	debug('timeout');
}

function fbLogin() {
	if (isWrongFBUser()) {
		FB.Connect.logout(function() {
			FB.Connect.requireSession(function() {
				reloadPage();
			});
		});
	} else {
		connectToFacebook();
	}
}

function gotoRegistration() {
	document.location.href = "/register.action";
}

function reloadPage() {
	document.location.reload(true);
}

function isPoshMember() {
	return (member.id != null);
}

function isAppConnected() {
	return (member.fuid != null);
}

function isWrongFBUser() {
	return isAppConnected() && (typeof member.uid != 'undefined') && (member.fuid != member.uid);
}

function onRegistrationPage() {
	return (document.location.pathname == '/register.action') ||
	       (document.location.pathname == '/welcome.action');
}

function connectToFacebook() {
	if (!isAppConnected()) {
		var sdata = getFBCookieParams();	
		$j.get("/javascript/facebookRegister.action", sdata, function(data) {
			if (data == "first_success") {
				askForFacebookPublish();
			} else if (data == "success") {
				reloadPage();
			} else {
				warn('failed to app-connect!')
				reloadPage();
				//alert('Facebook member is already connected with another Posh24 member');
				//document.location.href = "/fbRegister.action?error=accountTaken";
			}
		});
	} else {
		showFacebookContent();
	}
}

function askForFacebookPublish() {
	debug('ask for autopublish');
	facebook_publish_feed_story_cb(feedBundles.joined, null, function(data) {
		reloadPage();
	});
}

function showFacebookContent(){
	fbConnected = true;
	$j(".facebookVisible").show();
	$j(".facebookInvisible").hide();
	fillFBForms();
}

function showConnectToFacebook() {
	fbConnected = false;
	if (!onRegistrationPage()) {
		var v = $j(".facebookVisible");
		if (v) {
			$j(".facebookVisible").hide();
		}
		$j(".facebookInvisible").show();
		if ($("comment_anonymousName")) {
			$("comment_anonymousName").value="";
		}
	}
}

function fillFBForms(){
	var sdata = getFBCookieParams();
	
	var fb_uid = $j("#fb_uid");
	if (fb_uid.length) {
		fb_uid.val(sdata.user);
		
		var fb_expires = $j("#fb_expires");
		var fb_sessionKey = $j("#fb_sessionKey");
		var fb_ss = $j("#fb_ss");
		var fb_hash = $j("#fb_hash");
	
		if (fb_expires.length) 		fb_expires.val(sdata.expires);
		if (fb_sessionKey.length) 	fb_sessionKey.val(sdata.sessionKey);
		if (fb_ss.length) 			fb_ss.val(sdata.ss);
		if (fb_hash.length) 		fb_hash.val(sdata.hash);
	}
	
	var comment_anonymousName = $j("#comment_anonymousName");
	if (comment_anonymousName.length) {
		comment_anonymousName.hide();
		//$("comment_anonymousName").value=FB.Facebook.apiClient.get_session().uid+"_"+new Date().getTime();
		comment_anonymousName.val(member.uid + "_" + new Date().getTime());
	}
	
	// Import fb-info!
	var fb_area = $j('#fb_area');
	if (fb_area.length) {
		debug('getting info for: ' + member.uid); 
		FB.ensureInit(function() {
			FB.Facebook.apiClient.users_getInfo(
				//new Array(FB.Facebook.apiClient.get_session().uid),
				new Array(member.uid),
				["current_location", "hometown_location", "about_me", "first_name", "last_name", "sex"],
				function(result, ex) {
					if (!ex) {
						var usr = result[0];
						
						var fb_aboutMe = $j("#fb_aboutMe");
						var fb_firstName = $j("#fb_firstName");
						var fb_lastName = $j("#fb_lastName");
						var fb_genderAsString = $j("#fb_genderAsString");
						var fb_submitImport = $j("#fb_submitImport");
						
						if (fb_area.length && usr.current_location && usr.current_location.country)
							fb_area.val(usr.current_location.country);
						else if(fb_area.length && usr.hometown_location && usr.hometown_location.country)
							fb_area.val(usr.hometown_location.country);
						
						if (fb_aboutMe.length && usr.about_me)
							fb_aboutMe.val(usr.about_me);
						
						if (fb_firstName.length && usr.first_name)
							fb_firstName.val(usr.first_name);
						
						if (fb_lastName.length && usr.last_name)
							fb_lastName.val(usr.last_name);
						
						if (fb_genderAsString.length && usr.sex)
							fb_genderAsString.val(usr.sex);
						
						if (fb_submitImport.length)
							fb_submitImport.removeAttr("disabled");
					} else {
						debug('no result for users info: ' + ex);
					}
				});
		});
	}
}

function getFBCookieParams(){
	return {
		expires:$j.cookie(fbApiKey+"_expires"),
		sessionKey:$j.cookie(fbApiKey+"_session_key"),
		ss:$j.cookie(fbApiKey+"_ss"),
		user:$j.cookie(fbApiKey+"_user"),
		hash:$j.cookie(fbApiKey)
	};
}

/*
 * Executed on jsp's and votebox.js
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
	// Load the feed form
	FB.ensureInit(function() {
		FB.Connect.showFeedDialog(form_bundle_id, template_data);
	});
}

function facebook_publish_feed_story_cb(form_bundle_id, template_data, callback) {
	// Load the feed form
	FB.ensureInit(function() {
		FB.Connect.showFeedDialog(form_bundle_id, template_data,null,null,null,null,callback);
	});
}

function unescapeHTML(html) {
	var htmlNode = document.createElement("DIV");
	htmlNode.innerHTML = html;
	if(htmlNode.innerText !== undefined)
	return htmlNode.innerText; // IE
	return htmlNode.textContent; // FF
}

function debug(text) {
	//alert(text);
}

function warn(text) {
	//alert(text);
}
