(function($){

	var thirtyWays = {
		idPrefix : 'ThirtyWaysCommentInterface_Form_ThirtyWaysCommentsPostCommentForm',
		
		init : function()
		{
			$('a#facebook-btn').click(thirtyWays.onFBBtnClick);
			$('a#fb-logout').click(thirtyWays.onFBLogout);
			//$('form#'+thirtyWays.idPrefix).submit(thirtyWays.onFBSubmit);
			$('a.fb-share').click(thirtyWays.onShare);
			
			if(typeof $.fn.validate == 'function')
			{
				var rules = { Comment : 'required'};
				
				if ($('#'+thirtyWays.idPrefix+'_Name').length > 0)
					rules.Name = 'required';
				
				$('form#'+thirtyWays.idPrefix).validate({
					submitHandler : thirtyWays.onFBSubmit,
					rules : rules
				});
			}
			
			$('input#'+thirtyWays.idPrefix+'_Url').click(function()
			{
				if (this.value == 'Your personal URL if you have one')
					this.value = '';
			});
		},
		
		onShare : function(e)
		{
			FB.Connect.showShareDialog(window.location.href.toString(), null);
			return false;
		},
		
		onFBSubmit : function(form)
		{
			var publish = $('#'+thirtyWays.idPrefix+'_Publish');
			
			if (publish.length <= 0)
			{
				form.submit();
				return;
			}
			
			var checkbox = publish.get(0);

			if (!checkbox.checked)
			{
				form.submit();
				return;
			}
			
			var comment = $('#'+thirtyWays.idPrefix+'_Comment').get(0).value;
			var data = {
				'post' : (window.location.toString().split('#'))[0],
				'blog' : window.location.protocol + '//' + window.location.host + $('#'+thirtyWays.idPrefix+'_Blog').get(0).value,
				'post_name' : document.title
			};
			FB.Connect.showFeedDialog(74258633833, 
										data, 
										[], 
										'',
										null, 
										FB.RequireConnect.require, 
										thirtyWays.onEndFeedDialog, 
										'Comment on ' + document.title,
										{value: comment});
		},
		
		onEndFeedDialog : function()
		{
			$('form#'+thirtyWays.idPrefix).get(0).submit();
		},
		
		onFBBtnClick : function(e)
		{
			//thirtyWays.initGuestForm();
			
			//add FB stuff
			FB.Connect.requireSession(thirtyWays.onFBUserLogin);
			
			return false;
		},
		
		onFBUserLogin : function()
		{
			window.location = window.location.protocol + '//' + window.location.host + window.location.pathname + window.location.search + '#comment-form';
			window.location.reload();
		},
		
		onFBLogout : function(e)
		{
			FB.Connect.logoutAndRedirect(window.location.toString());
			return false;
		}
	}
	
	$(function()
	{
		thirtyWays.init();

		FB.init("a2748e2ded2a48426a2a82560a5be916", "/xd_receiver.htm", { });
		
		FB.ensureInit(function()
		{
			if (!window.location.hash || window.location.hash == '')
				return;
			
			var position = $(window.location.hash).offset();
			
			if (position)
				window.scrollTo(position.left, position.top);
		});
	});
})(jQuery);