$(document).ready(function(){

	FB.init({
		appId  : '166478891950', // app id for azulcasa.net/~devin/fly/webroot
		status : true, // check login status
		cookie : true, // enable cookies to allow the server to access the session
		xfbml  : true  // parse XFBML
	});

	// Bind to the auth login event, and post this to update/store
	// the user's facebook_id and access_token
	FB.Event.subscribe('auth.login',
		function (response) {
			$.ajax({
				url  : baseUrl + 'my/update-facebook-info',
				type : 'POST',
				data : {
					facebook_id  : response.session.uid,
					access_token : response.session.access_token 
				},
				success : function (msg) {
					location.href = '';
				},
				dataType : 'json'
			});
		}
	);

	$('.deauthorize-facebook').click(function (event) {
		$.ajax({
			url : baseUrl + 'my/update-facebook-info',
			type : 'POST',
			data : {
				facebook_id : null,
				access_token : null
			},
			success : function (msg) {
				location.href = '';
			},
			dataType : 'json'
		});
	});

	$('.postToFacebook').click(function(event){
		event.preventDefault();
		event.stopPropagation();
		var eventId = $(this).attr('eventId');
		var feId = $(this).attr('feId');
		FB.Connect.requireSession(function(){
		FB.Connect.showPermissionDialog(
			"create_event, rsvp_event",   
				function() {											      
					if(feId == 0) {
						$('#facebook-dialog').dialog('open');
						$('input#fbcatselect').unbind();

						$('input#fbcatselect').click(function(event) {
							var cat = $('#fbcategory').selectedValues();
							var subcat = $('#fbsubcategory').selectedValues();
							$.post(baseUrl+'events/post-to-facebook',
								{event: eventId,
								category: cat,
								subcategory: subcat},
								function(html) {
									alert('This event has been posted to your facebook');
								},
								'text');
							$('#facebook-dialog').dialog('close');														
						})
					} else {
						$.post(baseUrl+'events/post-to-facebook',
							{event: eventId},
							function(html) {
								alert('You have RSVPed to this even on facebook');
							},
							'text');
					}
				}, 
				function(){
					alert('error')
				});
			},  
		true);              
	});

	$('#facebook-dialog').dialog({
		autoOpen: false,
		width: 300,
		height: 300,
		modal: true,
		overlay: {
			opacity: 0.5,
			background: 'black'
		} 
	});
});

