$(function() {
	$signupLinks = $('.eventSignup');
	
	if(typeof logged_in !== 'undefined') {
		
		$.fn.signup = function() {
			return $(this).removeClass('eventSignup').addClass('eventUnsignup').text('Unsignup');
		};
		
		$.fn.unSignup = function() {
			return $(this).removeClass('eventUnsignup').addClass('eventSignup').text('Signup');
		};
		
		$.fn.waiting = function() {
			return $(this).addClass('waiting');
		};
		
		$.fn.notWaiting = function() {
			return $(this).removeClass('waiting');
		};
		
		$.ajax({
			type	: 'POST',
			url		: '/ajax/events',
			data	: {
				'f'			: 'userSignups'
			},
			dataType: 'json',
			beforeSend	: function() {
				$signupLinks.waiting();
			},
			success	: function(events) {
				$signupLinks.notWaiting();
				for(var i in events) {
					// Change events to show that the user has already subscribed
					$signupLinks.filter('[rel="' + events[i].id +'"]').signup();
				}
			}
		});

		// Add handler for event signup clicks
		$('.eventSignup').live('click', function(e) {
			e.preventDefault();

			$this = $(this);
			event = $this.attr('rel');

			// Send data to signup for event
			$.ajax({
				type	: 'POST',
				url		: '/ajax/events',
				data	: {
					'f'			: 'eventSignup',
					'event_id'	: event
				},
				beforeSend	: function() {
					$this.waiting();
				},
				dataType: 'json',
				success	: function(count) {
					// console.log(count);
					// On success, show change
					$this.notWaiting().signup();
				}
			});
		});

		// Add handler for event un-signup clicks
		$('.eventUnsignup').live('click', function(e) {
			e.preventDefault();

			$this = $(this);
			event = $this.attr('rel');

			// // Send data to un-signup for event
			$.ajax({
				type	: 'POST',
				url		: '/ajax/events',
				data	: {
					'f'			: 'eventUnsignup',
					'event_id'	: event
				},
				beforeSend	: function() {
					$this.waiting();
				},
				dataType: 'json',
				success	: function(count) {
					// console.log(count);
					// On success, show change
					$this.notWaiting().unSignup();
				}
			});

		});
		
	} else {
		
		$signupLinks.hide();
		
	}
	
});
