﻿function login(settings) {
    login.prototype.init.apply(this, [settings]);
};

login.prototype = {
    init: function(settings) {
        var defaults = {
            timeout: 60000
        };
		var context = this;
		context.settings = $.extend(defaults, settings);
		context.form = $('#loginForm');
		context.emailControl = $('#email');
		context.passwordControl = $('#password');
		context.loginButton = $('#loginButton');
		context.loginRegisterButton = $('#loginRegisterButton');
		context.loginErrorsControl = $('#loginErrors');
		context.loginDialog = $('#loginForm').dialog({
			autoOpen: false,
			modal: true,
            draggable: true,
            resizable: false,
			width: 384,
			height: 276,
			title: 'Login'
		});

		var inherit = ['color','font-weight', 'font-family'];
		$('#email', context.form).watermark({html:"Your Email", inherit:inherit});
		$('#password', context.form).watermark({html:"Your Password", inherit:inherit});
		
		$('a.loginLink').click(function(){ 
			context.loginDialog.dialog("open"); 
			$('#email', context.form).blur();
			return false; 
		});
		
		// Bind events
		context.loginButton.click(function(){ 
			// 1) Block interface
			$.blockUI();
			
			// 2) Make AJAX request
			context.loginErrorsControl.hide();
			$.ajax({
				url: context.settings.requestUrl + '/Login',
				type: 'POST',
				dataType: 'json',
				data:  $.toJSON({
					'email': context.emailControl.val(),
					'password': context.passwordControl.val()
				}),
				contentType: 'application/json; charset=utf-8',
				success: function(data) {
					var response = $.evalJSON(data.d);
					$.unblockUI();
					
					// If not success
					if (!response.Success){
						context.loginErrorsControl.show();
						return;
					}
					
					isAuthenticated = true;
					
					// 3) Hide login links and register links
					$('.loginInvitation').hide();
					$('.registerInvitation').hide();
					$('.logoutInvitation').show();
					
					context.hide();
				},
				error: function(data, status, e) {
					$.unblockUI();
					context.loginErrorsControl.show();
				}
			});						

		});
		
		context.loginRegisterButton.click(function(){ 
			context.loginDialog.dialog("close"); 
			registerControl.show();
			return false;
		});
	},
	
	// Hide dialog
	hide: function(){
		var context = this;
		context.loginDialog.dialog("close"); 
	}	
}	

function register(settings) {
    register.prototype.init.apply(this, [settings]);
};

register.prototype = {
    init: function(settings) {
        var defaults = {
            timeout: 60000,
			redirectOnSuccess: true
        };
		
		var context = this;
		context.settings = $.extend(defaults, settings);
		context.callbacks = [];
		context.form = $('#registerForm');
		context.emailControl = $('#rEmail');
		context.passwordControl = $('#rPassword');
		context.registerButton = $('#registerButton');
		context.cancelRegisterButton = $('#cancelRegisterButton');
		context.registerStatusControl = $('#registrationStatus');
		context.registerErrorsControl = $('#registrationErrors');
		context.registerDialog = context.form.dialog({
			autoOpen: false,
			modal: true,
            draggable: true,
            resizable: false,
			width: 705,
			height: 592,
			title: 'Create your account',
			close: function(){
				$('input', context.form).each(function(){
					if (this.tip)
						$(this).qtip("destroy");
				});				
			}
		});
		
		var inherit = ['color','font-weight', 'font-family'];
		$('#rPassword', context.form).watermark({html:"Your Desired Password", inherit:inherit});		
		$('#rRetypePassword', context.form).watermark({html:"Retype your password", inherit:inherit});
		context.emailControl.watermark({html:"Your E-mail", inherit:inherit});
		$('#rRetypeEmail', context.form).watermark({html:"Retype your E-mail", inherit:inherit});
		
		// Init all links where sign up control must be displayed
		$('a.registerLink').click(function(){ 
			context.registerDialog.dialog("open"); 
			$('#rEmail', context.form).blur();
			return false; 
		});		
		
		// Bind events
		$('#rEmail', context.form).blur(function(){
			// Make sync Ajax request to server to verify if email is available
			var email = context.emailControl.val();
			
			if (email && email != '')
				$.ajax({
					url: context.settings.requestUrl + '/IsEmailAvailable',
					type: 'POST',
					dataType: 'json',
					data:  $.toJSON({
						'email': email
					}),
					contentType: 'application/json; charset=utf-8',
					success: function(data) {
						var response = $.evalJSON(data.d);
						if (!response.IsAvailable && response.Email == context.emailControl.val())
							context.showIsNotAvailableEmail();
					},
					error: function(data, status, e) {
						context.showIsNotAvailableEmail();
					}
				});			
		});
		
		context.registerButton.click(function(){ 
			if (context.validate())
				context.register();
				
			return false;
		})
		
		context.cancelRegisterButton.click(function(){ 
			context.hide();
			return false;
		})
	},
	
	// Validate user input
	validate: function(){
		var context = this;
	
		// Make client validation
		return $('form', context.form).valid();
	},
	
	// Show validation message which says that email is not available
	showIsNotAvailableEmail: function(){
		var context = this;
		
		if (context.emailControl[0].tip) // Don't show anything if there is another validation message already
			return
				
		context.emailControl[0].tip = context.emailControl.qtip({
			content: 'This email address is not available',
			style: {
				name: "validator"
			},
			position: {
				corner: {
					tooltip: "leftMiddle",
					target: "rightMiddle"
				}
			},
			show: { effect: "fade", when: false, ready: true, delay: 200 },
			hide: false
		});		
	},
	
	// Send register request
	register: function(){
		var context = this;
		
		// 1) Block interface
		$.blockUI();
		context.registerStatusControl.show();
		context.registerErrorsControl.empty().hide();
		
		// 2) Make Ajax request to Register
		$.ajax({
			url: context.settings.requestUrl + '/Register',
			type: 'POST',
			dataType: 'json',
			data:  $.toJSON({
				'email': context.emailControl.val(),
				'password': context.passwordControl.val()
			}),
			contentType: 'application/json; charset=utf-8',
			success: function(data) {
				var response = $.evalJSON(data.d);
				$.unblockUI();
				context.registerStatusControl.hide();
				
				// If not success
				if (!response.Success){
					context.registerErrorsControl.append(response.Error);
					context.registerErrorsControl.show();
					return;
				}

				// 3) Close dialog
				context.hide();
				$('.registerInvitation').hide();
				// To-do: add activation information to cookie
				// this reminder must be showsn instead of "create account link"
				
				// 4) Run all callbacks on success
				for (var i = 0; i < context.callbacks.length; i++){
					if ($.isFunction(context.callbacks[i]))
						context.callbacks[i](response.Email, response.Id);
				}
				
				// 5) Redirect to signup complete page
				if (context.settings.redirectOnSuccess)
					window.location = context.settings.successUrl;
				
			},
			error: function(data, status, e) {
				context.registerErrorsControl.append(e);
				context.registerErrorsControl.show();
				$.unblockUI();
				context.registerStatusControl.hide();
			}
		});			
	},
	
	// Add callback methods to queue - they will be called when sign up is complete
	addCallback: function(func){
		var context = this;
		context.callbacks.push(func);
	},
	
	// Show register dialog
	show: function(){
		var context = this;
		context.registerDialog.dialog("open"); 
	},
	
	// Hide dialog
	hide: function(){
		var context = this;
		context.registerDialog.dialog("close"); 
	}
	
}	