/**
*
* 	ActiveFacebook JS Wrapper API Facebook - AS3 Bridge
*
*	Copyright (c) 2008-2010 Gianluca Cirone @ RMG Connect Milano
*	Version 2.0 Open Graph API - Facebook RoadMap 2010
*
**/

var ActiveFacebookEvent = {
	WAITING_FOR_LOGIN:"waitingForLogin",
	ON_LOGGEDIN:"onLoggedIn",
	ON_LOGGEDOUT:"onLoggedOut",
	ON_PERMISSION:"onPermission",
	ON_CALL_COMPLETE:"onCallComplete",
	ON_GETUSERINFO:"onGetUserInfo",
	ON_ERROR:"onError"
}

var FlashCallback = {
	WAITINGFORLOGIN:"CallbackWaitingForLogin",
	LOGGEDIN:"CallbackLoggedIn",
	LOGGEDOUT:"CallbackLoggedOut",
	PERMISSION:"CallbackPermission",
	CALLCOMPLETE:"CallbackCallComplete",
	GETUSERINFO:"CallbackGetUserInfo"
}

var ActiveFacebook = function(){
	var api = {}, session = {}, user = {},
	events = {}, apiKey, objsFlash = new Array(),
	isFlashReady = false, isLoggedIn = false,
	isSessionExist = false;
	
	// Init Facebook Api 
	function init(){		
		window.fbAsyncInit = function() {		
			FB.init({appId: apiKey, status: true, cookie: true, xfbml: true});
			ceckSession();
		};
		(function() {
			var e = document.createElement('script');
			e.async = true;
			e.src = 'http://connect.facebook.net/en_US/all.js';
			var divfb = document.createElement('div');
			divfb.id = 'fb-root';
			divfb.appendChild(e);
			document.body.appendChild(divfb);			
		}());		
	}
	
	// Wait until Session in ready
	function ceckSession(){		
		//alert("ceckSession");	
		dispatchEvent(ActiveFacebookEvent.WAITING_FOR_LOGIN);
		dispatchFlashCallback(FlashCallback.WAITINGFORLOGIN);
		FB.getLoginStatus(function(response) {
			if (response.session) {
				session = response.session;
				isSessionExist = true;
				sessionReady();			
			} else {
				isSessionExist = false;
			}		  
		});
	}
	
	// Session is ready api active
	function sessionReady(){
		//alert("sessionReady "+session.uid);	
		isLoggedIn = true;
		dispatchEvent(ActiveFacebookEvent.ON_LOGGEDIN, session);
		dispatchFlashCallback(FlashCallback.LOGGEDIN, session);
	}
	
	// Flash is ready
	function flashReady() {
		isFlashReady = true;
		dispatchFlashCallback(FlashCallback.WAITINGFORLOGIN);
		if(isLoggedIn) {
			dispatchFlashCallback(FlashCallback.LOGGEDIN, session);
		}
	}
	
	// Require login
	function login(perms) {	
		//alert('login');
		if(!isLoggedIn){
			if(perms){
				FB.login(function(response) {
					if (response.session) {					
						session = response.session;
						isSessionExist = true;
						isLoggedIn = true;
						sessionReady();									
						if (response.perms) {						
							dispatchEvent(ActiveFacebookEvent.ON_PERMISSION, response.perms);
							dispatchFlashCallback(FlashCallback.PERMISSION, response.perms);						  
						}					
					} else {
						isLoggedIn = false;
						isSessionExist = false;
					}
				}, {perms:perms});			
			}else{			
				FB.login(function(response) {
					if (response.session) {
						session = response.session;
						isSessionExist = true;
						isLoggedIn = true;
						sessionReady();			
					} else {			
						isLoggedIn = false;
						isSessionExist = false;
					}
				});
			}	
		}
	}
	
	// Logout from Facebook 
	function logout() {	
		//alert('logout');
		if(isLoggedIn){
			FB.logout(function(response) {
				isLoggedIn = false;
				isSessionExist = false;
				dispatchEvent(ActiveFacebookEvent.ON_LOGGEDOUT);
				dispatchFlashCallback(FlashCallback.LOGGEDOUT);
			});
		}	
	}
	
	// Get User Info 
	function userInfo() {
		if(isLoggedIn){
			var fields = 'uid, first_name, last_name, name, sex, birthday, birthday_date, current_location,';
			fields += 'hometown_location, pic_square, pic_small, pic_big, proxied_email, email_hashes, locale, profile_url';			
			var fql = {
				method: 'fql.query',
				query: 'SELECT '+fields+' FROM user WHERE uid='+session.uid
			};
			FB.api(fql, function(response) {
				dispatchEvent(ActiveFacebookEvent.ON_CALL_COMPLETE, response[0], response.error_msg);
				removeEventListener(ActiveFacebookEvent.ON_CALL_COMPLETE);
				dispatchFlashCallback(FlashCallback.CALLCOMPLETE, {res:response[0], ex:response.error_msg});	  
			});
		}
	}	
	
	// Get User Friends 
	function userFriends() {
		if(isLoggedIn){			
			var fql = {
				method: 'fql.query',
				query: 'SELECT uid,name,pic_square,pic_big FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='+session.uid+')'
			};
			FB.api(fql, function(response) {
				dispatchEvent(ActiveFacebookEvent.ON_CALL_COMPLETE, response, response.error_msg);
				removeEventListener(ActiveFacebookEvent.ON_CALL_COMPLETE);
				dispatchFlashCallback(FlashCallback.CALLCOMPLETE, {res:response, ex:response.error_msg});	  
			});
		}
	}
	
	// Stream Publish templateData
	function streamPublish(templateData, display) {
		
		var media;
		
		if(templateData.swf_href)
			media= [{type:'flash', swfsrc:templateData.swf_href, imgsrc:templateData.image_src,width:templateData.width,height:templateData.height,expanded_width:templateData.expanded_width,expanded_height:templateData.expanded_height}];
		else if(templateData.image_href)
			media= [{type:'image', src:templateData.image_src, href:templateData.image_href}]			;
			
		
		var publish = {
			method: 'stream.publish',
			display: 'popup',
			message: templateData.message,
			target_id: templateData.targetId,
			attachment: {
				name: templateData.title,
				caption: templateData.caption,
				description: templateData.description,
				media: media,
				href: templateData.href
			},
			action_links: [
				{ text: templateData.action_txt, href: templateData.action_href }
			],
			user_prompt_message: templateData.user_prompt_message
		};		
		FB.ui(publish, function(data){ /*alert(data)*/ 
			//modifica 210610 cla
			dispatchEvent(ActiveFacebookEvent.ON_CALL_COMPLETE);
			removeEventListener(ActiveFacebookEvent.ON_CALL_COMPLETE);
			dispatchFlashCallback(FlashCallback.CALLCOMPLETE,{});	
			//fine modifica
		});		
	}
	
	function openInvite(exclude_ids)
	{
		///PROBLEMA ACTION...
		var fbml='<fb:fbml> <fb:request-form method="POST" action="http://www.haveabreak.it/index.php?close=1" invite="false" type="Working like a machine? Have a Chair Break" content="Hai mai navigato un sito muovendoti sulla tua sedia? Prova l\'esperienza sul nuovo sito Kit Kat. Partecipa al concorso, in palio iPhone e iPod Shuffle. Working like a machine? Have a Chair Break. <a href=\http://www.haveabreak.it\>www.haveabreak.it</a>"> <fb:multi-friend-selector exclude_ids='+exclude_ids+' showborder="false" actiontext="Working like a machine? Have a Chair Break."> </fb:request-form> </fb:fbml>';

		var dialog = {
		method: 'fbml.dialog',
		display: 'popup',
		fbml: fbml
	};
  
		FB.UIServer.Methods["fbml.dialog"].size = {width:800, height:600};
		FB.ui(dialog, function(){
		
		  dispatchFlashCallback(FlashCallback.CALLCOMPLETE,{});
		  
		});    
	}
	
	// Add event for flash listeners - Under construction
	function addFlashDelegate(objfl) {
		objsFlash.push(objfl);
	}
	
	// Dispatch event for flash listeners - Under construction
	function dispatchFlashCallback(type) {
		for(var i=0; i<objsFlash.length; i++){	
			if(objsFlash[i] != null){
				var obj = objsFlash[i];			
				if( obj[type] != null && obj!=null && isFlashReady ){
					if(arguments.length > 1)
						obj[type](Array.prototype.slice.call(arguments).slice(1)[0]);
					else
						obj[type]();
				}
			}
		}
	}
	
	// Dispatch event for javascript listeners
	function dispatchEvent(type) {
		if(events[type] != null){
			if(arguments.length > 1)
				events[type](Array.prototype.slice.call(arguments).slice(1)[0]);
			else
				events[type]();
		}
	}
	function addEventListener(type, func) {
		events[type] = func;
	}
	function removeEventListener(type, func) {
		events[type] = null;
	}

	return {		
		/**
		* 	Public API
		**/
		init:function(apikey){ 
			apiKey = apikey;					
			init();
		},
		
		login:login,
		logout:logout,
		
		userInfo:userInfo,
		userFriends:userFriends,
		streamPublish:streamPublish,
		openInvite:openInvite,
		
		flashReady:flashReady,
		addFlashDelegate:addFlashDelegate,
		addEventListener:addEventListener,
		removeEventListener:removeEventListener
		
		
	};
	
}();



