// TODO: add some password requirements
// TODO: confirm registrations (right now they go right to member area)

var AttIQ = {
	templateRoot: '/templates',
	templateFiles:['login.html', 'register.html', 'forgotPassword.html', 'resetPassword.html'],
	templates:{},

	$register: null,
	$login: null,
	$forgotPassword: null,
	$resetPassword: null,
	
	resetToken: null,
	
	qtipOpts: null,
	//templateCount:2,
	
	msg_forgotPasswordValidation: "Please enter your email address",
	
	msg_resetPasswordValidation1: "Please enter your new password twice",
	msg_resetPasswordValidation2: "Please enter your new password",
	msg_resetPasswordValidation3: "Please enter your new password again",
	msg_resetPasswordValidation4: "Please make sure your new password entries match each other",
	
	msg_loginValidation1: "Please enter your email address and password",
	msg_loginValidation2: "Please enter your email address",
	msg_loginValidation3: "Please enter your password",

	msg_registrationValidation1: "Please fill out all fields",
	msg_registrationValidation2: "Please enter your first name",
	msg_registrationValidation3: "Please enter your last name",
	msg_registrationValidation4: "Please enter your email address",
	msg_registrationValidation5: "Please enter your desired password two times",
	msg_registrationValidation6: "Please enter your password",
	msg_registrationValidation7: "Please re-enter your password",
	msg_registrationValidation8: "Please enter matching passwords",
	
	init: function(successFn){
		this.$register = $('#register');
		this.$login = $('#login');
		this.$forgotPassword = $('#forgotPassword');
		this.$resetPassword = $('#resetPassword');
		this.$badUrl = $('#badUrl');

		var resetToken = $.url.param('rs');
		if(resetToken) this.resetToken = resetToken;
		
		this.setDefaults();
		this.bindControls();
		this.getTemplates(function(){
			if(AttIQ.resetToken != null) {
				AttIQ.validateToken(function(ok){
					if(ok){
						AttIQ.loadResetPassword(function(){ // we want to show the reset password form if the url had a token
							AttIQ.$resetPassword.jqmShow();
						});
					} else {
						AttIQ.loadBadUrl(function(){
							AttIQ.$badUrl.jqmShow();
						});
					}
				});
			}
			AttIQ.loadRegister();
			AttIQ.loadLogin();
			AttIQ.loadForgotPassword();
		});
		if (successFn) successFn();
	},

	bindControls: function(){
		this.$register.jqm({trigger: '#registerLink'});
		this.$login.jqm({trigger: '#loginLink'});
		this.$forgotPassword.jqm();
		this.$resetPassword.jqm();
		this.$badUrl.jqm();
	},
		
	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;
	},
	
	loadRegister: function(){
		AttIQ.$register.html( TrimPath.parseTemplate( this.templates['register'] ).process() );
		
		$('[name=firstName], [name=lastName], [name=emailAddress], [name=password], [name=password2]', AttIQ.$register).qtip(AttIQ.qtipOpts);

		$('#btnRegister', AttIQ.$register).click(function(){ AttIQ.register(); return false; });
		$('#btnRegisterCancel', AttIQ.$register).click(function(){
			$('#register').jqmHide();
			return false;
		});
	},
	
	loadBadUrl: function(successFn){
		$('a.ok', this.$badUrl).click(function(){
			AttIQ.$badUrl.jqmHide();
			return false;
		});
		
		if(successFn) successFn();
	},
	
	loadLogin: function(){
		AttIQ.$login.html( TrimPath.parseTemplate( this.templates['login'] ).process() );
		
		$('[name=emailAddress], [name=password]', AttIQ.$login).qtip(AttIQ.qtipOpts);

		$('#btnLogin', AttIQ.$login).click(function(){ AttIQ.login(); return false; });

		// enter key for password field clicks login button
		$('[name=password]', AttIQ.$login).keypress(function(e){
			if(e.which == 13){
				$('#btnLogin', AttIQ.$login).click();
			}
		});

		$('#btnLoginCancel', AttIQ.$login).click(function(){
			$('#login').jqmHide();
			$('[name=emailAddress], [name=password]', AttIQ.$login).each(function(){ $(this).val(''); });
			return false;
		});

		$('#btnForgotPassword', AttIQ.$login).click(function(){
			// prepare the forgot password view
			AttIQ.$forgotPassword
				.find('.message').hide().end()
				.find('[name=emailAddress]').val('').end()
				.find('form').show();
			
			$('#login').jqmHide();
			$('#forgotPassword').jqmShow(); 
			return false;
		});
	},

	loadForgotPassword: function(){
		AttIQ.$forgotPassword.html( TrimPath.parseTemplate( this.templates['forgotPassword'] ).process() );
		
		$('[name=emailAddress]', AttIQ.$forgotPassword).qtip(AttIQ.qtipOpts);

		// delegates
		//
		AttIQ.$forgotPassword.click(function(e){
			var $target = $(e.target);
			
			if($target.is('a.send')){
				/*
				var $spinner = AttIQ.$forgotPassword.find('.spinner');
				
				AttIQ.$forgotPassword
					.find('a.cancel').hide().end()
					.find('a.send').html('Sending...').after( $spinner ).show();
				*/
				
				AttIQ.sendPassword(function(sent){
					if(sent){
						AttIQ.$forgotPassword.find('form').hide().end().find('.message.success').show();
					} else {
						var $msg = AttIQ.$forgotPassword.find('.message.failure');
						$msg.show();
						setTimeout(function(){ $msg.fadeOut("slow").hide(); }, 4000);
					}
				});
				
				return false;
			}
			
			if($target.is('a.cancel') || $target.is('a.ok')){
				AttIQ.$forgotPassword.jqmHide();
									
				return false;
			}
		});
	},

	loadResetPassword: function(successFn){
		AttIQ.$resetPassword.html( TrimPath.parseTemplate( this.templates['resetPassword'] ).process() );
		
		$('[name=password], [name=password2]', AttIQ.$resetPassword).qtip(AttIQ.qtipOpts);

		// delegates
		//
		AttIQ.$resetPassword.click(function(e){
			var $target = $(e.target);
			
			if($target.is('a.send')){
				AttIQ.resetPassword(function(sent){
					if(sent){
						AttIQ.$resetPassword.find('form').hide().end().find('.message.success').show();
					} else {
						var $msg = AttIQ.$resetPassword.find('.message.failure'); // should never happen
						$msg.show();
						setTimeout(function(){ $msg.fadeOut("slow").hide(); }, 4000);
					}
				});
				
				return false;
			}
			
			if($target.is('a.cancel') || $target.is('a.ok')){
				AttIQ.$resetPassword.jqmHide();
									
				return false;
			}
		});
		
		if(successFn) successFn();
	},

	resetPassword: function(successFn){
		var $password1 = $('[name=password]', this.$resetPassword),
			$password2 = $('[name=password2]', this.$resetPassword),
			password1 = $.trim( $password1.val() ),
			password2 = $.trim( $password2.val() );
			
		// validation
		var err = false;
		if (password1 == '' && password2 == ''){
			alert(this.msg_resetPasswordValidation1);
			$password1.focus();
			err = true;
		} else if (password1 == ''){
			alert(this.msg_resetPasswordValidation2);
			$password1.focus();
			err = true;
		} else if (password2 == ''){
			alert(this.msg_resetPasswordValidation3);
			$password2.focus();
			err = true;
		} else if (password1 != password2){
			alert(this.msg_resetPasswordValidation4);
			err = true;
		}

		if(err) return;
		
		var url = Config.servicesUrl + "/v1_1/RegistrationService.ashx?ResetPassword&jsonp=?",
			data = {
				token: AttIQ.resetToken,
				password: password1 
			};
			
		$.ajax({
			type: "GET",
			url: url,
			data: data,
			cache: false,
			success: function(response){
				if(successFn) successFn( (response.toLowerCase() == 'true') );
			},
			error: function (req, textStatus, errorThrown) {
				//        ...
			}
		});
 	},

	sendPassword: function(successFn){
		var url = Config.servicesUrl + "/v1_1/RegistrationService.ashx?ForgotPassword&jsonp=?",
			data = {
				username:$.trim($('[name=emailAddress]', this.$forgotPassword).val())
			};

		// validation
		if (data.username == ''){
			alert(this.msg_forgotPasswordValidation);
			AttIQ.$forgotPassword.find('[name=emailAddress]').focus();
			return;			
		}
			
		$.ajax({
			type: "GET",
			url: url,
			data: data,
			cache: false,
			success: function(response){
				if(successFn) successFn( (response.toLowerCase() == 'true') );
			},
			error: function (req, textStatus, errorThrown) {
				//        ...
			}
		});
	},
	
	validateToken: function(successFn){
		var url = Config.servicesUrl + "/v1_1/RegistrationService.ashx?ValidToken&jsonp=?",
			data = {
				token: AttIQ.resetToken
			};

		$.ajax({
			type: "GET",
			url: url,
			data: data,
			cache: false,
			success: function(response){
				if(successFn) successFn( (response.toLowerCase() == 'true') );
			},
			error: function (req, textStatus, errorThrown) {
				//        ...
			}
		});
	},

	register: function(){
		var 
			$firstName = $('[name=firstName]', this.$register),
			$lastName = $('[name=lastName]', this.$register),
			$emailAddress = $('[name=emailAddress]', this.$register),
			$password1 = $('[name=password]', this.$register),
			$password2 = $('[name=password2]', this.$register),
			firstName = $.trim( $firstName.val() ),
			lastName = $.trim( $lastName.val() ),
			emailAddress = $.trim( $emailAddress.val() ),
			password1 = $.trim( $password1.val() ),
			password2 = $.trim( $password2.val() );
		
		var err = false;
		if (firstName == '' && lastName == '' && emailAddress == '' && password1 == '' && password2 == ''){
			alert(this.msg_registrationValidation1);
			$firstName.focus();
			err = true;
		} else if (firstName == ''){
			alert(this.msg_registrationValidation2);
			$firstName.focus();
			err = true;
		} else if (lastName == ''){
			alert(this.msg_registrationValidation3);
			$lastName.focus();
			err = true;
		} else if (emailAddress == ''){
			alert(this.msg_registrationValidation4);
			$emailAddress.focus();
			err = true;
		} else if (password1 == '' && password2 == ''){
			alert(this.msg_registrationValidation5);
			$password1.focus();
			err = true;
		} else if (password1 == ''){
			alert(this.msg_registrationValidation6);
			$password1.focus();
			err = true;
		} else if (password2 == ''){
			alert(this.msg_registrationValidation7);
			$password2.focus();
			err = true;
		} else if (password1 != password2){
			alert(this.msg_registrationValidation8);
			err = true;
		}
		
		if(err) return;
					
		var url = Config.servicesUrl + "/v1_1/RegistrationService.ashx?Register&jsonp=?",
			data = {
				username:emailAddress, 
				password:password1, 
				metaDataKeys:['FirstName','LastName','EmailAddress'], 
				metaDataValues:[
					firstName,
					lastName,
					emailAddress
				]
			};

		$.ajax({
			type: "GET",
			url: url,
			data: data,
			dataType: 'jsonp',
			cache: false,
			success: function(response){
				if(response.Success === true){
					AttIQ.authenticate(emailAddress, password1);
				} else { 
					alert('failure: ' + response.Messages.join('.')); // TODO: make this a nice message	
				}
			},
			error: function (req, textStatus, errorThrown) {
				//        ...
			}
		});
	},
	
	login: function(){
		var 
			$emailAddress = $('[name=emailAddress]', this.$login),
			$password = $('[name=password]', this.$login),
			emailAddress = $.trim( $emailAddress.val() ),
			password = $.trim( $password.val() );
		
		// 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;
		
		AttIQ.authenticate(emailAddress, password);
	},
	
	authenticate: function(username, password){
		var url = Config.servicesUrl + "/v1_1/AuthenticationService.ashx?Login&jsonp=?",
			data = {
				username:username,
				password:password
			};
		
		$.ajax({
			type: "GET",
			url: url,
			data: data,
			dataType: 'jsonp',
			cache: false,
			success: function(response){
				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
					} else {
						$.cookie('username', username, {path:'/'});
						$.cookie('token', response.Token, {path:'/'});
					
						window.location.href = 'members/';
					}
				} else { 
					alert("Incorrect username or password. Please try again."); // TODO: do something more graceful	
				}
			},
			error: function (req, textStatus, errorThrown) {
				//        ...
			}
		});
	},
	
	/* utility stuff
	********************************************************************************** */
	
	getTemplates: function(successFn){
		if (this.templateFiles.length > 0){
			var fileName = this.templateFiles.shift(); // shrinks the queue
			var url = AttIQ.templateRoot + '/' + fileName;
			$.get(Utility.noCache(url), function(template){
				AttIQ.templates[ fileName.split('.')[0] ] = template;
				AttIQ.getTemplates(successFn); // recursive call
			});
		}
		else if (successFn != undefined) successFn();
	}
}
