// Setup event bindings when DOM is loaded
$(document).ready(function(){	
	// Autocomplete form
	$('#tag_form #name, #associated_tags_form #name').autocomplete({url: WWW_ROOT + 'tags.text', multiple: true, cacheLength: 25});
	
	// Member.profile - add service
	$("#services .service").submit(addService);
	
	// Member.profile - destroy service
	$('a.destroy_service').live('click', destroyService);
	
	// Member.profile - Change password
	$('a.change_password').click(function(){
		$('#change_password').modal();
		return false;
	});
	
	// Member.profile - Change Photo
	$('a.change_photo').click(changePhoto);
	
	// Member.profile - Delete friend
	$('a.delete_friend').click(removeFriend);
	
	// Member.view - Add friend
	$('a.add_friend').click(addFriend);
	
	// Member.signup
	$('a.swap_login_form').click(swapLoginForms);
	
	// Cancel service
	$('a.cancel').live('click', function(){
		$(this).parents('form').clear();
		return false;
	});
	
	$('a.help').live('click', function(event){
		
		return false;
	});
});

function changePhoto()
{
	$('#change_photo').modal();
	return false;
}

function swapLoginForms()
{
	var $form = $(this).parents('form');
	if ($form.attr('id') == 'vmb_login_form')
	{
		$('#sixhundred_block_login_form').show();
		$form.hide();
	}
	else
	{
		$('#vmb_login_form').show();
		$form.hide();
	}
	
	return false;
}

function addService(event)
{
	var $form = $(event.target);
	var $service = $form.parents('.service');
	
	if($form.find('input[name=identifier]').val() === '')
	{
		$.alert.error('Please fill in a username');
		return false;
	}
	
	$.alert.loading();
	
	$.post($form.attr('action'), $form.serialize(), function(json){
		if (json.status == 'ok')
		{
			$service.html(json.html);
			$.alert.success();
		}
		else
		{
			$.alert.error(json.message);
		}
		
	}, 'json');
	
	return false;
}

function destroyService(event)
{
	var url = $(this).attr('href');
	var $service = $(this).parents('.service');
	
	$.confirm("Are you sure you want to remove this service and all its items?", event, function(){
		$.getJSON(url, function(json){
			if (json.status == 'ok')
			{
				$service.html(json.html);
				$.alert.success();
			}
			else
			{
				$.alert.error(json.message);	
			}
		});
	});
	
	return false;
}

function removeFriend(event)
{
	var url = $(this).attr('href');
	var friend = $(this).parents('.friend');
	$.confirm('Are you sure you want to remove this member from \'Your People\'?', event, function(){
		$.getJSON(url, function(json){
			if (json.status == 'ok')
			{
				$(friend).fadeOut(500, function(){ $(this).remove(); });
				var friend_count = $('#people h3 .count').html();
				$('#people h3 .count').html(friend_count - 1);

				$.alert.success();
			}
			else
			{
				$.alert.error(json.message);
			}
		});
	});

	return false;
}