/**
 * FollowButton.js - AJAX stuff for FollowButton widget.
 * 
 * This script installs handlers for every form inside a div with class .FollowButton.
 * If the FollowButton is embedded in a FollowerTableRow, as on Followers or Profile,
 * then clicking it will toggle the YES/NO text and class.
 * 
 * @author Miles, Daniel
 */

// Change the text of the follow/unfollow button.
function FollowButton_toggleButtonText(button) {
	if (button.html() == "Stop Following") {
		button.html("Follow");
	} else {
		button.html("Stop Following");
	}
};
	
// If we're on the Followers page, change the red/green "yes/no" message
// to indicate our new following status.
function FollowButton_toggleFollowingOnFollowersPage(form) {
	$(form).parents('.user').find('.following span:not(.since)').each(function() {
		$(this).toggleClass('yes').toggleClass('no');
		if ($(this).html() == 'YES') {
			$(this).html('NO');
		} else {
			$(this).html('YES');
		}
	});
};

// The ajax call was successful: change the page to reflect
// our new follower status wrt the person we clicked on.
function FollowButton_succeed(response, form) {
	$('.status', form).toggleClass('loading');
	var submitButton = $(form).find(':submit');
	submitButton.removeAttr('disabled')
		.toggleClass('follow').toggleClass('unfollow');
	FollowButton_toggleButtonText(submitButton);
	// change the action of the follow/unfollow form
	// to do the other thing next time we click it.
	$(form).find('input[name=action]').each(function() {
		if ($(this).val() == 'unfollow') {
			$(this).val('follow');
		} else {
			$(this).val('unfollow');
		}
	});
	FollowButton_toggleFollowingOnFollowersPage(form);
	handleAjaxResponse(response);
};
	
// install the onSubmit handler for every FollowerButton.
function FollowButton_ajaxify() {
	$('.FollowButton form')
		.filter(':parents(.MessageStream)')
		.not(".ajaxed")
			.addClass('ajaxed')
			.submit(function() {
				console.log("ajax submit please");
				
				var form = $(this);
				
				$(':submit', this).attr('disabled', 'disabled');
				
				form.ajaxSubmit({
					dataType: 'json',
					error: function(response) {
						fail(response, form);
					},
					success: function(response) {
						if (response['success']) {
							FollowButton_succeed(response, form);
						} else {
							fail(response, form);
						}
					}
				});
				
				console.log("ajax submit please... return false");
				
				return false;
			});
};

console.log("registering FollowButton_ajaxify");
ajaxifyFunctions.push(FollowButton_ajaxify);

