/*
Sky.FacebookUtil
copyright by MySign AG (http://www.mysign.ch)
depencies: Prototype 1.6.1
		   Sky.PrototypeExtensions
documentation:
	Tutoweb:	http://tutoweb.intranet/de/facebook_widgets_einbauen_content---1--1443--317.html
	Facebook:	http://developers.facebook.com/docs/
*/

// creating namespace
var Sky;
if ( !Sky ) Sky = {};

Sky.FacebookUtil = Class.create();

Sky.FacebookUtil._ALL_JS_LOADED = false;

Sky.FacebookUtil.CODE_VERSION_XFBML = 1;
Sky.FacebookUtil.CODE_VERSION_HTML5 = 2;

// @see Sky.FacebookUtil#insertLikeButton (Verb to display)
Sky.FacebookUtil.LIKE_BUTTON_VERB_LIKE = 'like';
Sky.FacebookUtil.LIKE_BUTTON_VERB_RECOMMEND = 'recommend';

//@see Sky.FacebookUtil#insertLikeButton (Layout Style)
Sky.FacebookUtil.LIKE_BUTTON_STYLE_STANDARD = 'standard';
Sky.FacebookUtil.LIKE_BUTTON_STYLE_BUTTON_COUNT = 'button_count';
Sky.FacebookUtil.LIKE_BUTTON_STYLE_BOX_COUNT = 'box_count';

//@see Sky.FacebookUtil#insertLikeButton (Font)
Sky.FacebookUtil.LIKE_BUTTON_FONT_ARIAL = 'arial';
Sky.FacebookUtil.LIKE_BUTTON_FONT_LUCIDA_GRANDE = 'lucida grande';
Sky.FacebookUtil.LIKE_BUTTON_FONT_SEGOE_UI = 'segoe ui';
Sky.FacebookUtil.LIKE_BUTTON_FONT_TAHOMA = 'tahoma';
Sky.FacebookUtil.LIKE_BUTTON_FONT_TREBUCHET_MS = 'trebuchet ms';
Sky.FacebookUtil.LIKE_BUTTON_FONT_VERDANA = 'verdana';

//@see Sky.FacebookUtil#insertLikeButton (Color Scheme)
Sky.FacebookUtil.LIKE_BUTTON_COLORSCHEME_LIGHT = 'light';
Sky.FacebookUtil.LIKE_BUTTON_COLORSCHEME_DARK = 'dark';

//@see Sky.FacebookUtil#insertLikeButton (Color Scheme)
Sky.FacebookUtil.LIKE_BOX_COLORSCHEME_LIGHT = 'light';
Sky.FacebookUtil.LIKE_BOX_COLORSCHEME_DARK = 'dark';

//@see Sky.FacebookUtil#insertCommentsBox (Color Scheme)
Sky.FacebookUtil.COMMENTS_BOX_COLORSCHEME_LIGHT = 'light';
Sky.FacebookUtil.COMMENTS_BOX_COLORSCHEME_DARK = 'dark';

Sky.FacebookUtil._AUTH_REVOKE_AUTHORIZATION = "Auth.revokeAuthorization";
Sky.FacebookUtil._CONNECT_BUTTON_TEXTS = {
		"de_DE" : "Mit Facebook anmelden",
		"de_CH" : "Mit Facebook anmelden",
		"fr_CH" : "Se connecter avec Facebook",
		"it_CH" : "Collegati tramite Facebook",
		"en_US" : "Connect with Facebook"
};

/*
 * default permissions supported by facebook
 * @see http://developers.facebook.com/docs/authentication/permissions
 */
Sky.FacebookUtil.PERMISSION_LIKES = "user_likes";
Sky.FacebookUtil.PERMISSION_PUBLISHSTREAM = "publish_stream";

// supported locales from facebook (20.07.2010)
Sky.FacebookUtil._FB_LOCALES = [
	{ 'name': 'Catalan', 'locale': 'ca_ES' },
	{ 'name': 'Czech', 'locale': 'cs_CZ' },
	{ 'name': 'Welsh', 'locale': 'cy_GB' },
	{ 'name': 'Danish', 'locale': 'da_DK' },
	{ 'name': 'German', 'locale': 'de_DE' },
	{ 'name': 'Basque', 'locale': 'eu_ES' },
	{ 'name': 'English (Pirate)', 'locale': 'en_PI' },
	{ 'name': 'English (Upside Down)', 'locale': 'en_UD' },
	{ 'name': 'Cherokee', 'locale': 'ck_US' },
	{ 'name': 'English (US)', 'locale': 'en_US' },
	{ 'name': 'Spanish', 'locale': 'es_LA' },
	{ 'name': 'Spanish (Chile)', 'locale': 'es_CL' },
	{ 'name': 'Spanish (Colombia)', 'locale': 'es_CO' },
	{ 'name': 'Spanish (Spain)', 'locale': 'es_ES' },
	{ 'name': 'Spanish (Mexico)', 'locale': 'es_MX' },
	{ 'name': 'Spanish (Venezuela)', 'locale': 'es_VE' },
	{ 'name': 'Finnish (test)', 'locale': 'fb_FI' },
	{ 'name': 'Finnish', 'locale': 'fi_FI' },
	{ 'name': 'French (France)', 'locale': 'fr_FR' },
	{ 'name': 'Galician', 'locale': 'gl_ES' },
	{ 'name': 'Hungarian', 'locale': 'hu_HU' },
	{ 'name': 'Italian', 'locale': 'it_IT' },
	{ 'name': 'Japanese', 'locale': 'ja_JP' },
	{ 'name': 'Korean', 'locale': 'ko_KR' },
	{ 'name': 'Norwegian (bokmal)', 'locale': 'nb_NO' },
	{ 'name': 'Norwegian (nynorsk)', 'locale': 'nn_NO' },
	{ 'name': 'Dutch', 'locale': 'nl_NL' },
	{ 'name': 'Polish', 'locale': 'pl_PL' },
	{ 'name': 'Portuguese (Brazil)', 'locale': 'pt_BR' },
	{ 'name': 'Portuguese (Portugal)', 'locale': 'pt_PT' },
	{ 'name': 'Romanian', 'locale': 'ro_RO' },
	{ 'name': 'Russian', 'locale': 'ru_RU' },
	{ 'name': 'Slovak', 'locale': 'sk_SK' },
	{ 'name': 'Slovenian', 'locale': 'sl_SI' },
	{ 'name': 'Swedish', 'locale': 'sv_SE' },
	{ 'name': 'Thai', 'locale': 'th_TH' },
	{ 'name': 'Turkish', 'locale': 'tr_TR' },
	{ 'name': 'Kurdish', 'locale': 'ku_TR' },
	{ 'name': 'Simplified Chinese (China)', 'locale': 'zh_CN' },
	{ 'name': 'Traditional Chinese (Hong Kong)', 'locale': 'zh_HK' },
	{ 'name': 'Traditional Chinese (Taiwan)', 'locale': 'zh_TW' },
	{ 'name': 'Leet Speak', 'locale': 'fb_LT' },
	{ 'name': 'Afrikaans', 'locale': 'af_ZA' },
	{ 'name': 'Albanian', 'locale': 'sq_AL' },
	{ 'name': 'Armenian', 'locale': 'hy_AM' },
	{ 'name': 'Azeri', 'locale': 'az_AZ' },
	{ 'name': 'Belarusian', 'locale': 'be_BY' },
	{ 'name': 'Bengali', 'locale': 'bn_IN' },
	{ 'name': 'Bosnian', 'locale': 'bs_BA' },
	{ 'name': 'Bulgarian', 'locale': 'bg_BG' },
	{ 'name': 'Croatian', 'locale': 'hr_HR' },
	{ 'name': 'Dutch (België)', 'locale': 'nl_BE' },
	{ 'name': 'English (UK)', 'locale': 'en_GB' },
	{ 'name': 'Esperanto', 'locale': 'eo_EO' },
	{ 'name': 'Estonian', 'locale': 'et_EE' },
	{ 'name': 'Faroese', 'locale': 'fo_FO' },
	{ 'name': 'French (Canada)', 'locale': 'fr_CA' },
	{ 'name': 'Georgian', 'locale': 'ka_GE' },
	{ 'name': 'Greek', 'locale': 'el_GR' },
	{ 'name': 'Gujarati', 'locale': 'gu_IN' },
	{ 'name': 'Hindi', 'locale': 'hi_IN' },
	{ 'name': 'Icelandic', 'locale': 'is_IS' },
	{ 'name': 'Indonesian', 'locale': 'id_ID' },
	{ 'name': 'Irish', 'locale': 'ga_IE' },
	{ 'name': 'Javanese', 'locale': 'jv_ID' },
	{ 'name': 'Kannada', 'locale': 'kn_IN' },
	{ 'name': 'Kazakh', 'locale': 'kk_KZ' },
	{ 'name': 'Latin', 'locale': 'la_VA' },
	{ 'name': 'Latvian', 'locale': 'lv_LV' },
	{ 'name': 'Limburgish', 'locale': 'li_NL' },
	{ 'name': 'Lithuanian', 'locale': 'lt_LT' },
	{ 'name': 'Macedonian', 'locale': 'mk_MK' },
	{ 'name': 'Malagasy', 'locale': 'mg_MG' },
	{ 'name': 'Malay', 'locale': 'ms_MY' },
	{ 'name': 'Maltese', 'locale': 'mt_MT' },
	{ 'name': 'Marathi', 'locale': 'mr_IN' },
	{ 'name': 'Mongolian', 'locale': 'mn_MN' },
	{ 'name': 'Nepali', 'locale': 'ne_NP' },
	{ 'name': 'Punjabi', 'locale': 'pa_IN' },
	{ 'name': 'Romansh', 'locale': 'rm_CH' },
	{ 'name': 'Sanskrit', 'locale': 'sa_IN' },
	{ 'name': 'Serbian', 'locale': 'sr_RS' },
	{ 'name': 'Somali', 'locale': 'so_SO' },
	{ 'name': 'Swahili', 'locale': 'sw_KE' },
	{ 'name': 'Filipino', 'locale': 'tl_PH' },
	{ 'name': 'Tamil', 'locale': 'ta_IN' },
	{ 'name': 'Tatar', 'locale': 'tt_RU' },
	{ 'name': 'Telugu', 'locale': 'te_IN' },
	{ 'name': 'Malayalam', 'locale': 'ml_IN' },
	{ 'name': 'Ukrainian', 'locale': 'uk_UA' },
	{ 'name': 'Uzbek', 'locale': 'uz_UZ' },
	{ 'name': 'Vietnamese', 'locale': 'vi_VN' },
	{ 'name': 'Xhosa', 'locale': 'xh_ZA' },
	{ 'name': 'Zulu', 'locale': 'zu_ZA' },
	{ 'name': 'Khmer', 'locale': 'km_KH' },
	{ 'name': 'Tajik', 'locale': 'tg_TJ' },
	{ 'name': 'Arabic', 'locale': 'ar_AR' },
	{ 'name': 'Hebrew', 'locale': 'he_IL' },
	{ 'name': 'Urdu', 'locale': 'ur_PK' },
	{ 'name': 'Persian', 'locale': 'fa_IR' },
	{ 'name': 'Syriac', 'locale': 'sy_SY' },
	{ 'name': 'Yiddish', 'locale': 'yi_DE' },
	{ 'name': 'Guaraní', 'locale': 'gn_PY' },
	{ 'name': 'Quechua', 'locale': 'qu_PE' },
	{ 'name': 'Aymara', 'locale': 'ay_BO' },
	{ 'name': 'Northern Sámi', 'locale': 'se_NO' },
	{ 'name': 'Pashto', 'locale': 'ps_AF' },
	{ 'name': 'Klingon', 'locale': 'tl_ST' }
];

Sky.FacebookUtil.prototype =
{
	/**
	 * @param appId YOUR APP ID
	 * @param opts have a look at the default options in constructor
	 */
	initialize: function ( appId, opts )
	{
		// default options
		this.options = 
		{
			/*
			 * default options used by FB.init and Sky.FacebookUtil
			 */
			status: true,				// check login status
			cookie: true,				// enable cookies to allow the server to access the session
			xfbml: true,				// parse XFBML
			codeVersion: Sky.FacebookUtil.CODE_VERSION_XFBML,
			autoGrow: null,				// https://developers.facebook.com/docs/reference/javascript/FB.Canvas.setAutoGrow/
			fbRootElementId: 'fb-root',	// the element where fb-js is written to
			locale: 'de_CH',			// the current locale (@see Sky.FacebookUtil._FB_LOCALES)
			languagepath: 'de',			// the current languagepath (@see Sky.FacebookUtil#_facebookAuthenticate)
			webroot: '/',				// the current webroot (@see Sky.FacebookUtil#_facebookAuthenticate)
			callbackAfterInit: null,	// method called after FB.init
			callbackAfterLoad: function () {
				this.style.visibility = "visible";
			},							// method to call after parse with FB.XFBML
			
			/*
			 * Mobile
			 */
			isMobileApp: false,
			mobileLoginDivId: 'fb-login-mobile',
			mobileLoginButtonLabel: 'mobile login',
			mobileLoginRedirectURL: '', 		// required if is mobile app!
			
			/*
			 * fan-box options
			 * @deprecated by facebook @use Sky.FacebookUtil#insertLikeBox
			 */
			fanBoxConnections: 10,
			fanBoxWidth: 193,
			fanBoxHeight: 300,
			fanBoxShowHeader : 'true',
			fanBoxShowStream: 0,
			fanBoxShowLogobar: false,
			fanBoxCSS: null,
			
			/*
			 * like-box options
			 * @see Sky.FacebookUtil#insertLikeBox
			 */
			likeBoxWidth: 292,			// the width of the plugin in pixels.
			likeBoxHeight: 390,			// the height of the plugin in pixels.
			likeBoxShowFaces: true,		// specifies whether or not to display profile photos in the plugin.
			likeBoxShowHeader: 'true',	// specifies whether to display the Facebook header at the top of the plugin.
			likeBoxShowStream: 'true',	// specifies whether to display a stream of the latest posts from the Page's wall
			likeBoxColorScheme: Sky.FacebookUtil.LIKE_BOX_COLORSCHEME_LIGHT, // the color scheme for the plugin.
			likeCallback: null,			// called when user liked this page
			likeBoxBorderColor: null,   // the border color
			
			/*
			 * user name options
			 * @see http://developers.facebook.com/docs/reference/fbml/name/
			 * @see Sky.FacebookUtil#insertUserName
			 */
			userNameUid: 'loggedinuser',	// The ID of the user or Page whose name you want to show. Alternately, you can use "profileowner" only on a user's profile; you can use "loggedinuser" only on canvas pages.
			userNameFirstnameonly: 'false',	// Show only the user's first name.
			userNameLinked: 'false',		// Link to the user's profile.
			userNameLastnameonly: 'false',	// Show only the user's last name.
			userNamePossessive: 'false',	// Make the user's name possessive (e.g. Joe's instead of Joe).
			userNameReflexive: 'false',		// Use "yourself" if useyou is true.
			userNameShownetwork: 'false',	// Displays the primary educational network for the uid, if applicable. Other networks do not show.
			userNameUseyou: 'false',		// Use "you" if uid matches the logged in user.
			userNameIfcantsee: null,		// Alternate text to display if the logged in user cannot access the user specified. To specify an empty string instead of the default, use ifcantsee="". Default value is Facebook User
			userNameCapitalize: 'false',	// Capitalize the text if useyou### true and loggedinuseruid.
			userNameSubjectid: null,		// The Facebook ID of the subject of the sentence where this name is the object of the verb of the sentence. Will use the reflexive when appropriate. When ''subjectid'' is used, ''uid'' is considered to be the object and ''uid'''s name is produced.
			
			// @deprecated
			likeBoxConnections: 10,		// number of users liked this page
			
			/*
			 * comments-box options
			 * @see Sky.FacebookUtil#insertCommentsBox
			 */
			commentsHref: null,			// the URL for this Comments plugin. News feed stories on Facebook will link to this URL. 
			commentsWidth: 550,			// the width of the plugin in pixels. Minimum recommended width: 400px. 
			commentsColorScheme: Sky.FacebookUtil.COMMENTS_BOX_COLORSCHEME_LIGHT, // the color scheme for the plugin.
			commentsNumPosts: 10,		// the number of comments to show by default. Default: 10. Minimum: 1
			// @deprecated: use commentsHref
			commentsXid: null,
			// @deprecated: use commentsColorScheme
			commentsCSS: null,
			
			/*
			 * like-button options
			 * @see Sky.FacebookUtil#insertLikeButton
			 */
			likeButtonURL: null,		// the URL to like. In XFBML, defaults to the current page.
			likeButtonType: Sky.FacebookUtil.LIKE_BUTTON_STYLE_STANDARD, // determines the size and amount of social context next to the button
			likeButtonShowFaces: false,	// Show profile pictures below the button.
			likeButtonWidth: 450,		// the width of the like button in pixels
			likeButtonVerb: Sky.FacebookUtil.LIKE_BUTTON_VERB_LIKE, // the verb to display in the button.
			likeButtonFont: Sky.FacebookUtil.LIKE_BUTTON_FONT_ARIAL, // the font of the plugin.
			likeButtonColorScheme: Sky.FacebookUtil.LIKE_BUTTON_COLORSCHEME_LIGHT, // the color scheme of the plugin.
			
			/*
			 * share-button options
			 * @deprecated by facebook @use Sky.FacebookUtil#insertLikeButton
			 */
			shareButtonType: 'button_count',
			
			// login/connect-button options
			loginButtonCondition: "", // string 	 Indicates whether the button is visible or hidden. See the Notes below for further explanation. 	
			loginButtonSize: "medium", // string 	Specifies the size of the button. Specify icon to display a favicon only, or small, medium, large, or xlarge. (Default value is medium.) 	
			loginButtonAutologoutlink: 	false, // bool 	If true and the user is already connected and has a session, then the button image changes to indicate the user can log out. Clicking the button logs the user out of Facebook and all connected sessions. (Default value is false.) 	
			loginButtonBackground: "light", // string 	Specifies the button image to use that is anti-aliased to match the background of your site -- whether it's pure white, light, or dark. Specify white, dark, or light. (Default value is light.)
			// Note: You don't specify this attribute if you are using v="2". 	
			loginButtonLength: "long", 	// string 	Specifies which text label to use on a button with size specified as small, medium, large, or xlarge. Specify short for the text label Connect only or long for the text label Connect with Facebook. If you are rendering the login button text by including it within the fb:login-button tags, you don't specify a length at all. (Default value is short.) 	
			// onlogin 	string 	JavaScript code to execute when the user gains a Facebook session (that is, after logging into Facebook and authorizing the site). 	
			loginButtonV: "", 
			postAuthenticationCallback: null,
			connectPermissions: 'email,user_hometown,user_location',
			callbackAfterLoginClick: null
		};
		Object.extend( this.options, opts || {} );
		
		// set xfbml use to false, when using HTML5
		if ( this.options.codeVersion == Sky.FacebookUtil.CODE_VERSION_HTML5 && this.options.xfbml )
		{
			this.options.xfbml = false;
		}
		
		var tmpLocale = this.options.locale;
		if ( tmpLocale.length > 5 && tmpLocale.indexOf( '_' ) != tmpLocale.lastIndexOf( '_' ) )
		{
			tmpLocale = tmpLocale.substring( 0, tmpLocale.lastIndexOf( '_' ) );
		}
		this.options.locale = tmpLocale;
		
		this.appId = appId;
		this.fbAuthResponse = null;
		
		var tmpOpts = this.options;

		window.fbAsyncInit = function() 
		{
			// @see http://developers.facebook.com/docs/reference/javascript/FB.init
			FB.init( {
				appId: appId,
				status: tmpOpts.status,
				cookie: tmpOpts.cookie,
				xfbml: tmpOpts.xfbml,
				oauth : true // force OAuth 2.0, @see https://developers.facebook.com/blog/post/525/
			} );
			
			if ( tmpOpts.autoGrow != null )
			{
				FB.Canvas.setAutoGrow( tmpOpts.autoGrow );
			}
			
			if ( tmpOpts.callbackAfterInit != null )
			{
				tmpOpts.callbackAfterInit.call();
			}
			
			/*
			 * @see http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe
			 */
			FB.Event.subscribe( 'edge.create', function( response ) {
				if ( this.likeCallback )
				{
					this.likeCallback();
				}
			}.bind( tmpOpts ) );
	    };
	    
	    // Asynchronous Loading of Facebook's all.js
	    if ( !Sky.FacebookUtil._ALL_JS_LOADED )
	    {
	    	Sky.FacebookUtil._ALL_JS_LOADED = true;
			
	    	// find the current locale supported by facebook
			var locale = null;
			var tmpSecondLocale = null;
			
			for ( var i = 0; i < Sky.FacebookUtil._FB_LOCALES.length; i++ )
			{
				var tmpLocaleObj = Sky.FacebookUtil._FB_LOCALES[i];
				var tmpLocale = tmpLocaleObj.locale;
				
				if ( this.options.locale == tmpLocale )
				{
					locale = tmpLocale;
					break;
				}
				else if ( tmpSecondLocale == null && this.options.locale.indexOf( tmpLocale.substring( 0, 3 ) ) >= 0 )
				{
					tmpSecondLocale = tmpLocale;
				}
			}
			
			if ( locale == null )
			{
				locale = tmpSecondLocale;
				if ( locale == null )
				{
					locale = 'de_DE'; // fallback: default locale is de_DE
				}
			}
			
			// if not exists, create the fb-root div element
			if ( !Element.myIsExisting( this.options.fbRootElementId ) )
			{
				$(document.body).insert( new Element( 'div', { id: this.options.fbRootElementId } ) );
			}
			
			// @see http://developers.facebook.com/docs/reference/javascript/FB.init
			var js = document.createElement('script');
			js.id = 'facebook-jssdk';
			js.async = true;
	    	js.src = '//connect.facebook.net/' + locale + '/all.js';
			document.getElementsByTagName( 'head' )[0].appendChild( js );
	    }
	},
	
	/**
	 * login into facebook and get permissions
	 * @param perms Comma separated list of Extended permissions (@see http://developers.facebook.com/docs/authentication/permissions)
	 * @param doFBAuthenticate login with facebook account to cms
	 * @param if set, then this callback is called after session response has been set
	 * @see http://developers.facebook.com/docs/reference/javascript/FB.login
	 */
	login: function ( perms, doFBAuthenticate, callback )
	{
		if ( callback==undefined )
		{
			callback = null;
		}
		if ( doFBAuthenticate )
		{
			callback = this._facebookAuthenticate;
		}
		
		if ( this.isLoggedIn() )
		{
			this._handleAuthResponse( this.fbAuthResponse, callback );
		}
		else
		{
			if ( this.options.isMobileApp )
			{
				if ( !Element.myIsExisting( this.options.mobileLoginDivId ) )
				{
					$(document.body).insert( new Element( 'div', { id: this.options.mobileLoginDivId } ) );
				}
				$(this.options.mobileLoginDivId).innerHTML = '<a id="facebook-login-button-mobile" href="https://m.facebook.com/dialog/oauth?client_id='+this.appId+'&redirect_uri='+this.options.mobileLoginRedirectURL+'?scope=?response_type=token"><span>'+this.options.mobileLoginButtonLabel+'</span></a>';
			}
			else
			{
				FB.login( function( response ) { this._handleAuthResponse( response, callback ); }.bind( this ), { scope: perms } );
			}
		}
	},
	
	/**
	 * logout from facebook
	 * @param callback the callback function
	 * @see http://developers.facebook.com/docs/reference/javascript/FB.logout
	 */
	logout: function ( callback )
	{
		var tmpThis = this;
		FB.logout( function( response ) { tmpThis._handleAuthResponse( response, callback ); } );
	},
	
	/**
	 * disconnect from the website
	 * @deprecated by facebook http://developers.facebook.com/docs/reference/javascript/FB.api
	 */
	disconnect: function ( callback )
	{
		var tmpThis = this;
		FB.api( { method: Sky.FacebookUtil._AUTH_REVOKE_AUTHORIZATION }, function( response ) { tmpThis._handleAuthResponse( response, callback ); } );
	},
	
	/**
	 * Find out the current status from the server, and get a session if the user is connected
	 * @param callback the callback function
	 * @see http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus
	 */
	getLoginStatus: function ( callback )
	{
		var tmpThis = this;
		FB.getLoginStatus( function( response ) { tmpThis._handleAuthResponse( response, callback ); } );
	},
	
	/**
	 * returns true if the user is logged in (#login or #getLoginStatus has to be called before)
	 */
	isLoggedIn: function ()
	{
		return ( this.fbAuthResponse != null && this.fbAuthResponse.status != null && 
				 this.fbAuthResponse.status == 'connected' );
	},
	
	/**
	 * returns the facebook user id if the user is logged in (#login or #getLoginStatus has to be called before)
	 */
	getUserID: function ()
	{
		var returnValue = null;
		
		if ( this.fbAuthResponse != null && this.fbAuthResponse.authResponse != null )
		{
			returnValue = this.fbAuthResponse.authResponse.userID;
		}
		
		return returnValue;
	},
	
	getUserAccessToken: function ()
	{
		var returnValue = null;
		
		if ( this.fbAuthResponse != null && this.fbAuthResponse.authResponse != null )
		{
			returnValue = this.fbAuthResponse.authResponse.accessToken;
		}
		
		return returnValue;
	},

	
	/**
	 * Handle the session response from:
	 * 		#login
	 * 		#logout
	 * 		#disconnect
	 * 		#getLoginStatus
	 */
	_handleAuthResponse: function ( response, callback )
	{
		this.fbAuthResponse = response;
		if ( callback != null )
		{
			callback.call( this, this.fbAuthResponse );
		}
	},
	
	/**
	 * insert the facebook like-box
	 * @param likeBoxContainer container to append the like-box
	 * @param profileId the id of fanpage or app
	 * @param opts
	 * 		likeBoxWidth
	 * 		likeBoxHeight
	 * 		likeBoxConnections
	 * 		likeBoxShowFaces
	 * 		likeBoxShowStream
	 * 		likeBoxShowHeader
	 *		likeBoxColorScheme
	 * 		callbackAfterLoad
	 * @see http://developers.facebook.com/docs/reference/plugins/like-box
	 */
	insertLikeBox: function ( likeBoxContainer, profileId, opts )
	{
		Object.extend( this.options, opts || {} );
		likeBoxContainer.innerHTML = '<fb:like-box profile_id="' + profileId +
			'" width="' + this.options.likeBoxWidth +
			'" height="' + this.options.likeBoxHeight + 
			'" connections="' + this.options.likeBoxConnections +
			'" show_faces="' + this.options.likeBoxShowFaces +
			'" stream="' + this.options.likeBoxShowStream + 
			'" header="' + this.options.likeBoxShowHeader +
			'" border_color ="' + this.options.likeBoxBorderColor +
			'" colorscheme="' + this.options.likeBoxColorScheme + '"></fb:like-box>';
		FB.XFBML.parse( likeBoxContainer, this.options.callbackAfterLoad.bind( likeBoxContainer ) );
	},
	
	/**
	 * insert the facebook user name
	 * @param userNameContainer container to append the user name
	 * @param opts
	 * 		userNameUid
	 * 		userNameFirstnameonly
	 * 		userNameLinked
	 * 		userNameLastnameonly
	 * 		userNamePossessive
	 * 		userNameReflexive
	 * 		userNameShownetwork
	 * 		userNameUseyou
	 * 		userNameIfcantsee
	 * 		userNameCapitalize
	 * 		userNameSubjectid
	 * 		callbackAfterLoad
	 * @see http://developers.facebook.com/docs/reference/fbml/name/
	 */
	insertUserName: function ( userNameContainer, opts )
	{
		Object.extend( this.options, opts || {} );
		var fbml = '<fb:name uid="' + this.options.userNameUid +
			'" firstnameonly="' + this.options.userNameFirstnameonly +
			'" linked="' + this.options.userNameLinked +
			'" lastnameonly="' + this.options.userNameLastnameonly +
			'" possessive="' + this.options.userNamePossessive +
			'" reflexive="' + this.options.userNameReflexive +
			'" shownetwork="' + this.options.userNameShownetwork +
			'" useyou="' + this.options.userNameUseyou + '"';
			if ( this.options.userNameIfcantsee != null )
			{
				fbml += ' ifcantsee="' + this.options.userNameIfcantsee + '"';
			}
			fbml += ' capitalize="' + this.options.userNameCapitalize + '"';
			if ( this.options.userNameSubjectid != null )
			{
				fbml += ' subjectid="' + this.options.userNameSubjectid + '"';
			}
			fbml += '></fb:name>';
			userNameContainer.innerHTML = fbml;
		FB.XFBML.parse( userNameContainer, this.options.callbackAfterLoad.bind( userNameContainer ) );
	},
	
	/**
	 * insert the facebook comments-box
	 * @param commentsContainer container to append the comments
	 * @param opts
	 * 		commentsHref
	 * 		commentsWidth
	 * 		commentsColorScheme
	 * 		commentsNumPosts
	 * 		callbackAfterLoad
	 * @see http://developers.facebook.com/docs/reference/plugins/comments
	 */
	insertCommentsBox: function ( commentsContainer, opts )
	{
		Object.extend( this.options, opts || {} );
		
		var fbml = '';
		if ( this.options.codeVersion == Sky.FacebookUtil.CODE_VERSION_HTML5 )
		{
			fbml = '<div class="fb-comments" data-num-posts="' + this.options.commentsNumPosts +
				'" data-width="' + this.options.commentsWidth +
				'" data-colorscheme="' + this.options.commentsColorScheme + '"';
			
			if ( this.options.commentsHref != null )
			{
				fbml += ' data-href="' + this.options.commentsHref + '"';
			}
			
			fbml += '></div>';
		}
		// for older webs use XFBML
		else
		{
			fbml = '<fb:comments width="' + this.options.commentsWidth + '" num_posts="' + 
				this.options.commentsNumPosts + '" colorscheme="' + this.options.commentsColorScheme + '"';
			
			if ( this.options.commentsHref != null )
			{
				fbml += ' href="' + this.options.commentsHref + '"';
			}
			
			// @deprecated: start
			if ( this.options.commentsXid != null )
			{
				fbml += ' xid="' + this.options.commentsXid + '"';
			}
			if ( this.options.commentsCSS != null )
			{
				fbml += ' css="' + this.options.commentsCSS + '"';
			}
			// @deprecated: end
			
			fbml += '></fb:comments>';
		}
		
		commentsContainer.innerHTML = fbml;
		FB.XFBML.parse( commentsContainer, this.options.callbackAfterLoad.bind( commentsContainer ) );
	},
	
	/**
	 * insert the facebook like-button
	 * @param likeButtonContainer container to append the like
	 * @param opts
	 * 		likeButtonType
	 * 		likeButtonVerb
	 * 		likeButtonShowFaces
	 * 		likeButtonFont
	 * 		likeButtonColorScheme
	 * 		likeButtonWidth
	 * 		likeButtonURL
	 * 		callbackAfterLoad
	 * @see http://developers.facebook.com/docs/reference/plugins/like
	 */
	insertLikeButton: function ( likeButtonContainer, opts )
	{
		Object.extend( this.options, opts || {} );
		var fbml = '<fb:like ' +
			'layout="' + this.options.likeButtonType + '" ' +
			'action="' + this.options.likeButtonVerb + '" ' +
			'show_faces="' + this.options.likeButtonShowFaces + '" ' +
			'font="' + this.options.likeButtonFont + '" ' +
			'colorscheme="' + this.options.likeButtonColorScheme + '" ' +
			'width="' + this.options.likeButtonWidth + '"';
		if ( this.options.likeButtonURL != null )
		{
			fbml += ' href="' + this.options.likeButtonURL + '"';
		}
		fbml += '></fb:like>';
		likeButtonContainer.innerHTML = fbml;
		FB.XFBML.parse( likeButtonContainer, this.options.callbackAfterLoad.bind( likeButtonContainer ) );
	},
	
	/**
	 * insert the facebook share-button
	 * @param shareButtonContainer container to append the share-button
	 * @param opts
	 * 		shareButtonType
	 * 		callbackAfterLoad
	 * @param url only needed if not equal the current url
	 * @deprecated by facebook @use Sky.FacebookUtil#insertLikeButton
	 */
	insertShareButton: function ( shareButtonContainer, opts, url )
	{
		Object.extend( this.options, opts || {} );
		var fbml = '<fb:share-button class="url" type="' + this.options.shareButtonType + '" href="';
		if ( url != null && url != '' )
		{
			fbml += url;
		}
		else
		{
			fbml += location.href;
		}
		fbml += '"></fb:share-button>';
		shareButtonContainer.innerHTML = fbml;
		FB.XFBML.parse( shareButtonContainer, this.options.callbackAfterLoad.bind( shareButtonContainer ) );
	},

	/**
	 * insert the facebook fan-box
	 * @param fanBoxContainer container to append the fan
	 * @param profileId the id of fanpage or app
	 * @param opts
	 * 		fanBoxWidth
	 * 		fanBoxHeight
	 * 		fanBoxConnections
	 * 		fanBoxShowStream
	 * 		fanBoxShowHeader
	 * 		fanBoxShowLogobar
	 * 		fanBoxCSS
	 * 		callbackAfterLoad
	 * @deprecated by facebook @use Sky.FacebookUtil#insertLikeBox
	 */
	insertFanBox: function ( fanBoxContainer, profileId, opts )
	{
		Object.extend( this.options, opts || {} );
		var fbml = '<fb:fan profile_id="' + profileId + 
			'" width="' + this.options.fanBoxWidth + '" height="' + this.options.fanBoxHeight +
			'" connections="' + this.options.fanBoxConnections + '" stream="' + this.options.fanBoxShowStream + 
			'" header="' + this.options.fanBoxShowHeader + '" logobar="' + this.options.fanBoxShowLogobar + '"';
		if ( this.options.fanBoxCSS != null )
		{
			fbml += ' css="' + this.options.fanBoxCSS + '"';
		}
		fbml += '></fb:fan>';
		fanBoxContainer.innerHTML = fbml;
		FB.XFBML.parse( fanBoxContainer, this.options.callbackAfterLoad.bind( fanBoxContainer ) );
	},
	
	/**
	 * get the profile informations
	 * @param profileNameOrId
	 * @param callback the callback function
	 */
	getProfileInfo: function ( profileNameOrId, callback )
	{
		FB.api( '/' + profileNameOrId, function( response ) { callback.call( this, response ); }.bind( this ) );
	},
	
	/**
	 * get the user permissions for this app
	 * @see http://developers.facebook.com/docs/reference/api/user/
	 * @param callback the callback function
	 */
	getUserAppPermissions: function ( callback )
	{
		FB.api( '/me/permissions', function( response ) { callback.call( this, response ); }.bind( this ) );
	},
	
	/**
	 * insert the facebook login/connect-button
	 * @param loginButtonContainer container to append the login/connect-button
	 * @param opts
	 * 		locale
	 * 		callbackAfterLoginClick
	 * 		connectPermissions
	 */
	insertLoginButton: function ( loginButtonContainer, opts, dontAuhenticate, callback )
	{
		Object.extend( this.options, opts || {} );
		
		var fbLoginText = Sky.FacebookUtil._CONNECT_BUTTON_TEXTS[this.options.locale];
		if ( fbLoginText == null )
		{
			fbLoginText = Sky.FacebookUtil._CONNECT_BUTTON_TEXTS['de_CH'];
		}
		
		var html = '<a href="#" id="facebook-login-button">' + 
					'<span>'+
					fbLoginText +
					'</span></a>';
		loginButtonContainer.innerHTML = html;
		
		$('facebook-login-button').observe( 'click', function() {
			if ( this.options.callbackAfterLoginClick != null )
			{
				this.options.callbackAfterLoginClick( this );
			}
			this.login( this.options.connectPermissions, !dontAuhenticate, callback );
		}.bind( this ) );
	},
	
	/**
	 * authenticate user in core
	 */
	_facebookAuthenticate: function ( response )
	{
		if ( this.fbAuthResponse != null && this.fbAuthResponse.authResponse != null )
		{
			var uid = this.fbAuthResponse.authResponse.userID;
			var accesstoken = this.fbAuthResponse.authResponse.accessToken;
			var accesstokenexpires = this.fbAuthResponse.authResponse.expiresIn.toString();
			var authenticationUri = this.options.webroot + "myinterfaces/" + this.options.languagepath + "/sky/fb/users/" + uid + ".json";
			// authenticate facebook user via an Ajax call...
			new Ajax.Request( authenticationUri, {
				method: 'put',
				parameters: {
					"accesstoken": accesstoken,
					"accesstokenexpiresinseconds": accesstokenexpires,
					"authtype": "fbjs"
				},
				onComplete: this.options.postAuthenticationCallback
			} );
		}
		// else do NOTHING, cause the login was (most probably) 
		// canceled by the user
	},
	
	/**
	 * publish something to a user, page or app
	 * @param params
	 * 		message	The message
	 * 		picture	If available, a link to the picture included with this post
	 * 		link	The link attached to this post
	 * 		name	The name of the link
	 * 		caption	The caption of the link (appears beneath the link name)
	 * 		description	A description of the link (appears beneath the link caption)
	 * 		source	If available, the source link attached to this post (for example, a flash or video file)
	 * @param profileId id to where the wall post has to published
	 * @param callback the callback function
	 * @see http://developers.facebook.com/docs/reference/api/post
	 */
	publishToStream: function ( params, profileId, callback, requestPerms )
	{
		if( profileId == null || Object.isUndefined( profileId ) )
		{
			profileId = "me";
		}
		
		var params = {
			"profileId": profileId,
			"params": params,
			"callback": callback
		};
		// compatibility: if requestPerms is not set, request permission!
		if ( requestPerms==undefined || 
				requestPerms==true )
		{
			this.requestUserAppPermission( Sky.FacebookUtil.PERMISSION_PUBLISHSTREAM, this._publishToStreamCallback, params );
		}
		else
		{
			params._permissionGranted = true;
			this._publishToStreamCallback( params );
		}
	},
	
	/**
	 * callback for Sky.FacebookUtil#publishToStream after checking the user permissions
	 */
	_publishToStreamCallback: function ( params )
	{
		/*
		 * format to Old Api
		 * do not use action_links in params!
		 * @deprecated
		 */		 
		if ( params._permissionGranted )
		{
			if ( params.params.action_links )
			{
				Object.extend( params.params, {
					method: 'stream_publish',
					attachment: { 
						href: params.params.link, 
						name: params.params.name,
						description: params.params.description,
						media: [{
							type: 'image', 
							src: params.params.picture, 
							href: params.params.link 
						}] 
					}
				});
				
				FB.api( params.params );
			}
			else
			{
				FB.api( '/' + params.profileId + '/feed', 'post', params.params, function ( response ) {
					if ( params.callback != null )
					{
						params.callback( !( !response || response.error ) );
					}
				} );
			}
		}
	},
	
	/**
	 * check if current user likes a page
	 * @param pageId the page id to check
	 * @param callback the callback function
	 */
	doesUserLikePage: function ( pageId, callback )
	{
		var params = {
			"pageId": pageId,
			"callback": callback
		};
		this.hasUserAppPermission( Sky.FacebookUtil.PERMISSION_LIKES, this._doesUserLikePageCallback, params );
	},
	
	/**
	 * callback for Sky.FacebookUtil#doesUserLikePage after checking the user permissions
	 */
	_doesUserLikePageCallback: function ( params )
	{
		if ( params._permissionGranted )
		{
			FB.api( '/me/likes', function ( response ) {
				var userLikedPage = false;
				for ( var i = 0; i < response.data.length; i++ )
				{
					if ( response.data[i].id == params.pageId )
					{
						userLikedPage = true;
						break;
					}
				}
				
				if ( params.callback != null )
				{
					params.callback( userLikedPage );
				}
			} );
		}
	},
	
	/**
	 * request user app permissions, if necessary with the facebook permission pop-up
	 * @param perms Comma separated list of Extended permissions (@see http://developers.facebook.com/docs/authentication/permissions)
	 * @param callback the callback function
	 * @param params param obj for callback function
	 */
	requestUserAppPermission: function ( perms, callback, params )
	{
		// ask user for extended permissions...
		FB.login( function( response ) {
				params.response = response;
				params._permissionGranted = response.authResponse;
				callback( params );
			}.bind( this ),
			{
				scope: perms
			}
		);
	},
	
	/**
	 * check the user app permission
	 * @param perms Comma separated list of Extended permissions (@see http://developers.facebook.com/docs/authentication/permissions)
	 *        The user must have all permissions accepted, if one Extended permission fails, permission will not be granted!
	 * @param callback the callback function
	 * @param params param obj for callback function
	 */
	hasUserAppPermission: function ( perms, callback, params )
	{
		// Use Graph API
		if ( params==undefined )
		{
			params = {};
		}
		var possiblePerms = perms.split(",");
		params._permissionGranted = false;
		FB.api( '/me/permissions', 
			function( response )
			{
				if ( !response.error )
				{
					params._permissionGranted = true;
					for ( var p = 0; p < possiblePerms.length; p++ )
					{
						var perm = response.data[0][possiblePerms[p]];

						if ( Object.isUndefined(perm) || perm != 1 )
						{
							params._permissionGranted = false;
							break;
						}
					}
				}
				callback( params );
			}.bind( this )
		);
	}
};
