$.namespace('Chide');

Chide.login = function () {
	var loginButtonHandler = function (e) {
		var that = this;
		var errors = $('#login-errors');
		e.preventDefault();
		errors.text('').hide('slow');		
		if (Chide.login.form_lastTrigger !== e.target) {
			Chide.login.form_lastTrigger = e.target;
			$('#login-form').parent().css({
				top: $(that).offset().top + 28,
				right: $(document).width() - $(that).offset().left - 18
			}).end().html('<span class="loading">Loading, please wait...<\/span>').load(this.href + '?c=' + randomString(20), undefined, function(responseText, textStatus, request){
				$(this).fadeIn().find('form').find('input:text:first').focus().end().ajaxForm({
					beforeSubmit: function(data, form, options){
						errors.hide();
						form.find(':input, :submit').attr('disabled', true);
					},
					dataType: 'json',
					success: function(response){
						if (response.success) {
							if (response.redirect) {
								window.location = response.redirect;
							}
							else {
								window.location.href = '/account/';
							}
							return;
						}
						else {
							$('#login-form').find(':input, :submit').attr('disabled', false);
							for (field in response.errors) {
								$('#login-errors').text(response.errors[field][0]);
								break;
							}
							errors.show('drop', {
								direction: 'up'
							});
							$('#login-form input:text:first').focus();
						}
					},
					error: function(){
						
					}
				});
			});
		}else{
			Chide.login.form_lastTrigger = undefined;
			$('#login-form').fadeOut();
		}
	};

	return {
		init: function () {
			$('#account-info .login-box a.association.login').click(loginButtonHandler);
		}
	};
}();

$(Chide.login.init);
