var userID;
var invite=false;
var appName="";
var title="";
var actionTitle="";
var message="";
//
var myHome = "http://www.yourfaceforfreedom.org";

function loginConnect(api_key, homeUrl)
{
		FB_RequireFeatures(["Connect"], function() { 
		FB.init(api_key, myHome + "/facebook/xd_receiver.htm",{"doNotUseCachedConnectState":true,"forceBrowserPopupForLogin":true,"reloadIfSessionStateChanged":false}); 
		FB.Connect.requireSession(function(){
			FB.Facebook.get_sessionState().waitUntilReady(function()	  {
				var sessionData=FB.Facebook.apiClient.get_session();
				userID = sessionData.uid;
				if (!userID) {
					sendLoginStatus(false,'',"nessun userID recuperato")
				}else{
					if(invite){
						sendInviteFriends();
						inviteFriends(api_key,appName,title,actionTitle,message, homeUrl)
					}else{
						sendLoginStatus(true,sessionData,'');
					}
					
				}
				
			});
		},
		function(){ 
			//premuto cancel o chiudi
			sendLoginStatus(false,'','')
		}
		); 
	}); 
}
	
function askPermission(args){
	FB.Connect.showPermissionDialog(args, sendPermissions,true,null);
}

var	ret_domainJS="";

function getDomainJS(fb_id)
{
			var ret="";
			if (fb_id!=undefined && fb_id!=null && fb_id.length>0)
			{
				// jquery che interroga il DB 
				var wait= $.ajax({
				   async: false,
				   url: "/getDomain-srv.jsp",
				   data: "id_fb="+ fb_id+"&domain=org",
				   success: function(msg){
				   	ret_domainJS=msg;
				   	if (ret_domainJS.indexOf("com")!=-1)
				   		ret_domainJS = "com";
				   	else
				   		ret_domainJS = "org";
    					}
				 });
				 ret=ret_domainJS;
			}
			else
				ret=app_domain;
			return ret;	

}

function inviteFriends(api_key, sAppName, sTitle, sActionTitle, sMessageCopy, homeUrl)
{
	var dom = getDomainJS(userID); // Ajax 
	//
	if (dom=="com")
		sMessageCopy = "The 10th December 2009 change your Facebook profile photo with the 'Aung San Suu Kyi Free Now' one. Support the campaign to free the Burma Nobel Peace Laureate, sending a peace message and sharing the initiative with your friends. Join now. http://www.yourfaceforfreedom.com";
	else
		sMessageCopy = "The 10th December 2009 change your Facebook profile photo with the 'Aung San Suu Kyi Free Now' one. Support the campaign to free the Burma Nobel Peace Laureate, sending a peace message and sharing the initiative with your friends. Join now. http://www.yourfaceforfreedom.org";
	//
	appName		=	sAppName;
	title		= 	sTitle;
	actionTitle	=	sActionTitle;
	message		=	sMessageCopy;
	if(!userID)
	{
		invite=true;
		loginConnect(api_key, homeUrl);
	}
	else
	{
		invite=false;
	        //var dialog = new FB.UI.FBMLPopupDialog(sTitle, "");
	        var fbml = "<fb:fbml>" + 
	        				"<fb:request-form " + 
	        							"method=\"GET\" " +
										"action=\"" + myHome + "/facebook/invite.jsp?dom=" + dom + "\" " + 
										"target=\"_top\"" + "\" " + 
	        							"invite=\"false\" " + 
	      								"type=\"YourFaceForFreedom\" " + 
	       								"content=\"" + sMessageCopy + " " +        										
	    	   									"<fb:req-choice url='http://apps.facebook.com/yourfaceforfreedom/&next=%3Fdom%3D"+dom+"' label='Confirm' />\"" + 
	    	   							">" + 
	  							"<fb:multi-friend-selector showborder=\"false\" exclude_ids=\"\" actiontext=\"" + sActionTitle + "\" rows=\"3\" cols=\"4\" bypass=\"cancel\" showborder=\"true\" />" + 
	        				"</fb:request-form>" + 
	        			"</fb:fbml>";
	    var dialog = new FB.UI.FBMLPopupDialog(sTitle, fbml);
			//dialog.setFBMLContent(fbml);
			dialog.setContentWidth(630); 
			dialog.setContentHeight(550);
			dialog.show();
	}
}

function publishPost( userImage, caption, description )
{
	var dom = getDomainJS(userID); // Ajax 
	 
	/*
	userImage = "http://www.yourfaceforfreedom.org/resources/template.png";
	//caption = " taking part in the 'Aung San Suu Kyi Free Now' event";
    description = "The 10th December 2009 change your Facebook profile photo with the 'Aung San Suu Kyi Free Now' one.\r\n
                  Support the campaign to free the Burma Nobel Peace Laureate, sending a peace message and sharing the initiative with your friends.\r\n
                  Freedom has only one face.";
     */
    //
    // caption = "is taking part in the 'Aung San Suu Kyi Free Now' event";
    var action = null;
    var attachment = null;
    if (dom == "com")
    {
	    description = "The 10th December 2009 change your Facebook profile photo with the 'Aung San Suu Kyi Free Now' one. Support the campaign to free the Burma Nobel Peace Laureate, sending a peace message and sharing the initiative with your friends. Join now. http://www.yourfaceforfreedom.com";
		action =[{ "text": "YourFaceForFreedom", "href": "http://www.yourfaceforfreedom.com" } ];
		attachment = {'media':[{'type':'image','src': userImage ,'href':'http://apps.facebook.com/yourfaceforfreedom/?dom=com'}], "caption": caption,"description":description };
	} 
	else
	{
	    description = "The 10th December 2009 change your Facebook profile photo with the 'Aung San Suu Kyi Free Now' one. Support the campaign to free the Burma Nobel Peace Laureate, sending a peace message and sharing the initiative with your friends. Join now. http://www.yourfaceforfreedom.org";
		action =[{ "text": "YourFaceForFreedom", "href": "http://www.yourfaceforfreedom.org" } ];
		attachment = {'media':[{'type':'image','src': userImage ,'href':'http://apps.facebook.com/yourfaceforfreedom/?dom=org'}], "caption": caption,"description":description };
	}
	FB.Connect.streamPublish( '', attachment, action, null, null, sendPublishPost);
}


function sendPublishPost(post_id, exception) {
  if (post_id) {
    var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["container"]:document["container"];
	flash.returnPublishPost(post_id);
  }
}


function sendPermissions(args){
	var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["container"]:document["container"];
	flash.returnPermissions(args);
}

function sendLoginStatus(how,sessionData,error){
	var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["container"]:document["container"];
	flash.returnLoginStatus(how,sessionData,error); 		
}

function sendInviteFriends(){
	var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["container"]:document["container"];
	flash.returnInviteFriends(); 		
}
