BLIP.Class.create("BLIP.Facebook", BLIP.Object,
	function(config) {
		this.appId = config.appId;
		this.postsId = config.postsId;
		this.successRedirect = config.successRedirect;
		this.failureRedirect = config.failureRedirect;
		this.watched = false;

		$(document).ready(this.delegate(this.init));
	},

	{
		init: function() {
			window.fbAsyncInit = this.delegate(function() {
				FB.init({
					appId: this.appId,
					status: true,
					cookie: true,
					xfbml: true,
					oauth: true,
					channelURL : $('meta[name=fb_channel_url]').attr('value')
				});
				FB.UIServer.setLoadedNode = function(a,b){
				    FB.UIServer._loadedNodes[a.id]=b;
				};
				this.addEventListeners();
				this.ready = true;
				this.fireEvent('FacebookReady');
			});
			if(!$('#fb-root').length) {
				$(document.body).append($('<div id="fb-root"></div>'));
			}
			var fbScript = document.createElement('script');
			fbScript.async = true;
			fbScript.src = '//connect.facebook.net/en_US/all.js';
			$('#fb-root').append(fbScript);
		},

		addEventListeners: function () {
			//JL we are not using any of these atm..
//			this.addEventListener('playbackStart', this.delegate(this.sendWatch));
//			this.addEventListener("viewerTimeChanged", this.delegate(this.viewerTimeChanged));
		},

		authenticate: function(callback) {
			FB.getLoginStatus(this.delegate(callback ? callback : this.authenticateResponded));
		},

		authenticateResponded: function(response) {
			if (response && response.authResponse) {
				this.sendAuthResponse(response.authResponse);
				this.fireEvent('FacebookAuthenticated');
			}
			else {
				$("#FacebookShareButton").show();
				this.log("Facebook has no authResponse");
			}
		},


		// callback is
		login : function(callbacks) {
			FB.login(this.delegate(function(response) {
				this.loginResponded(response, callbacks);
			}), {scope : 'email,offline_access'});
/*			this.authenticate(this.delegate(function(response) {
				this.loginAuthenticateResponded(response, callbacks);
			}));
*/
		},

		logout : function() {
			function blipLogout () {
				var returnUrl = window.location.href;
				window.location = '/facebook/logout?no-cache=1&return_url=' + encodeURIComponent(returnUrl);
			}

			blipLogout();

//old way if we ever need it again
/*
			FB.getLoginStatus(function(response) {
				if(response.authResponse) {
					FB.logout(blipLogout);
				}
				else {
					blipLogout();
				}
			});
*/
		},

		loginAuthenticateResponded  : function(response, callbacks) {
			if(response && response.authResponse) {
				this.sendAuthResponse(response.authResponse, this.delegate(function(response) {
					this.loginResponded(response, callbacks);
				}));
			}
			else if(response) {
				this.fireEvent('pause');
				FB.login(this.delegate(function(response) {
					this.loginResponded(response, callbacks);
				}), {perms : 'email,offline_access'});
			}
		},

		loginResponded : function(response, callbacks) {
			if(response && response.authResponse) {
				this.sendAuthResponse(response.authResponse, this.delegate(function(success) {
					if(success) {
						this.fireEvent('FacebookLogin');
						if(callbacks && callbacks.success) {
							callbacks.success();
						}
					}
					else {
						if(callbacks && callbacks.failure) {
							callbacks.failure();
						}
					}
				}));
			}
			else if(callbacks && callbacks.failure){
				callbacks.failure();
			}
		},

		sendAuthResponse: function(authResponse, callback) {
			var json = JSON.stringify(authResponse);
			$.post('/facebook/verify_viewer_user', {
					authResponse: json,
					skin: 'json',
					'no-cache': 1,
					no_wrap: 1
				}, this.delegate(function(response) {
					this.sendAuthResponseResponded(response);
					if(callback) {
						callback(response);
					}
				}),
				'json'
			);
		},

		sendAuthResponseResponded: function(response) {
			this.log("verify_viewer_user response: "+response.error);
			if(response.new_user === 1 && !this.skipFirstTimeRedirect) {
				window.location = '/subscriptions/start-subscribing';
			}
			else if (response.error === 0) {
				this.fireEvent('FacebookLogin');
			}
			else if (this.failureRedirect) {
				window.location = this.failureRedirect;
			}
		},


		sendWatch: function() {
			$.post('/facebook/watch', {
					posts_id: this.postsId,
					skin: 'json',
					'no-cache': 1,
					no_wrap: 1
				}, this.delegate(this.sendWatchResponded),
				'json'
			);
		},

		sendWatchResponded: function(response) {
			this.log("wooo watch responded");
		}
	}
);

