$(document).ready(function () {
	/* Update User Form */
	$('.language_option').bind('click', function () {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
			$(this).children('input').attr('checked',false);
		} else {
			$(this).addClass('selected');
			$(this).children('input').attr('checked',true);
		}
	});
	var toggleFileSelector = function () {
		if ($('.upload_photo').length) {
			$('#photo').css('display','none');
			$('.image_types').css('display','none');
		} else {
			$('#photo').css('display','inline');
			$('.image_types').css('display','block');
		}
	}
	toggleFileSelector();
	$('.upload_photo').live('click', function () {
		$(this).remove();
		toggleFileSelector();
		return false;
	});
	$('.remove_photo').live('click', function () {
		$(this).css('display','none');
		var span = $('<span class="really"> You sure? </span>');
		var yes = $('<a href="'+$(this).attr('href')+'" class="yes">Yes!</a>');
		$(this).before(span.append(yes));
		yes.bind('click', function () {
			$.ajax({
				type: 'post',
				url: $(this).attr('href'),
				success: function (data) {
					if (data.message == 'success') {
						$('.profile_photo').attr('src',data.photo);
						$('.remove_photo').remove();
						yes.remove();
						span.remove();
					} else {
						alert(data.message);
					}
				},
				dataType: "json"
			});
			return false;			
		});
		setTimeout ( function () {
			$('.remove_photo').css('display','block');
			yes.remove();
			span.remove();
		}, 2100);
		return false;
	});
	$('.deactive_profile').bind('click', function () {
		$(this).css('display','none');
		var span = $('<span class="really deactive_check"> Really? Deactivate your account? </span>');
		var yes = $('<a href="'+$(this).attr('href')+'" class="yes">Yes!</a>');
		$(this).before(span.append(yes));
		yes.bind('click', function () {
			$.ajax({
				type: 'post',
				url: $(this).attr('href'),
				success: function (data) {
					if (data.message == 'success') {
						window.location = '/user/logout';
					} else {
						alert(data.message);
					}
				},
				dataType: "json"
			});
			return false;			
		});
		setTimeout ( function () {
			$('.deactive_profile').css('display','block');
			yes.remove();
			span.remove();
		}, 2100);
		return false;
	});
	$('#update_profile').validate({
		submitHandler:function(form) {
			form.submit();
		},
		messages: {
			name: {
				required: 'So, what is your name?' },
			email: {
				required: 'We need a valid e-mail address for you.',
				email: 'We need a valid e-mail address for you.',
				remote: 'That e-mail address has been registered already.' }
		},
		rules: {
			name: {
				required: true
			},
			email: {
				required: true,
				email: true,
				remote: {
					url: "/user/unique_email",
					type: "post",
					data: {
						email: function() {
							return $("#email").val();
						}
					}
				}
			},
			homepage: {
				url: true
			}
		}
	});
	/* Change Password Form */
	$('#update_password').validate({
		submitHandler:function(form) {
			$('#update_password input[type=submit]').attr('disabled','disabled');
			$('#update_password input[type=submit]').after(loading_img);
			$.ajax({
				type: 'post',
				url: $(form).attr('action'),
				data: $(form).serialize(),
				success: function (data) {
					if (data.message == 'success') {
						$('.success').remove();
						$(form).before($('<p class="success"/>').text(data.result));
						$('.success').hide().fadeIn("slow");
						$('input[type=password]').val('');
						$('#update_password input[type=submit]').removeAttr('disabled');
					} else {
						alert(data.message);
					}
					$(loading_img).remove();
				},
				dataType: "json"
			});
			return false;
		},
		messages: {
			old_password: {
				required: 'We need to confirm your old password.' },
			password: {
				required: 'Required',
				minlength: 'Your password must be at least 8 characters.' },
			password_confirm: {
				required: 'Required',
				equalTo: 'You misspelled your new passwords.' }
		},
		rules: {
			old_password: {
				required: true
			},
			password: {
				required: true,
				minlength: 7
			},
			password_confirm: {
				equalTo: "#password"
			}
		}
	});
	/* Send Message */
	$('#send_message').submit( function (form) {
		$('#send_message input[type=submit]').after(loading_img);
		if ($('#message').val() == '') {
			$('#message').focus();
		} else {
			$('#send_message input[type=submit]').attr('disabled','disabled');
			$.ajax({
				type: 'post',
				url: $('#send_message').attr('action'),
				data: $('#send_message').serialize(),
				success: function (data) {
					if (data.message == 'success') {
						$('#message').val('');
						displayMessage(data,false);
					} else if (data.message == 'not_logged_in') {
						result = $('<p class="login_message" />').html(data.result);
						$('.messages').after(result);
						result.fadeTo(890,1);
					} else {
						alert(data.message);
					}
					$('#send_message input[type=submit]').removeAttr('disabled');
					$(loading_img).remove();
				},
				dataType: "json"
			});
		}
		return false;
	});
	var displayMessage = function (json,append) {
		message = $('<div class="message clearfix"><a href="/profile/'+json.from_user_id+'"><img src="'+json.from_user_photo+'" alt="'+json.from_user+'" class="medium_user"/></a><div class="info"><a href="/profile/'+json.from_user_id+'">'+json.from_user+'</a> wrote <span class="date">'+json.date+'</span></div><div class="text">'+json.text+'</div></div>');
		$.each(json.replies, function (i,item) {
			message.append(displayReply(item));
		});
		message.append('<a href="#'+json.id+'" class="reply_link">Reply</a>');
		if (append) {
			$('#see_more_messages').before(message);
		} else {
			$('#send_message').after(message);
		}
	};
	var displayReply = function (reply) {
		return $('<div class="reply"><a href="/profile/'+reply.user_id+'"><img src="'+reply.photo+'" alt="'+reply.name+'" class="small_user"/></a><div class="info"><a href="/profile/'+reply.user_id+'">'+reply.name+'</a> wrote <span class="date">'+reply.date+'</span></div><div class="text">'+reply.message+'</div></div>');
	};
	$('#see_more_messages').live('click', function () {
		return browseMessages(this);
	});
	var browseMessages = function (a) {
		see_more_text = $('#see_more_messages').text();
		$('#see_more_messages').html('<img src="http://www.onlinelanguagehelp.com/media/images/loading.gif" alt="Loading..." class="loading" />');
		$.ajax({
			type: 'get',
			url: $('#see_more_messages').attr('href'),
			data: 'limit=5&offset='+$('.message').length,
			success: function (data) {
				for (i in data.messages) {
					displayMessage(data.messages[i],true);
				}
				if (data.count <= $('.message').length) {
					$('#see_more_messages').remove();
				} else {
					$('#see_more_messages').html(see_more_text);
				}
			},
			dataType: "json"
		});
		return false;
	}
	if ($('.message').length < 5) {
		$('#see_more_messages').hide();
	}
	$('.reply_link').live('click', function () {
		$('.reply_link').show();
		$('.reply_form').hide();
		$(this).hide();
		if ( $('#rf'+$(this).attr('href').substr(1)).length ) {
			$('#rf'+$(this).attr('href').substr(1)).show();
		} else {
			var reply_form = $('<form method="post" action="/message/reply/'+$(this).attr('href').substr(1)+'" class="reply_form" id="rf'+$(this).attr('href').substr(1)+'"><textarea name="message"></textarea><input type="submit" value="Reply" /></form>');
			$(this).before(reply_form);
		}
		$('#rf'+$(this).attr('href').substr(1)).children('textarea').select();
	});
	$('.reply_form').live('submit', function (form) {
		var form = $(this);
		if ($(this).children('textarea').val().length > 2) {
			$(this).children('input').after(loading_img);
			$(this).children('input[type=submit]').attr('disabled','disabled');
			$.ajax({
				type: 'post',
				url: $(this).attr('action'),
				data: $(this).serialize(),
				success: function (data) {
					form.before(displayReply(data));
					form.hide();
					form.children('textarea').val('');
					form.children('input[type=submit]').attr('disabled','false');
					$('.reply_link').show();
					$(loading_img).remove();
				},
				dataType: "json"
			});
		}
		return false;
	});
});