	var inviteFrameLoaded = false;
	var inviteFrameDisplayState = false;
	
	var friendData = null;
	var userData = null;
	
	var fbLoggedIn = false;
	
	var friendSelectorInitialized = false;
	
	// Various jQuery objects
	var fbcUserName = null;
	var fbcUserImage = null;
	var fbcLoggedinPanel = null;
	var fbcLoggedoutPanel = null;
	var flc = null;	
	var docObj = null;
	var fbcInviteContainer = null;
	var inviteFormTrigger = null;
	
	// Chooser Dialog Objects
	var dlgObj = null;
	var optSelf = null;
	var optFriend = null;
	var friendForm = null;
	
	// Call the initialization procedure
	jQuery(document).ready(function() { _init(); });
	
	//
	//	
	// Helper function to force login
	//
	//
	function facebook_requireSession(options) {
		FB_RequireFeatures(["Connect"], function() {
			FB.Connect.requireSession(function() {
				facebook_onlogin();
				if (options.success != null) options.success();
			});
		});
	}
	
	//
	//
	//	Log the user out of Facebook Connect
	//
	//
	function facebook_logout() {
		FB_RequireFeatures(["Connect"], function() {
			FB.Connect.logout(function() {
				fbLoggedIn = false;
				fbcLoggedinPanel.hide();
				fbcLoggedoutPanel.show();
				return false;
			});
		});
	}

	//
	//
	//	Facebook On-Login Routine
	//
	//	Abstracted out in case there are functions we need to add in to here that don't need to be initialized all the time
	//
	//
	function facebook_onlogin() {
		fbLoggedIn = true;		
		_initializeFacebookConnect();
	}
	
	//
	//
	//	Sets the default state
	//
	//
	function facebook_notloggedin() {
		fbcLoggedinPanel.hide();
		fbcLoggedoutPanel.show();
	} 
	
	//
	//
	//	Facebook - Prompt for Permissions
	//
	//
	function facebook_extendedPermissions(permissions,options) {
	
		// Sort the permissions so there is a predictable order
		perms = permissions.split(',');
		perms.sort();
		permissions = perms.join(',');
	
		FB_RequireFeatures(["Connect"], function() {
			FB.Connect.showPermissionDialog(permissions,function(approved) {
				
				// Sort the approved permissions
				
				if (approved == "" || approved == null) {
					options.failure(options.failMessage);
				}
				else {
				
					perms = approved.split(',');
					perms.sort();
					approved = perms.join(',');
					
					if (approved == permissions) {
						options.success();
					}
					else {
						options.failure(options.failMessage);
					}
				
				}
			});
		});		
		
	}
	
	//
	//
	//	A slight misnomer - actually toggles the invite form
	//
	//
	function showInviteForm() {
			
		if (!inviteFrameLoaded) {
			_initializeInviteFrame();
		}
		
		if (!inviteFrameDisplayState) {
			fbcInviteContainer.slideDown('slow');
			inviteFrameDisplayState = true;
			_inviteFramePositioning();
		}
		else {
			fbcInviteContainer.slideUp('slow');
			inviteFrameDisplayState = false;
		}
		
		return false;
	}
	
	//
	//
	//	Show the share dialog
	//
	//	Will be expanded to handle a bunch of different options
	//
	//
	function showFacebookConnectShare(opts,friendOpts) {
	
		FB_RequireFeatures(["Connect"], function() {
			
			facebook_requireSession({
			
				success: function() {
				
					facebook_showChooser(opts, friendOpts, function(options,friendOptions) {
					
						if (options.target != null && friendOptions != null) {
							friendOptions.target = options.target;
							options = friendOptions;							
						}
					
						if (options.message != null) {
						
							if (options.attachment == null) {
									options.attachment = { description: options.message };
							}
							else {
								if (options.attachment.description == null) {
									options.attachment.description = options.message;
								}
							}

							options.message = null;
							
						}
						
						if (!options.message) { options.message = ''; }
					
						FB.Connect.streamPublish(options.text,options.attachment,options.links, options.target, options.message_prompt, options.callback, options.actor_id);
					
					});
				
				},
				failure: function() {
					jQuery.facebox('<div style="margin: 20px;">You must log in to share this on facebook.</div>');
				}
				
			});
		
		});
	}
	
	//
	//
	//	Exposed share function
	//
	//
	function doFacebookConnectShare(options, friendOptions) {
		
		if (options.target != null && friendOptions != null) {
			friendOptions.target = options.target;
			options = friendOptions;
		}
	
		if (options.message != null) {
		
			if (options.attachment == null) {
					options.attachment = { description: options.message };
			}
			else {
				if (options.attachment.description == null) {
					options.attachment.description = options.message;
				}
			}

			options.message = null;
			
		}
		
		if (!options.message) { options.message = ''; }
	
		FB.Connect.streamPublish(options.text,options.attachment,options.links, options.target, options.message_prompt, options.callback, options.actor_id);
		
	}
	
	//
	//
	//	Intialize Facebook Chooser
	//
	//
	function facebook_showChooser(options, friendOptions, callback) {		

		// Reset state to default
		optSelf.show();
		optFriend.show();
		friendForm.hide();
		
		// Bind the handler to create the click handlers on the new facebox instance
		jQuery(document).bind('reveal.facebox', {options: options, friendOptions: friendOptions}, function(evt) {
		
			_initDialog();
			scope = jQuery('#facebox');
			optSelf = jQuery('#facebook-share-option-self', scope);
	
			optSelf.bind('click', {options: options}, function(evt) {
				jQuery(document).trigger('close.facebox');
				doFacebookConnectShare(options);
				jQuery(this).unbind(evt);
			});
			
			optFriend = jQuery('#facebook-share-option-friend', scope);
			
			optFriend.bind('click', {options: options, friendOptions: friendOptions}, function(evt) {
			
				jQuery('a.friend-selector-item',friendForm).unbind('click');									
				jQuery('a.friend-selector-item',friendForm).bind('click', {options: options, friendOptions: friendOptions}, function(evt) {						
					options.target = jQuery(this).attr('fbuid');
					jQuery(document).trigger('close.facebox');
					doFacebookConnectShare(options,friendOptions);						
				});
			
				optFriend.fadeOut('slow');
				optSelf.fadeOut('slow', function() {
					friendForm.fadeIn('slow');
				});
			
			});
		
		});
		
		
		jQuery.facebox(dlgObj.show());
	
	}
	
	
	//
	//
	//	Individual Nominee Facebook Share
	//
	//
	function facebook_shareNominee(id) {
		
		jQuery.getJSON('/nominees/get_nominee/' + id, null, function(data, status) {
			
				if (data.success) {					
					showFacebookConnectShare({
						message:  data.data.Nominee.short_desc,
						message_prompt: 'Check out ' + data.data.Nominee.full_name + '\'s nomination for GQ\’s The Better Men Better World Search',
						attachment: {
							name: 'Check out ' + data.data.Nominee.full_name + '\'s nomination for GQ\’s The Better Men Better World Search',
							href: 'http://' + data.domain + '/nominees/view/' + data.data.Nominee.id,
							description: data.data.Nominee.short_desc + ' Powered by Movado.',
							media: [
								{
									type: 'image',
									src: 'http://' + data.domain + data.data.Nominee.path_sm,
									href: 'http://' + data.doamin + '/nominees/view/' + data.data.Nominee.id
								}
							]
						}
					},
					{
						message: data.data.Nominee.short_desc + ' Powered By Movado.',
						message_prompt: 'Check out ' + data.data.Nominee.full_name + '\'s nomination for GQ\’s The Better Men Better World Search',
						attachment: {
							name: 'Check out ' + data.data.Nominee.full_name + '\'s nomination for GQ\’s The Better Men Better World Search',
							href: 'http://' + data.domain + '/nominees/view/' + data.data.Nominee.id,
							description: data.data.Nominee.short_desc + ' Powered by Movado.',
							media: [
								{
									type: 'image',
									src: 'http://' + data.domain + data.data.Nominee.path_sm,
									href: 'http://' + data.doamin + '/nominees/view/' + data.data.Nominee.id
								}
							]
						}
					});
				}
				else {
					alert('Could not load data to populate share dialog');
				}
			
			}
		);
		
	}
	
	//
	//
	//	Charity Share
	//
	//
	function facebook_shareCharity(id) {
		if (id == '93') {
			
			// Uses the following Facebook Connect copy for the Hunger landing page instead of the standard copy
			jQuery.getJSON('/charities/get_charity/' + id, null, function(data, status) {
			
				if (data.success) {					
					showFacebookConnectShare({
						message: data.data.Charity.facebook_share_body,
						message_prompt: 'Help fight hunger with GQ and The Gentlemen’s Fund initiative',
						attachment: {
							name: 'I join GQ, David Arquette and Snickers in supporting Feeding America’s nationwide fight to end hunger.',
							href: 'http://' + data.domain + '/charities/view/' + data.data.Charity.slug,
							media: [
								{
									type: 'image',
									src: 'http://' + data.domain + '/img/facebook_connect/TGF-Graphic-For-Facebook.jpg',
									href: 'http://' + data.domain + '/charities/view/' + data.data.Charity.slug
								}
							]
						}
					},
					{
						message: data.data.Charity.facebook_friend_share_body,
						message_prompt: 'Join me in the fight to end hunger with GQ and The Gentlemen’s Fund initiative.',
						attachment: {
							name: 'GQ, David Arquette, and Snickers support Feeding America’s nationwide fight to end hunger. Learn more at <a href="http://' + data.domain + '">thegentlemensfund.com</a>.',
							href: 'http://' + data.domain + '/charities/view/' + data.data.Charity.slug,
							media: [
								{
									type: 'image',
									src: 'http://' + data.domain + '/img/facebook_connect/TGF-Graphic-For-Facebook.jpg',
									href: 'http://' + data.domain + '/charities/view/' + data.data.Charity.slug
								}
							]
						}
					});
				}
				else {
					alert('Could not load data to populate share dialog');
				}
			
			}
		);
		} else {
			// Standard Facebook Connect copy is right here
			jQuery.getJSON('/charities/get_charity/' + id, null, function(data, status) {
			
				if (data.success) {					
					showFacebookConnectShare({
						message: data.data.Charity.facebook_share_body,
						message_prompt: 'Support ' + data.data.Charity.focus + ' with GQ and The Gentlemen\'s Fund initiative',
						attachment: {
							name: 'Support of ' + data.data.Charity.focus + ' with GQ and The Gentlemen\'s Fund initiative',
							href: 'http://' + data.domain + '/charities/view/' + data.data.Charity.slug,
							media: [
								{
									type: 'image',
									src: 'http://' + data.domain + '/img/facebook_connect/TGF-Graphic-For-Facebook.jpg',
									href: 'http://' + data.domain + '/charities/view/' + data.data.Charity.slug
								}
							]
						}
					},
					{
						message: data.data.Charity.facebook_friend_share_body,
						message_prompt: 'Join me in support of ' + data.data.Charity.focus + ' with GQ and The Gentlemen\'s Fund initiative',
						attachment: {
							name: 'Join me in support of ' + data.data.Charity.focus + ' with GQ and The Gentlemen\'s Fund initiative',
							href: 'http://' + data.domain + '/charities/view/' + data.data.Charity.slug,
							media: [
								{
									type: 'image',
									src: 'http://' + data.domain + '/img/facebook_connect/TGF-Graphic-For-Facebook.jpg',
									href: 'http://' + data.domain + '/charities/view/' + data.data.Charity.slug
								}
							]
						}
					});
				}
				else {
					alert('Could not load data to populate share dialog');
				}
			
			}
		);
		}
	}
	
	//
	//
	//
	//
	//
	function facebook_shareImage(img_id, base_url, caption, page_url) {
	
		img_url = base_url + jQuery('#' + img_id).attr('src');
		
		showFacebookConnectShare({
			message: caption,
			message_prompt: 'GQ & The Gentlemen\'s Ball \'09',
			attachment: {
				name: 'GQ & The Gentlemen\'s Ball \'09',
				description: caption,
				href: page_url,
				media: [
					{
						type: 'image',
						src: img_url,
						href: page_url
					}
				]
			}
		},
		{
			message: caption,
			message_prompt: 'Check out this photo from GQ\'s The Gentlemen\'s Ball \'09',
			attachment: {
				name: 'Check out this photo from GQ\'s The Gentlemen\'s Ball \'09',
				description: caption,
				href: page_url,
				media: [
					{
						type: 'image',
						src: img_url,
						href: page_url
					}
				]
			}
		});
	
	}
	
	
	//
	//
	//	Show the facebook friend picker
	//  This needs to be finished
	//
	//
	function showFriendPicker() {
		// Load the user's friends		
		for (var i = 0; i < friendData.length; i++) {
		
			trObj = jQuery('<tr></tr>').addClass('friendListingObject');
			tdObj = jQuery('<td></td>');
			aObj = jQuery('<a></a>').attr('id',friendData[i].uid + '_trigger').attr('data',friendData[i].uid).click(function() { 
				alert(jQuery('#'+this.id).attr('data'));
				jQuery('td.selected').removeClass('selected'); 
				jQuery(this).parent().addClass('selected');
			});
			imgObj = jQuery('<img>').attr('src',friendData[i].pic_square);
			spanObj = jQuery('<span></span>').html(friendData[i].name);							
			trObj.append(tdObj.append(aObj.append(imgObj).append(spanObj))).appendTo(flc);
		}
	}
	
	//
	//
	//	Limit a field to only numeric characters
	//
	//
	function limitNumerics() {
		jQuery('input.numeric').numeric();
	}
	
	//
	//
	//	Initialize the Facebook Connection
	//
	//
	function _initializeFacebookConnect() {
		FB_RequireFeatures(["Connect","Api"], function() {		
			user = FB.Connect.get_loggedInUser();
			
			jQuery('.facebook-connect-enabled').show();
			jQuery("input[type=hidden][name$=\[facebook_uid\]]").val(user);		
		
			FB.Facebook.apiClient.users_getInfo(user,['name','pic_square','uid'], function(result) {			
				userData = result[0];
				fbcUserName.html(userData.name);
				fbcUserImage.html('<img src="' + userData.pic_square + '" height="50" width="50" />');
				fbcLoggedoutPanel.hide();
				fbcLoggedinPanel.show();
				return false;					
			});
			
			_initializeInviteFrame();
			
			// Load the user's friend data
			FB.Facebook.apiClient.friends_get(null, function(users) {	
				FB.Facebook.apiClient.users_getInfo(users,['name','pic_square','uid','affiliations'],function(result) {
					friendData = result;
					friendData.sort(function(a,b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; });
					_initFriendSelector();
				});
			});
		});
	}
	
	//
	//
	//
	//
	//
	function _initFriendSelector() {
	
		if (!friendSelectorInitialized) {	

			friendSelectorInitialized = true;
	
			// Make the friend divs
			friendList = jQuery('#facebook-friend-list');
			
			for (var i = 0; i < friendData.length; i++) {
				f = friendData[i];
				p = f.pic_square;
				n = f.name;
				u = f.uid;			
				a = (f.affiliations.length > 0 ? f.affiliations[0].name : '');
				
				d = jQuery('<a class="friend-selector-item" href="#" fbuid="' + u + '"><img src="' + p + '" /><div class="name">' + n + '</div><div class="network">'+a+'</div></a>');
				friendList.append(d);
			}
		
		}
		
	}
	
	//
	//
	//	Initialize the jQuery objects
	//
	//
	function _init() {
		fbcUserName = jQuery('#fbconnect-user-name');
		fbcUserImage = jQuery('#fbconnect-user-image');
		fbcLoggedinPanel = jQuery('#fb-state-loggedin');
		fbcLoggedoutPanel = jQuery('#fb-state-loggedout');
		flc = jQuery('#friendListContainer');	
		docObj = jQuery('#container');
		fbcInviteContainer = jQuery('#facebookInviteFormContainer');
		inviteFormTrigger = jQuery('#inviteFormTrigger');
		
		_initDialog();
		
		limitNumerics();
	}
	
	//
	//
	//	Initialize dialog objects
	//
	//
	function _initDialog() {
	
		// Build the dialog objects
		dlgObj = jQuery('#facebook-share-chooser-container');
		optSelf = jQuery('#facebook-share-option-self');
		optFriend = jQuery('#facebook-share-option-friend');
		friendForm = jQuery('#facebook-share-option-select-friend-form');
	
	}
	
	//
	//
	//	Invite Frame Initialization
	//
	//
	function _initializeInviteFrame() {
	
		jQuery('<iframe>').attr('src','/fbconnect_testing/invite_form').attr('width','625').attr('height','520').attr('class','fbshare_iframe').appendTo('#facebookInviteFormContainer').show();
		
		fbcInviteContainer.width(650);
		
		inviteFrameLoaded = true;

		jQuery(window).resize(function() {
			_inviteFramePositioning();
		});
		
		_inviteFramePositioning ();
		
		// Initialize the trigger
		inviteFormTrigger.click(function() {
			showInviteForm();
			if (!inviteFrameDisplayState) {
				inviteFormTrigger.html('Invite Friends');
			}
			else {
				inviteFormTrigger.html('Hide Invite');
			}					
		});				
	}
	
	//
	//
	//	Invite Frame Positioning
	//
	//
	function _inviteFramePositioning() {
		pos = inviteFormTrigger.offset();
		fbcInviteContainer.css('position','absolute').css('backgroundColor','white');
		fbcInviteContainer.offset({ top: (pos.top + inviteFormTrigger.height()) + 11, left: (pos.left + inviteFormTrigger.width() - jQuery('iframe',fbcInviteContainer).width() + 5) });
			
	}
