$(document).ready(function(){
	
	$("#connect-twitter").click(function(){
		$("#tie-profile-post").fadeOut(function(){
			$("#profile-connect-twitter").fadeIn();
		});
		return false;
	});
	
	$(".profile-cancel").click(function(){
		$("#profile-connect-facebook, #profile-connect-twitter").fadeOut(function(){
			$("#tie-profile-post").fadeIn();
		});
		return false;
	});
	
	$("#tie-profile").bind('submit', post_to_wall);
	$("#tie-profile a.newpost").bind('click', post_to_wall);
	
	$("#tw_connect").bind('click', connect_twitter);
	
	$('#wall a.delete_wallpost').click(function() {
		$.get($(this).attr('href'));
		$('#wallpost-' + $(this).attr('rel')).slideUp();

		return false;
	});
});


function post_to_wall(e) {
	e.preventDefault();
	e.stopPropagation();
	
	msg = $("#status_msg").val();
	if(msg == '' || msg == 'Write something on this wall.') return false;
	
	$.post($('#tie-profile').attr('action'), $('#tie-profile').serialize(), function(data) {
		$('#wall').prepend(data);
		
		$("#status_msg").val('Write something on this wall.');
		$("#status_msg").blur();
		
		$('#wall a.delete_wallpost').click(function() {
			$.get($(this).attr('href'));
			$('#wallpost-' + $(this).attr('rel')).slideUp();

			return false;
		});
	});
}


function connect_twitter() {
	$.post(
		'/profile/ajax_connect:twitter',
		{
			username : $('#tw_username').val(),
			password : $('#tw_password').val(),
			_ : new Date().getTime()
		}, function(data) {
			if(data == 'OK') {
				alert('Your Twitter account has been connected! Tweets will now appear automatically on your wall. Please be patient, it may take 1-2 minutes to take effect.');
				$('#profile-connect-twitter a.profile-cancel').click();
			} else {
				alert('Failed to connect to your Twitter account. Please check your login and try again.');
			}
		}
	);
}




