/**
* Follow button widget for MessageStream
* Differs from the original FollowButton.js by using DataLoader
*/

// TODO: Move to Utils or any more sensible place.
function isFollowedByCurrentUser(person) {
	if(person.isFollowedBy === undefined) { 
		return false;
	} else {	
		return person.isFollowedBy.indexOf(Creole.user.xid) != -1;
	}
};

function ajaxifyFollowButton() {
	console.log("ajaxify FollowButton...");

	$(".MessageStream .FollowButton").not(".noajax").not(".ajaxed").each(function() {			
		$(this).addClass("ajaxed");

		$(this).children("form").submit(function() {										
			var messageItem = MessageStream.getItem(this);

			var person = messageItem.owner;
			var undoPerson = Object.clone(person, "context");

			// Adjust the item
			if(isFollowedByCurrentUser(person)) {
				$(this).children('input[name="action"]').val("unfollow");
						
				person.isFollowedBy.removeValue(Creole.user.xid);

				console.log(person);
				console.log(undoPerson);				
			} else {
				$(this).children('input[name="action"]').val("follow");

				if(person.isFollowedBy === undefined) 
					person.isFollowedBy = new Array();
					
				person.isFollowedBy.push(Creole.user.xid);
			}
						
			var params = $(this).serializeObject();
			
			DataLoader.load(
				$(this).attr("action"), 
				params,
				undefined,
				undoPerson,
				person				
			);
			
			return false;
		});
	});

	console.log("... ajaxify FollowButton done.");
};

console.log("registering ajaxify FollowButton...");
ajaxifyFunctions.push(ajaxifyFollowButton);

$(ajaxifyFollowButton);

