jQuery(function() {
	jQuery('#shop-new-account').click(function() {
		jQuery(this).fadeOut(500, function () {
			jQuery('#account-choice').fadeIn(500);
		});
	});
	
	jQuery('.account-choice-form .submit').click(function() {
		validateAccountChoiceForm();
	});
	
	jQuery('.account-login-form .submit').click(function() {
		validateAccountLoginForm();
	});
	
	jQuery('#password2').keyup(function(e) {
		if(e.keyCode == 13) { validateAccountChoiceForm(); }
	});
	
	jQuery('#login_password').keyup(function(e) {
		if(e.keyCode == 13) { validateAccountLoginForm(); }
	});
});

function validateAccountChoiceForm() {
	var email = jQuery('#email').val();
	jQuery.ajax({
		type: 'POST',
		cache: false,
		url: baseUrl + '/ajax-account/check-email',
		dataType: 'json',
		data: 'email=' + email,
		success: function(account) {
			hideErrors();
			
			var password1 = jQuery('#password1').val();
			var password2 = jQuery('#password2').val();
			var passwordError = false;
			var passwordLengthError = false;
			
			if(password1.length < 5) {
				passwordLengthError = true;
			}
			
			if(password1 != password2) {
				passwordError = true;
			}
			
			if(account.response == 'success' && passwordError == false && passwordLengthError == false) {
				jQuery('.account-choice-form').submit();
			} else {
				if(passwordLengthError == true) {
					showError('#password2', 'Uw wachtwoord moet minimaal 5 tekens lang zijn.');
				}
				
				if(passwordError == true) {
					showError('#password2', 'Beide wachtwoorden moeten identiek zijn.');
				}
				
				if(account.response == 'invalid') {
					showError('#email', 'Ongeldig e-mail adres');
				}
				
				if(account.response == 'match') {
					showError('#email', 'Het ingevulde e-mail adres is al bekend in ons systeem. Gebruik het linker formulier om in te loggen met dit e-mail adres.');
				}
				jQuery('.submit').fadeIn(500);
			}
		}
	});
}

function validateAccountLoginForm() {
	var email = jQuery('#login_email').val();
	var password = jQuery('#login_password').val();
	jQuery.ajax({
		type: 'POST',
		cache: false,
		url: baseUrl + '/ajax-account/check-login',
		dataType: 'json',
		data: 'email=' + email + '&password=' + password,
		success: function(account) {
			hideErrors();
			if(account.response == 'success') {
				jQuery('.account-login-form').submit();
			} else {
				showError('#login_password', 'Ongeldig wachtwoord of onbekend e-mail adres');
			}
		}
	});
}
