/**
 * This creates a jquery extention that will make elements on the page post a facebook message to the users feed. and apply it automatically to 
 * all elements with the class fbShare.
 * usage: $('.elements').fbShare(options);
 * author:jkoberstein
 * options
 *   defaultMessage: the text that will be set in the user message to be posted
 *   url: the url to be shared on facebook
 *   urlText: the link text to be shared
 *   picture: the image to be shared in the post
 *   caption: a caption under the link
 *   description: a description of the post
 * note that all these options can be set on the element in the html so no javascript needs to be coded for the fbShare class
 * 
 * example:
 * <span 
 *	class="fbShare large" 
 *	urlText="Pogo" 
 *	url="http://www.pogo.com" 
 *	msg="Come check out Pogo! It's awesome" 
 *	picture="http://www.pogo.com/img/logo.png"
 * >
 *    Share
 * </span>
 * 
 * for some good looking styling of these element please use /include/css/fbconnect/jqfbConnect.css
 */
if(typeof jQuery == 'undefined'){
	alert("jQuery library is missing!");
}
if(typeof FB == 'undefined'){
	alert("fbconnect library is missing (all.js)");
}
if(typeof PogoFBConstants == 'undefined'){
	alert("fbconnect initialziation missing (/fbconnect/js.do) ")
}

(function( $ ){
	facbookPermsNeeded = 'publish_stream';
	//make jquery understand the contenttype text/json
	$.ajaxSetup({ converters: { "text text/json": function( textValue ) { return textValue; } } });

	$(document).ready(function() {
			if($('#fb-root').length==0){
				$('body').append($('<div id="fb-root"></div>'));
			}
			FB.init({appId: PogoFBConstants.apiKey, status: true, oauth:true, cookie: true, xfbml: true});
			$(".fbconnect.share").fbconnect('share');
	});
	
	var privateMethods = {
		fbLogin : function(callback){
			FB.getLoginStatus(function(response) {
				continuation = function(response){
					//loged into facebook now try pogo
					if(callback){
						if(response.authResponse){
							callback(response);
						} else {
							callback(false);
						}
					} else {
						if(response.authResponse){
							window.location.reload(true);
						} else {
							alert('Could not log you in');
						}
					}
				}
				if(response.authResponse){
					continuation(response);
				} else {
					FB.login(function(loginResponse) {
						continuation(loginResponse);
					}, {scope:facbookPermsNeeded});
				}
			}, {scope:facbookPermsNeeded});
		},
		fbAndPogoLogin : function(settings){
			if (typeof(settings) == 'undefined') {
				return;
			}
			var ajaxActionUrl = privateMethods.getSignInUrl(settings);
			privateMethods.fbLogin(function(response){
				if(response){
					//loged into facebook now try pogo
					$.ajax(ajaxActionUrl, {
						success: function(data,textStatus,jqXHR) {
							if (typeof(settings.callback) == 'function') {
								if(response.authResponse){
									settings.callback(response);
								} else {
									settings.callback(false);
								}
							} else {
								window.location = jqXHR.responseText;
							}
						},
						error: function () {
							if (typeof(settings.callback) == 'function') {
								settings.callback(false);
							}
							alert('Could not log you in');
						}
					});
				}
			});
		},
		getConnectStatus : function(callback, showErrorPopup) {
			$.ajax("/fbconnect/getstatus.do", {
				dataType: "text",
				success: function(responseJSON){
					callback(eval( responseJSON ));
				},
				error: function() {
					if (typeof showErrorPopup == 'undefined' || showErrorPopup) {
						privateMethods.showServerErrorPopUp();
					}
				}
			});
		},
		getShareStatus : function(callback, showErrorPopup) {
			$.ajax("/fbconnect/getsharestatus.do", {
				dataType:'text',
				success: function(responseJSON){
					callback(eval( responseJSON ) );
				},
				error: function() {
					if (typeof showErrorPopup == 'undefined' || showErrorPopup) {
						privateMethods.showServerErrorPopUp();
					}
				}
			});
		},
		showPopUp : function(url, showErrorPopup){
			$.ajax(url, {
				dataType:'text',
				success: function(response){
					privateMethods.showPopUpContent(response);
				},
				error: function() {
					if (typeof showErrorPopup == 'undefined' || showErrorPopup) {
						privateMethods.showServerErrorPopUp();
					}
				}
			});
		},
		showPopUpContent : function(html){
			if($('#fb-root #connect-popup').length==0){
				$('#fb-root').append($('<div id="connect-popup" style="z-index: 16177285; position: fixed; top: 50%;  left: 50%;  margin: -183px 0 0 -270px;"></div>'));
			}
			$('#fb-root #connect-popup').html(html);
			$('#fb-root #connect-popup').show();
		},
		hidePopUpContent : function(){
			$('#fb-root #connect-popup').hide();
		},
		callLinkAction: function(settings) {
			if (typeof(settings) == 'undefined') {
				return;
			}
			var ajaxActionUrl = '/fbconnect/link.do';
			$.ajax(ajaxActionUrl, {
					dataType:'text',
					success: function(responseText){
						var status = eval(responseText);
						if (!status.connected && status.isPogoUserLinked) {
							alert("user missmatch");
						} else if (!status.connected && status.isFbUserLinked) {
							alert("user already connected");
						}
						//if it is a new link then trigger a new omniture event to track
						//event10 == FACEBOOK_ACCT_LINK
						if (status.newLink) {
							if (typeof OmnitureEvent == 'function') {
								OmnitureEvent(s.pageName, 'event10');
							}
							if ((typeof(OmnitureLightEvent) == 'function') && (settings.posttag)) {
								OmnitureLightEvent(settings.posttag);
							}
							window.open(PogoFBConstants.URLs.inviteFriends, '_blank', 'width=800px,height=600px');
						}
						if (typeof(settings.callback) == 'function'){
							settings.callback(status.connected);
						} else {
							location.reload(true);
						}
					},
					error: function(jqXHR, textStatus, errorThrown) {
						alert("FAILED to request /fbconnect/link.do");
						if (typeof(settings.callback) == 'function'){
							settings.callback(false);
						}
					}
			});
		},
		showServerErrorPopUp : function(){
			privateMethods.showPopUpContent(
					'<div id="mdBox">'
					+ '<div class="hdr">'
					+   '<img src="/img/fbconnect/popover/hd-lt-cnr.gif" class="inl" />'
					+   '<h3 class="inl">'
					+   PogoFBConstants.Messages.errorInternalTitle
					+   '</h3>'
					+   '<img src="/img/fbconnect/popover/hd-rt-cnr.gif" class="inl-r" />'
					+   '<div class="clear"></div>'
					+ '</div>'
					+ '<div class="withfblogo">'
					+    '<img src="/img/fbconnect/facebook-logo.gif" class="inl firstBtn" />'
					+    '<div class="desc inl">'
					+      PogoFBConstants.Messages.errorFatalAjaxProblem
					+    '</div>'
					+    '<div class="clear"></div>'
					+  '</div>'
					+  '<div class="ftr">'
					+    '<a href="javascript:void(0)" onclick="if(typeof parentCallback == \'function\'){parentCallback(false);}PogoFB.Popover.close(this);">'
					+      PogoFBConstants.Images.cancelButton
					+    '</a>'
					+  '</div>'
					+  '</div>');
		},
		extractAttributes : function(element, settings) {
			if ((typeof(element) == 'undefined') || (typeof(settings) == 'undefined')) {
				return;
			}
			var attributes = element.attributes;
			if ((typeof(attributes) == 'undefined') || !(attributes.length)) {
				return;
			}
			for (var i = 0; i < attributes.length; i++) {
				var name = attributes[i].nodeName.toLowerCase();
				if ((name.search(/^pogo/) == 0) && typeof(settings[name]) == 'undefined') {
					settings[name.substring(4)] = attributes[i].nodeValue;
				}
			}
		},
		getSignInUrl : function(parameters) {
			return privateMethods.constructUrl('/fbconnect/reg/signin.do', parameters);			
		},
		constructUrl : function(url, parameters) {
			if (typeof(url) == 'undefined') {
				return null;
			}
			if (parameters) {
				var first = true;
				for (var parameter in parameters) {
					var value = parameters[parameter];
					if ((typeof(value) != 'function') && (typeof(value) != 'undefined')) {
						if (first) {
							url += '?';
							first = false;
						}
						else {
							url += '&';
						}
						url += (parameter + '=' + encodeURIComponent(value));
					}
				}
			}
			return url;
		}
	}
	//add glue to make this work with the old frame work. It has hard coded PogoFB.Popover.close() functions in the response html
	PogoFB = {Popover : { close : function(){
		privateMethods.hidePopUpContent();
	}}}
	PogoFB.logout = function(){
		FB.logout(function() {
			privateMethods.fbLogin();
		});
	}


	var methods = {
		share : function( options ) {
		var settings = {
			'size' : 2,
			'link': 'www.pogo.com',
			'linkText':'Pogo'
		};
		this.each(function() {
			if ( options ) { 
				$.extend( settings, options );
			}
			$(this).click(function(event){
				link = settings.link;
				if($(this).attr('url')){
					link = $(this).attr('url')
				}
				linkText = settings.linkText;
				if($(this).attr('urlText')){
					linkText = $(this).attr('urlText')
				}
				message = settings.defaultMessage;
				if($(this).attr('msg')){
					message = $(this).attr('msg')
				}
				picture = settings.picture;
				if($(this).attr('picture')){
					picture = $(this).attr('picture')
				}
				caption = settings.caption;
				if($(this).attr('caption')){
					caption = $(this).attr('caption');
				}
				description = settings.description;
				if($(this).attr('desc')){
					description = $(this).attr('desc');
				}
				properties = settings.properties;
				if($(this).attr('prop') && $(this).attr('propValue')){
					prop = $(this).attr('prop');
					properties = {};
					if($(this).attr('propLink')){
						properties[prop] = {'text':$(this).attr('propValue'),'href':$(this).attr('propLink')};
					} else {
						properties[prop] = $(this).attr('propValue');
					}
					
				}
				addFacebookInfo = function(str,info){
					if(!str){
						return str;
					}
					if(info && info.first_name){
						str = str.replace("|FACEBOOK_USER_FIRST_NAME|",info.first_name)
					}
					if(info && info.last_name){
						str = str.replace("|FACEBOOK_USER_LAST_NAME|",info.last_name)
					}
					if(info && info.name){
						str = str.replace("|FACEBOOK_USER_NAME|",info.name)
					}
					return str;
				}
				FB.api('/me', function(response) {
					FB.ui({
						method: 'feed',
						name:linkText,
						link:link,
						picture:picture,
						caption:addFacebookInfo(caption,response),
						description:addFacebookInfo(description,response),
						message:addFacebookInfo(message,response),
						properties: properties
					}, function(response) {
						if (typeof(settings.callback) == 'function') {
							if (response && response.post_id) {
								settings.callback(true);
							} else {
								settings.callback(false);
							}
						}
					});
				});
			});
		});
		return this;
		},
		login : function( options ) {
			var settings = {
				'size' : 2
			};
			this.each(function() {
				if ( options ) { 
					$.extend( settings, options );
				}
				$(this).click(function(event){
					privateMethods.extractAttributes(this, settings);
					if (typeof(settings.onClick) === 'function') {
						settings.onClick(true);
					}
					privateMethods.fbAndPogoLogin(settings);
				})
			});
		},
		connect : function( options ) {
			var settings = {
				'size' : 2
			};
			this.each(function() {
				if ( options ) { 
					$.extend( settings, options );
				}
				$(this).click(function(event){
					privateMethods.extractAttributes(this, settings);
					if (typeof(settings.onClick) === 'function') {
						settings.onClick(true);
					}
					privateMethods.fbLogin(function(fbstatus){
						if(!fbstatus){
							if (typeof(settings.callback) == 'function'){
								settings.callback(false);
							}
							return;
						}
						if (fbstatus.authResponse) { // same as: fbstatus.status == "connected") {
							privateMethods.getConnectStatus(function(status) {
								// three conditions may occur here:
								// - the pogo user has a link and he's attempting to log in with
								//   another facebook user which means we must show the users
								//   mismatch error
								// - the current fb user is linked to someone else, and the current
								//   pogo user is trying to create a link to him; in this case we
								//   must show the already connected error
								// - the current fb user has granted the app but the link was
								//   removed (though not the grant), therefore the user is free to
								//   be linked, we try to go through the linking process
								if (status.connected) {
									// yay user is connected
								} else if (status.isPogoUserLinked) {
									privateMethods.showPopUp('/fbconnect/error/usersmismatch.do');
								} else if (status.isFbUserLinked) {
									privateMethods.showPopUp('/fbconnect/error/alreadyconnected.do');
								} else {
									privateMethods.callLinkAction(settings);
								}
							},true);
						}
					});
				});
			});
			//newwindow=window.open('/fbconnect/friends/invite.do','name','height=200,width=150');
			//if (window.focus) {newwindow.focus()}
			//alert('connect not implemented yet');
		},
		logout : function(options) { 
			$(this).click(function(event){
				FB.logout(function() {
					privateMethods.fbLogin();
				});
			});
		}
	};

	$.fn.fbconnect = function( method ) {
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.fb' );
		} 
	}
})( jQuery );
