// TODO: add some password requirements
// TODO: confirm registrations (right now they go right to member area)

var Core = {
	templateRoot: 'templates',
	templateFiles:['core.html', 'access.html', 'login.html', 'forgotPassword.html'],
	templates:{},

	$core: null,
	$access: null,
	$login: null,
	$forgotPassword: null,
	
	qtipOpts: null,

	msg_accessValidation1: "Please enter your email address two times",
	msg_accessValidation2: "Please enter your email address",
	msg_accessValidation3: "Please enter a valid email address",
	msg_accessValidation4: "Please enter your email address again",
	msg_accessValidation5: "Your email addresses don't match",

	msg_usernameExists: "You are already registered with that email address",

	msg_forgotPasswordValidation1: "Please enter your email address",
	msg_forgotPasswordValidation2: "Please enter a valid email address",
	
	msg_loginValidation1: "Please enter your email address and password",
	msg_loginValidation2: "Please enter your email address",
	msg_loginValidation3: "Please enter your password",

	init: function(successFn){
		this.$core = $('#core');

		this.setDefaults();

		this.getTemplates(function(){
			Core.loadCore();
			if(successFn) successFn();
		});
	},

	setDefaults: function(){
		$.fn.qtip.styles.greenie = { // Last part is the name of the style
			width:190,
			name: 'light', 
			tip: true, 
			background:'#A2D959',
			lineHeight:'1.1em',
			border: {
				width: 2,
				radius: 5,
				color: '#A2D959'
			}
		};

		this.qtipOpts = {
			style:'greenie',
			position: {
				corner: {
					target: 'rightMiddle',
					tooltip: 'leftMiddle'
				},
				adjust: { x:5, y:0 }
			},
			show: { when: { event: 'focus' } },
			hide: { when: { event: 'blur' } }
		};
		
		$.jqm.params.overlay = 85;
		$.jqm.params.modal = true;
	},
	
	loadCore: function(){
		Core.$core.html( this.templates['core'] );
		
		this.$access = $('#access');
		this.$login = $('#login');
		this.$forgotPassword = $('#forgotPassword');

		//this.$access.jqm({trigger: '#buy a, .register'});
		this.$access.jqm({trigger: 'a.access'});
		this.$login.jqm({trigger: '#navLogin'});
		this.$forgotPassword.jqm();

		Core.loadAccess();
		Core.loadLogin();
		Core.loadForgotPassword();
	},

	loadAccess: function(){
		Core.$access.html( this.templates['access'] );
		
		$('[name=emailAddress1], [name=emailAddress2]', Core.$access).qtip(Core.qtipOpts);

		// delegates
		//
		Core.$access.click(function(e){
			var $target = $(e.target);
			
			if($target.is('a.send')){
				Core.sendAccessRequest(function(sent){
					if(sent){
						Core.$access.find('form').hide().end().find('.message.success').show();
					} else {
						var $msg = Core.$access.find('.message.failure');
						$msg.show();
						setTimeout(function(){ $msg.fadeOut("slow").hide(); }, 4000);
					}
				});
				
				return false;
			}
			
			if($target.is('a.cancel') || $target.is('a.ok')){
				Core.$access.jqmHide();
									
				return false;
			}
		});
	},

	loadLogin: function(){
		Core.$login.html( this.templates['login'] );
		
		$('[name=emailAddress], [name=password]', Core.$login).qtip(Core.qtipOpts);

		$('#btnLogin', Core.$login).click(function(){ Core.login(); return false; });
		
		// enter key for password field clicks login button
		$('[name=password]', Core.$login).keypress(function(e){
			if(e.which == 13){
				$('#btnLogin', Core.$login).click();
			}
		});

		$('#btnLoginCancel', Core.$login).click(function(){
			$('#login').jqmHide();
			$('[name=emailAddress], [name=password]', Core.$login).each(function(){ $(this).val(''); });
			return false;
		});

		$('#btnForgotPassword', Core.$login).click(function(){
			// prepare the forgot password view
			Core.$forgotPassword
				.find('.message').hide().end()
				.find('[name=emailAddress]').val('').end()
				.find('form').show();

			$('#login').jqmHide();
			$('#forgotPassword').jqmShow(); 
			return false;
		});
	},

	loadForgotPassword: function(){
		Core.$forgotPassword.html( this.templates['forgotPassword'] );
		
		$('[name=emailAddress]', Core.$forgotPassword).qtip(Core.qtipOpts);

		// delegates
		//
		Core.$forgotPassword.click(function(e){
			var $target = $(e.target);
			
			if($target.is('a.send')){
				/*
				var $spinner = Core.$forgotPassword.find('.spinner');
				
				Core.$forgotPassword
					.find('a.cancel').hide().end()
					.find('a.send').html('Sending...').after( $spinner ).show();
				*/
				
				Core.sendPassword(function(sent){
					if(sent){
						Core.$forgotPassword.find('form').hide().end().find('.message.success').show();
					} else {
						var $msg = Core.$forgotPassword.find('.message.failure');
						$msg.show();
						setTimeout(function(){ $msg.fadeOut("slow").hide(); }, 4000);
					}
				});
				
				return false;
			}
			
			if($target.is('a.cancel') || $target.is('a.ok')){
				Core.$forgotPassword.jqmHide();
									
				return false;
			}
		});
	},

	sendAccessRequest: function(successFn){
		var 
			$emailAddress1 = $('[name=emailAddress1]', this.$acccess),
			$emailAddress2 = $('[name=emailAddress2]', this.$acccess),
			emailAddress1 = $.trim( $emailAddress1.val() )
			emailAddress2 = $.trim( $emailAddress2.val() )
		
		// validation
		var err = false;
		if (emailAddress1 == '' && emailAddress2 == ''){
			alert(this.msg_accessValidation1);
			$emailAddress1.focus();
			err = true;
		} else if (emailAddress1 == ''){
			alert(this.msg_accessValidation2);
			$emailAddress1.focus();
			err = true;
		} else if ( ! Utility.isValidEmail(emailAddress1) ){
			alert(this.msg_accessValidation3);
			$emailAddress1.focus();
			err = true;
		} else if (emailAddress2 == ''){
			alert(this.msg_accessValidation4);
			$emailAddress2.focus();
			err = true;
		} else if (emailAddress1 != emailAddress2){
			alert(this.msg_accessValidation5);
			$emailAddress1.focus();
			err = true;
		}
		
		if(err) return;

		this.checkUsername(emailAddress1, function(exists){
			if(exists){
				alert(Core.msg_usernameExists);
			} else {
				var url = Config.servicesUrl + "/Registration.ashx?AccessRequest&jsonp=?",
					data = {
						username:emailAddress1
					};
				
				$.getJSON(url, data, function(ok){
					if(successFn) successFn(ok);
				});
			}
		});
	},
	
	checkUsername: function(username, successFn){
		var url = Config.servicesUrl + "/Registration.ashx?UsernameExists&jsonp=?",
			data = {
				username:username
			};

		$.getJSON(url, data, function(ok){
			if(successFn) successFn(ok);
		});
	},

	sendPassword: function(successFn){
		var url = Config.servicesUrl + "/Registration.ashx?ForgotPassword&jsonp=?",
			data = {
				username:$.trim($('[name=emailAddress]', this.$forgotPassword).val())
			};

		// validation
		if (data.username == ''){
			alert(this.msg_forgotPasswordValidation1);
			Core.$forgotPassword.find('[name=emailAddress]').focus();
			return;			
		} else if ( ! Utility.isValidEmail(data.username) ){
			alert(this.msg_forgotPasswordValidation2);
			Core.$forgotPassword.find('[name=emailAddress]').focus();
			return;			
		}
		
		$.getJSON(url, data, function(ok){
			if(successFn) successFn(ok);
		});
	},
	
	login: function(){
		var 
			$emailAddress = $('[name=emailAddress]', this.$login),
			$password = $('[name=password]', this.$login),
			emailAddress = $.trim( $emailAddress.val() ),
			password = $.trim( $password.val() ),
			root = this;
		
		// validation
		var err = false;
		if (emailAddress == '' && password == ''){
			alert(this.msg_loginValidation1);
			$emailAddress.focus();
			err = true;
		} else if (emailAddress == ''){
			alert(this.msg_loginValidation2);
			$emailAddress.focus();
			err = true;
		} else if (password == ''){
			alert(this.msg_loginValidation3);
			$password.focus();
			err = true;
		}
		
		if(err) return;
		
		$('.buttonBar, .loggingIn', this.$login).toggle();
		
		Core.authenticate(emailAddress, password, function(){
			$('.buttonBar, .loggingIn', root.$login).toggle();
		});
	},
	
	authenticate: function(username, password, failFn){
		var url = Config.servicesUrl + "/Authentication.ashx?Login&jsonp=?",
			data = {
				username:username,
				password:password
			};

		$.getJSON(url, data, function(response){
			var failed = false;
			if(response.Success === true){
				if(response.Token === "REGISTER"){
					alert("Your login info was not found, please try again or signup for an account."); // TODO: do something more graceful
					failed = true;
				} else {
					$.cookie('username', username, {path:'/', domain:'irocket.com'});
					$.cookie('token', response.Token, {path:'/', domain:'irocket.com'});
				
					window.location.href = Config.appUrl;
				}
			} else { 
				alert("Incorrect username or password. Please try again."); // TODO: do something more graceful
				failed = true;
			}

			if(failed) failFn();
		});
	},
	
	/* utility stuff
	********************************************************************************** */
	
	getTemplates: function(successFn){
		if (this.templateFiles.length > 0){
			var fileName = this.templateFiles.shift(); // shrinks the queue
			var url = Core.templateRoot + '/' + fileName;
			$.get(Utility.noCache(url), function(template){
				Core.templates[ fileName.split('.')[0] ] = template;
				Core.getTemplates(successFn); // recursive call
			});
		}
		else if (successFn != undefined) successFn();
	}
}

