var $dialog;

function loginUser(apikey) {
	// An optimization so that users do not get a javascript error when clicking the login button before
	// the FB.init() is called in the footer of the page.
	FB_RequireFeatures(["Connect"], function() {
		FB.init(apikey, "facebook/xd_receiver.htm");
		FB.Connect.requireSession(updateUserBox);
	});
}

var profileAjaxRequest = null;
function showUserProfile(uid, name) {
	FB.ensureInit(function() {
		if (profileAjaxRequest!=null) {
			profileAjaxRequest.abort();
			profileAjaxRequest = null;
		}
	
		var content = ' \
					<div id="loadingProfile"> \
						Just a sec ...<br/><br/> \
						<img src="images/ajax_progress2.gif"> \
					</div>';
				
		// An attempt to avoid getting a javascript error if $dialog is still undefined
		if (typeof $dialog=='undefined') {
			$dialog = $('#dialog');
		}
		
		$dialog
			.data('title.dialog', decodeURIComponent(name))
			.html(content)
			.dialog('open');
			
		profileAjaxRequest = $.ajax({
			type: 'GET',
			url: 'user_profile.php',
			data: {
				uid: uid
			},
			cache: false,
			success: function(html) {
				$dialog.html(html);
				profileAjaxRequest = null;
			},
			error: function() {
				$dialog.html('There was a problem connecting to the server. Please try again.');
				profileAjaxRequest = null;
			}
		});

		//FB.XFBML.Host.parseDomElement($dialog.get(0));
	});
	
	//.dialog("close"); //hide dialog
}

function showCommentEntryBox() {
	FB_RequireFeatures(["Connect"], function() {
		FB.Connect.requireSession(function() {
			$('#addCommentText').val('');
			$('#newCommentsBox').show();
			location.href='#newComment';
			$('#newCommentsBox').effect('highlight', {}, 2000);
		});
	});
}

function addResponse(xid, responseType) {
	FB_RequireFeatures(["Connect"], function() {
		FB.Connect.requireSession(function() {
			FB.Connect.showPermissionDialog("publish_stream", function(permission) {
				var perm = 0;
				if (permission) {
					perm = 1;
				}
				
				var comment = $('#addCommentText').val();

				$('#newLike').show();
				location.href='#newResponseProgress';
			
				$.ajax({
					type: 'POST',
					url: 'response.php',
					data: {
						xid: xid,
						responseType: responseType,
						comment: comment,
						perm: perm
					},
					dataType: 'text',
					cache: false,
					success: function(text) {
						if (text=='added') {
							addResponseHtml(responseType);
							$('#newCommentsBox').hide();
							$('#newLike').hide();
						}
						else if (text.indexOf('error.php') != -1) {
							$('#newLike').hide();
							alert('Oops. Something went wrong. Please wait a moment and try again.');
						}
						else {
							$('#newLike').hide();
							alert(text);
						}
					},
					error: function() {
						$('#newLike').hide();
						alert('There was an error connecting to the server. Please try again.');
					}
				});
			});
		});
	});
}

function addResponseHtml(responseType) {
	var firstName = $('#proxyUserFirstName').text();
	var userPic = $('#proxyUserPic').text();
	var parseDom = false;
	
	if (firstName=='') {
		firstName = '<fb:name uid="loggedinuser" useyou="false" linked="false" firstnameonly="false"></fb:name>';
		userPic = '<fb:profile-pic uid="loggedinuser" size="square" facebook-logo="false"></fb:profile-pic>';
		parseDom = true;
	}
	else {
		userPic = '<img width="50" height="50" src="' + userPic + '"/>';
	}

	var message = '';
	if (responseType==1) {
		var comment = $('#addCommentText').val();

		message = '<span style="color:gray;"><b>' + firstName + '</b> says,</span><br/><br/><pre>' + htmlEntityEncode(comment) + '</pre>';
	}
	else if (responseType==0) {
		message = '<span style="color:gray;"><b>' + firstName + '</b></span> likes this.';
	}
	
	var genHtml = '' +
				'<div>' +
					'<hr/>' +
					'<div style="float:left; position:relative;">' +
						'<div class="friendPicSmall">' +
							'<span class="userPic" onclick="showUserProfile(' + FB.Connect.get_loggedInUser() + ', \'Your Profile\'); return false;">' +
								userPic +
							'</span>' +
						'</div>' +
						'<div class="ltCommentRight">' +
							message +
						'</div>' +
					'</div>' +
					'<br style="clear:both;"/>' +
				'</div>';
	
	var $responseDiv = $('#appendResponses')
	$responseDiv.append(genHtml);
	if (parseDom) {
		FB.XFBML.Host.parseDomElement($responseDiv.get(0));
	}
	$responseDiv.effect('highlight', {}, 2000);
}

function htmlEntityEncode(htmlText) {
	return $('<div/>').text(htmlText).html();
}

function deleteResponse(rid) {
	if(confirm("Delete this response?")) {
		var $progressBar = $('<img src="images/ajax_progress2.gif">');
		$progressBar.appendTo('#resp_'+rid);
		$.ajax({
			type: 'POST',
			url: 'response_del.php',
			data: {
				rid: rid
			},
			dataType: 'text',
			cache: false,
			success: function(text) {
				if (text=='deleted') {
					$('#resp_'+rid).fadeOut('fast', function() {
						$(this).remove();
					});
				}
				else {
					$progressBar.remove();
					alert(text);
				}
			},
			error: function() {
				$progressBar.remove();
				alert('There was an error connecting to the server.');
			}
		});
	}
	return false;
}

$(document).ready(function(){

	$dialog = $('#dialog');
	$dialog.dialog({
		autoOpen: false,
		modal: true,
		width: 720,
		height: 540,
		resizable: false,
		buttons: {
			'Close': function() { 
				$(this).dialog('close'); 
			}
		}
		/*,close: function(ev, ui) {
		}*/
	});

	$('.lt_speaker_box')
		.live('mouseover', function(){
			$(this).find('.boxoverlay').show();
		})
		.live('mouseout', function(){
			$(this).find('.boxoverlay').hide();
		});

	$('.boxoverlay,.lt_speaker_box').live('click', function() {
		document.location.href = $(this).attr('dest');
		return false;
	});
	
	$('#content_response .deleteResponse')
		.css('opacity', 0.3)
		.mouseenter(function() {
			$(this).css('opacity', 1);
		})
		.mouseleave(function() {
			$(this).css('opacity', 0.3);
		});
		
});