//Local Variable with Flash Content id. default = flashcontent
var as_swf_name = "flashcontent";

//Initialize Facebook
function fbInit(pAsSwfName,pApi_key,pReceiver){
	as_swf_name = pAsSwfName;
	FB.init(pApi_key,pReceiver);
}

//JavaScript Connect methods
function login(){
	
	//alert('login');
	as_swf_name = "flashcontent";
	
	if(!is_init){
				FB_RequireFeatures(["Api", "Connect"], function () {
				FB.init(api_key, "xd_receiver.htm",{"ifUserConnected":showPermissionDialog,"ifUserNotConnected":onNotConnected});
				FB.ensureInit ( function () {		
				fb_api  = FB.Facebook.apiClient;
				is_init = true;
				});		
		});			
			}else{
				fbCheckStatus();
	}
	//fbCheckStatus();
}

	function fbCheckStatus(){
		//alert('fbCheckStatus');
		FB.Connect.get_status().waitUntilReady(function(status) {		
		   switch(status) {
		   case FB.ConnectState.connected:
		   		//alert('connected ');
				showPermissionDialog();			 
				break;
		   case FB.ConnectState.appNotAuthorized:
		   case FB.ConnectState.userNotLoggedIn:
		   		//alert('onNotConnected 1');
			 	onNotConnected();			 
			 	break;
		   }
		});	
	}

function onFBCancel(){
		//alert('cancel');
		flashCallBack("onLogInCancel");
		//flashCallBack( "onLogInCancel" );
		//document.getElementById("flashcontent").onFBCancel();
}
function onLogout(){
		flashCallBack("onLogInCancel");
		//document.getElementById("flashcontent").onFBLogout();
}
	
function FBlogout(){
		 FB.Connect.logout(onLogout);
}
function onNotConnected() {  
		//alert('onNotConnected 2');
		//FB.Connect.requireSession(null,onFBCancel);
		FB.Connect.requireSession( onLoginHandler,onFBCancel);
		//FB.Connect.requireSession(null,onFBCancel);
}	

	function showPermissionDialog(){
		//alert('pass 1');
		FB.Facebook.apiClient.users_hasAppPermission("user_photos",function(has1){
		FB.Facebook.apiClient.users_hasAppPermission("friends_photos",function(has2){
		FB.Facebook.apiClient.users_hasAppPermission("publish_stream",function(has3){
			if (has1 == 0 || has2 == 0 || has3 == 0) {
				//alert('pass 2');
			  FB.Connect.showPermissionDialog("friends_photos,user_photos,publish_stream,email", onConnected, false, null);
			}
			else {
			 onConnected();
			}
		  });
		 });
		 });
	}

	function onConnected() { 
		//alert('pass 3');
		if(fb_api.get_session()){
			//alert('pass 4');
			var uid = [fb_api.get_session().uid];
			var infos = ["uid","name"];		
			fb_api.users_getInfo(uid, infos, function(result, ex) {
				//document.getElementById("flashcontent").onFBConnected(fb_api.get_session().session_key);
				document.getElementById("flashcontent").onLogIn(fb_api.get_session().uid,fb_api.get_session().secret,fb_api.get_session().session_key);
				
				//flashCallBack("onLogIn");
				//alert('pass B');
			});
		}
	} 
	
//Event Handlers
function onLoginHandler(){
	//alert('Logged');
	
	//flashCallBack( "onLogIn" );
	//alert('pass A');
}

function onPermission() { 
		//log("onPermission");		
		//document.getElementById("flashContent").onPermission();
	}	
	
//Method to dispatch an Event to Flash
function flashCallBack ( func ) {
	if( arguments.length > 1 ){
		document[as_swf_name][func]( Array.prototype.slice.call(arguments).slice(1)[0]);
	}else{
		document[as_swf_name][func]();
	}
}

function callback (post_id, exception) { 
		flashCallBack( "onSubmitInvite" );

		if(post_id) { 
			//document.getElementById('swfid').callSWF('asMethod'); 
		} 
} 

function callbackreminder (post_id, exception) { 
		flashCallBack( "onSubmitReminder" );

		if(post_id) { 
			//document.getElementById('swfid').callSWF('asMethod'); 
		} 
} 

function callbackRAF (post_id, exception) { 
		flashCallBack( "onSubmitRAF" );

		if(post_id) { 
			//document.getElementById('swfid').callSWF('asMethod'); 
		} 
} 
	
function FBinvite(param){
	
	var inviteData = param.split(',');
	owner_uid = inviteData[0];
	owner_name = inviteData[1];
	friend_uid = inviteData[2];
	friend_name = inviteData[3];
	code_invite = inviteData[4];
	filename = inviteData[5];
	
		var message =  "I received a free PHYSIOGELTM AI Sun Cream worth RM66.90 for pledging my support for the POCC Campaign!";	//default text
		var attachment = {
			'name':"I received a free PHYSIOGELTM AI Sun Cream worth RM66.90 for pledging my support for the POCC Campaign!",	//widget name
			'href':"http://www.pocc.com.my/?page=pledge",
			'caption': "",	//action text
			'description':"Let's lend our support to the fight against Cervical Cancer! Power Over Cervical Cancer hopes to achieve the record of the largest portrait photo collage in the Malaysia Book of Records. Let's combine our strengths as Malaysians to achieve this by pledging your support!",													//widget description
			media: [{
			   type: "image",
			   src: "http://www.pocc.com.my/images/banner_msiapledge.jpg",
			   href: "http://www.pocc.com.my/?page=pledge"
			}]};
		var actionLinkData = [{	
				href:"http://www.pocc.com.my/?page=pledge",
				text:'Join Me Now!'	//cta
			}];
		FB.Connect.streamPublish(message, attachment, actionLinkData, friend_uid,"I received a free PHYSIOGELTM AI Sun Cream worth RM66.90 for pledging my support for the POCC Campaign!", callback);
}

function FBreminder(param){

	var inviteData = param.split(',');
	owner_uid = inviteData[0];
	owner_name = inviteData[1];
	friend_uid = inviteData[2];
	friend_name = inviteData[3];
	code_invite = inviteData[4];
	filename = inviteData[5];
	
		var message =  "Are we not friends anymore?";	//default text
		var attachment = {
			'name':"Are we not friends anymore?",	//widget name
			'href': "http://www.pocc.com.my/bff_join.php?code="+code_invite,
			'caption': 'Hey, a few days ago, I sent you an invitation to join me in the "Protect a Friend" eCard contest organized by a public awareness campaign called Power Over Cervical Cancer',	//action text
			'description':"Haven't received your response on this yet. ",													//widget description
			media: [{
			   type: "image",
			   src: filename,
			   href: "http://www.pocc.com.my/bff_join.php?code="+code_invite
			}]};
		var actionLinkData = [{	
				href:"http://www.pocc.com.my/bff_join.php?code="+code_invite,
				text:"Come on, join me!"	//cta
			}];
		FB.Connect.streamPublish(message, attachment, actionLinkData, friend_uid, 'Are we not friends anymore?', callbackreminder);
}

function FBraf(param){
	
	var inviteData = param.split(',');
	
	owner_uid = inviteData[0];
	owner_name = inviteData[1];
	friend_uid = inviteData[2];
	friend_name = inviteData[3];
	code_invite = inviteData[4];
	filename = inviteData[5];
	
	friend_uid = friend_uid.split('|');
	//friend_uid = temp.join(',');
	
	//alert(friend_uid);
	
		var message =  "Vote for me please!";	//default text
		var attachment = {
			'name':"Vote for me please!",	//widget name
			'href': "http://www.pocc.com.my",
			'caption': "I've entered into the Protect a Friend eCard contest organized by a public awareness campaign called Power Over Cervical Cancer.",	//action text
			'description':"I need all the votes I can get to win 2 X $100 Beauty Emporium Vouchers! Additionally through our participation, we can help to spread the word on the prevention of Cervical Cancer and protect all the women we care about.",													//widget description
			media: [{
			   type: "image",
			   src: filename,
			   href: "http://www.pocc.com.my"
			}]};
		var actionLinkData = [{	
				href:"http://www.pocc.com.my",
				text:"Vote for me now!"	//cta
			}];
		FB.Connect.streamPublish(message, attachment, actionLinkData, friend_uid[0], 'Vote for me now!', callbackRAF);
}

function FBraf_request(param) {
	
	var inviteData = param.split(',');
	
	owner_uid = inviteData[0];
	owner_name = inviteData[1];
	friend_uid = inviteData[2];
	friend_name = inviteData[3];
	code_invite = inviteData[4];
	filename = inviteData[5];
	
	title = 'Vote for me please!';
	actionTitle = "Vote for me please!";
	messageCopy = "I need all the votes I can get to win 2 X $100 Beauty Emporium Vouchers! Additionally through our participation, we can help to spread the word on the prevention of Cervical Cancer and protect all the women we care about.";
	
	FB.ensureInit(function() {
		my_dialog = new FB.UI.FBMLPopupDialog(title, "");
		profile_url = 'http://www.pocc.com.my'; // TODO
		var fbml = "<fb:fbml>" + 
				"<fb:request-form " + 
					"target=\"_top\" " + 
					"method=\"GET\" " + 
					"invite=\"true\" " +
					"action=\"" + document.location + "/\" " +
					"type=\"POCC - Protect a Friend\" " + 
					"content=\"" + messageCopy + " " +
					"<fb:req-choice url='" + document.location + "' label='Confirm' />\"" +
				">" + 
				"<fb:multi-friend-selector showborder=\"false\" exclude_ids=\"\" actiontext=\"" + actionTitle + "\" rows=\"3\" cols=\"4\" bypass=\"cancel\" showborder=\"true\" />" + 
				"</fb:request-form>" + 
				"</fb:fbml>";
        
        my_dialog.setFBMLContent(fbml);
        my_dialog.setContentWidth(620); 
        my_dialog.setContentHeight(620);
        my_dialog.show();
    });
}
