
var Alpha = new function() {

	var _emailRegEx = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	
	var _isBusy = false;	// indicates whether any server request is in progress
	
	(function() {
		
		$(document).ready(function() {
			
			$('#lnkLogin').click({'dialog': 'login'}, showRegisterLoginDialog);
			$('#lnkRegister').click({'dialog': 'register'}, showRegisterLoginDialog);
			$('.register-login-right').click(stopEventPropagation);
			
			$('#btnLogin').click(login);
			$('#btnRegister').click(register);
			$('#btnLoginCancel').click(function(event) {
				hideDialog(event);
				$('#txtLEmail').val('');
				$('#txtLPassword').val('');
			});
			$('#btnRegCancel').click(function(event) {
				hideDialog(event);
				$('#txtRName').val('');
				$('#txtRPassword').val('');
				$('#txtRPassword1').val('');
			})
			
			$('#btnInvite').click(doInvite);
			
			// add hideDialog event in case of alpha_register
			if($('#registerDialog').css('display') == 'block') $(document).bind('click', hideDialog);
		});
		
	})();
	
	function showRegisterLoginDialog(event) {
		stopEventPropagation(event);
		hideDialog();

		if(event.data.dialog && event.data.dialog == 'login') {
			$('#loginDialog').fadeIn('fast');
			// $('#txtLEmail').focus();
		}
		else {
			$('#registerDialog').fadeIn('fast');
			// $('#txtRName').focus();
		}
		
		$(document).bind('click', hideDialog);
	}
	
	function hideDialog(event) {
		
		// don't hide if some server request is in progress 
		if(_isBusy) return;
		
		if(typeof event === 'undefined') jQuery.fx.off = true;
		
		$('#txtLPassword').val('');
		$('#txtRPassword').val('');
		$('#txtRPassword1').val('');

		if($('#loginDialog').css('display') == 'block') $('#loginDialog').fadeOut('fast');
		
		if($('#registerDialog').css('display') == 'block') $('#registerDialog').fadeOut('fast');
		
		$(document).unbind('click');
		
		jQuery.fx.off = false;
	}
	
	function stopEventPropagation(event) {
		if(typeof event !== 'undefined' && event.preventDefault) event.preventDefault();
		if(typeof event !== 'undefined' && event.stopPropagation) event.stopPropagation();
	}
	
	function login(event)
	{
		var errorText = '';
		
		stopEventPropagation();
		
		// client side validations
		if(!_emailRegEx.test($('#txtLEmail').val())) {
			errorText = "Please enter a valid email address.";
			$('#txtLEmail').focus();
		}
		else if($('#txtLPassword').val().length === 0) {
			errorText = 'Please enter the password.';
			$('#txtLPassword').focus();
		}
		
		if(errorText.length) {
			
			$('#loginDialog .error').fadeOut('fast', function() {
				$('#loginDialog .error').html(errorText);
				$('#loginDialog .error').fadeIn('fast');	
			});
			return;
		}
		
		$('#btnLogin').prop('disabled', true);
		$('#loginDialog .error').fadeOut('fast');
		
		if(_emailRegEx.test($('#txtLEmail').val()))
		{
			showLoader(true, 'login');
			$('#btnLogin').prop('disabled', false);
			
			$.post(
				apiHost+"/login",
				{ email: $('#txtLEmail').val(), password: SHA1($('#txtLPassword').val()) },
				function(data) {
					showLoader(false, 'login');
					data = eval('(' + data + ')');
					if(data.success)
					{
						window.location.href='/';
					}
					else
					{
						if(data.error)
						{
							$('#loginDialog .error').html('Invalid email / password. Please try again.');
							$('#loginDialog .error').fadeIn('fast');
						}
					}
				}
			);
		}
		
	}
	
	function register(event) {
		
		var errorText = '';
		var name = $('#txtRName').val().trim(); 
		var password = $('#txtRPassword').val();
		var email = $('#txtREmail').val();
		
		stopEventPropagation(event);
		
		// Client side validations
		if(name.length === 0) {
			errorText = 'Please enter your name.';
			$('#txtRName').focus();
		}
		else if(name.length > 32) {
			errorText = "Name should not have more than 32 characters.";
			$('#txtRName').focus();
		}
		else if(password.indexOf(' ') != -1) {
			errorText = "Password cannot have spaces.";
			$('#txtRPassword').focus();
		}
		else if(password.length < 6) {
			errorText = "Please enter a password with 6 or more characters.";
			$('#txtRPassword').focus();
		}
		else if(password != $('#txtRPassword1').val()) {
			errorText = "Passwords do not match.";
			$('#txtRPassword').focus();
		}
		
		// display error msg if there is any
		if(errorText.length) {
			$('#registerDialog .error').fadeOut('fast', function() {
				$('#registerDialog .error').html(errorText);
				$('#registerDialog .error').fadeIn('fast');	
			});
			return;
		}
		
		// hide the error msg
		$('#registerDialog .error').fadeOut('fast');
		
		// disable submit button
		$('#btnSubmit').prop('disabled', true);
		
		showLoader(true, 'register');
		
		// if everything is fine, send rquest to the server
		sendRegistrationRequest(name, email, password);
	}
	
	function sendRegistrationRequest(pName, pEmail, pPassword) {
		$.post(
			apiHost+"/alpha_register",
			{invite_code: $('#ic_code').val(), name: pName, email: pEmail, password: SHA1(pPassword) },
			function(data) {
				showLoader(false, 'register');
				
				if(data)
				{
					data = eval('('+data+')');
					if(data.success)
					{
						// $('div.info').html(data.success.message+"<br/>Redirecting to ErosNow Home.");
						
						setTimeout(function(){$.post(
							apiHost+"/login",
							{ email: $('#txtREmail').val(), password: SHA1($('#txtRPassword').val()) },
							function(data)
							{
								showLoader(false, 'register');
								
								data = eval('(' + data + ')');
								if(data.success)
								{
									window.location.href='/';
								}
								else
								{
									if(data.error)
									{
										$('#registerDialog .error').html(data.error.message);
										$('#registerDialog .error').fadeIn('fast');
										// TODO: what if you get any error for log-in
									}
								}
							}
						);}, 2000);
					}
					else
					{
						if(data.error)
						{
							$('#registerDialog .error').html(data.error.message);
							$('#registerDialog .error').fadeIn('fast');
						}
					}
				}
			}
		);
	}
	
	function doInvite(event) {
		stopEventPropagation(event);
		
		$('#btnInvite').prop('disabled', true);
		
		if(_emailRegEx.test($('#txtInvite').val())) 
		{
			$('#infoInvite').fadeOut('fast');
			
			$.post(
				apiHost+"/alpha_invite",
				{ email: $('#txtInvite').val() },
				function(data)
				{
					if(data)
					{
						data = eval('('+data+')');
						
						if(data.success) {
							$('#infoInvite').removeClass('error');
							$('#infoInvite').html('Thank you for your interest in joining Eros Now. We\'ll send you an email when your account is active.');
							$('#formInvite').fadeOut('fast', function() {
								$('#infoInvite').fadeIn('fast');
							});
						}
						else if(data.error)
						{
							$('#btnInvite').prop('disabled', false);
							$('#infoInvite').html(data.error.message);
							$('#infoInvite').fadeIn('fast');
						}
					}
				}
			);
		}
		else
		{
			$('#btnInvite').prop('disabled', false);
			$('#txtInvite').focus();
			$('#infoInvite').fadeOut('fast', function() {
				$('#infoInvite').html("Please enter a valid email address.");
				$('#infoInvite').fadeIn('fast');	
			});
		}
		
	}
	
	function showLoader(show, dialog) {
		_isBusy = show;
		dialog = dialog == 'register' ? 'registerDialog' : 'loginDialog';
		// TODO: show some loading image
		if(show)
			$('#' + dialog + ' .loader').fadeIn('fast');
		else
			$('#' + dialog + ' .loader').fadeOut('fast');
	}
}
