var Home = {
	templateRoot: 'templates',
	//templateFiles:['register.html', 'resetPassword.html'],
	templateFiles:['confirm.html', 'resetPassword.html'],
	templates:{},

	//$register: null,
	$confirm: null,
	$resetPassword: null,
	
	resetToken: null,
	accessToken: null,
	
	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_resetPasswordValidation5: "Please use a password at least 6 letters/numbers long",
	
	/*
	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",
	*/

	msg_confirmationValidation1: "Please fill out all fields",
	msg_confirmationValidation2: "Please enter your first name",
	msg_confirmationValidation3: "Please enter your last name",
	msg_confirmationValidation4: "Please enter your email address",
	msg_confirmationValidation5: "Please enter a valid email address",
	msg_confirmationValidation6: "Please enter your desired password two times",
	msg_confirmationValidation7: "Please enter your password",
	msg_confirmationValidation8: "Please re-enter your password",
	msg_confirmationValidation9: "Please enter matching passwords",
	msg_confirmationValidation10: "Please use a password at least 6 letters/numbers long",
	
	msg_confirmationError1: "Unable to start your free trial: some required information is missing. Please fill in all fields on the form.",
	msg_confirmationError2: "Unable to start your free trial: the email address you entered does not match the one used for your access request. Please use the email address you used for your access request.",
	msg_confirmationError3: "Unable to start your free trial: your email address is already registered. Click the Cancel button on the registration form, then login using the login button.",
	msg_confirmationError4: "Unable to start your free trial: an error has occurred while saving your information. Please try again. If the problem continues, please contact us for assistance.",
	msg_confirmationErrorUnexpected: "Unable to start your free trial: an unexpected error has occurred. Please try again. If the problem continues, please contact us for assistance.",
	
	sliderOpts: {distance:940, shift:940, slide:0},

	init: function(){
		//this.$register = $('#register');
		this.$confirm = $('#confirm');
		this.$resetPassword = $('#resetPassword');
		this.$badUrl = $('#badUrl');

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

			/*
			if(Home.accessToken != null) {
				Home.loadRegister(function(){ // show the registration form if the url had an access token
					Home.$register.jqmShow();
				});
			}
			*/
			
			if(Home.accessToken != null) {
				Home.loadConfirm(function(){ // show the confirmation form if the url had an access token
					Home.$confirm.jqmShow();
				});
			}
		});
	},

	bindControls: function(){
		//this.$register.jqm();
		this.$confirm.jqm();
		this.$resetPassword.jqm();
		this.$badUrl.jqm();
		
		//$.validator.setDefaults({
		//	success: "valid"
		//});
		//$.validator.messages.creditcard2 = "invalid";
		
		$('.slide a').click(function(){
			if(Home.sliderOpts.slide == 4){
				return true;
			}
			/*
			if(slide == 4){
				shift=distance;
				slide=0;
				alert('poo');
				//$('#slides .slide').eq(slide)
			}
			*/
			
			var $this = $(this),
				$slide = $('#slides .slide').eq(Home.sliderOpts.slide), //$this.closest('.slide'),
				$h2 = $slide.find('h2'),
				$p = $slide.find('p'),
				$screen = $slide.find('.screen'),
				$a = $slide.find('a');
	
			/*
			if($this.is('.register')){ // TODO A: set register link to register page
				return false;
			}
			*/
			
			//$p.animate( {left:100}, {duration:4000, easing:'easeOutElastic'});
			$h2.animate( {left:25}, {duration:'fast'})
				.animate( {left:-500}, {duration:200});
	
			$p.animate( {left:75}, {duration:'fast'})
				.animate( {left:-500}, {duration:200});
	
			$a.animate( {left:75}, {duration:'fast'})
				.animate( {left:-500}, {duration:200});
	
			$screen.animate( {left:100}, {duration:'fast'})
				.animate( {left:-1000}, 200, function(){
					Home.sliderOpts.slide++;
	
					var $slide = $('#slides .slide').eq(Home.sliderOpts.slide),
						$h2 = $slide.find('h2'),
						$p = $slide.find('p'),
						$screen = $slide.find('.screen'),
						$a = $slide.find('a');
					
					$slide.animate({left:-Home.sliderOpts.shift}, {duration:600, easing:'easeOutBounce'});
					//$h2.animate( {left:-shift}, {duration:600, easing:'easeOutBounce'} );
					//$p.animate( {left:-shift}, {duration:630, easing:'easeOutBounce'} );
					//$screen.animate( {left:-shift}, {duration:660, easing:'easeOutBounce'} );
					//$a.animate( {left:-shift}, {duration:690, easing:'easeOutBounce'} );
					
					Home.sliderOpts.shift += Home.sliderOpts.distance;
					//$('#slides').animate({left:'-=940'}, {duration:'fast'});
					//$('#slides').css('left',-940);
				});
			
			return false;
		});
	},
		
	/*
	loadRegister: function(successFn){
		Home.$register.html( this.templates['register'] );
		
		$('[name=firstName], [name=lastName], [name=emailAddress], [name=password], [name=password2]', Home.$register).qtip(Home.qtipOpts);
	
		$('#btnRegister', Home.$register).click(function(){ Home.register(); return false; });
	
		$('#btnRegisterCancel', Home.$register).click(function(){
			$('#register').jqmHide();
			return false;
		});

		$('#registrationForm', Home.$register).validate({
			rules: {
				cardNumber: {
					creditcard2: function(){ return $('[name=cardType]').val(); }
				}
			}
		});
		
		$('[name=cardType]', Home.$register).change(function(){
			console.log('in here');
			$('#registrationForm', Home.$register).validate().element('[name=cardNumber]');
		});
		
		if(successFn) successFn();
	},
	*/
	
	loadConfirm: function(successFn){
		Home.$confirm.html( this.templates['confirm'] );
		
		$('[name=firstName], [name=lastName], [name=emailAddress], [name=password], [name=password2]', Home.$confirm).qtip(Core.qtipOpts);
	
		$('#btnConfirm', Home.$confirm).click(function(){
			Home.confirm();
			return false;
		});
	
		$('#btnConfirmCancel', Home.$confirm).click(function(){
			$('#confirm').jqmHide();
			return false;
		});

		if(successFn) successFn();
	},

	loadBadUrl: function(successFn){
		$('a.ok', this.$badUrl).click(function(){
			Home.$badUrl.jqmHide();
			return false;
		});
		
		if(successFn) successFn();
	},
	
	loadResetPassword: function(successFn){
		Home.$resetPassword.html( this.templates['resetPassword'] );
		
		$('[name=password], [name=password2]', Home.$resetPassword).qtip(Core.qtipOpts);

		// delegates
		//
		Home.$resetPassword.click(function(e){
			var $target = $(e.target);
			
			if($target.is('a.send')){
				Home.resetPassword(function(sent){
					if(sent){
						Home.$resetPassword.find('form').hide().end().find('.message.success').show();
					} else {
						var $msg = Home.$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')){
				Home.$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;
		} else if (password1.length < 6){
			alert(this.msg_resetPasswordValidation5);
			err = true;
		}

		if(err) return;
		
		var url = Config.servicesUrl + "/Registration.ashx?ResetPassword&jsonp=?",
			data = {
				token: Home.resetToken,
				password: password1 
			};

		$.getJSON(url, data, function(response){
			if(successFn) successFn(response);
		});
 	},

	validateToken: function(successFn){
		var url = Config.servicesUrl + "/Registration.ashx?ValidToken&jsonp=?",
			data = {
				token: Home.resetToken
			};

		$.getJSON(url, data, function(response){
			if(successFn) successFn(response);
		});
	},
	
	/*
	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 + "/Registration.ashx?Register&jsonp=?",
			data = {
				username:emailAddress, 
				password:password1,
				accessToken:escape(Home.accessToken),
				metaDataKeys:['FirstName','LastName','EmailAddress'], 
				metaDataValues:[
					firstName,
					lastName,
					emailAddress					
				]
			};

		$('.buttonBar, .signingUp', this.$register).toggle();

		$.getJSON(url, data, function(response){
			$('.buttonBar, .signingUp', this.$register).toggle();

			if(response.Success === true){
				Core.authenticate(emailAddress, password1);
			} else { 
				alert('failure: ' + response.Messages.join('.')); // TODO: make this a nice message	
			}
		});
	},
	*/

	confirm: function(){
		var 
			$firstName = $('[name=firstName]', this.$confirm),
			$lastName = $('[name=lastName]', this.$confirm),
			$emailAddress = $('[name=emailAddress]', this.$confirm),
			$password1 = $('[name=password]', this.$confirm),
			$password2 = $('[name=password2]', this.$confirm),
			firstName = $.trim( $firstName.val() ),
			lastName = $.trim( $lastName.val() ),
			emailAddress = $.trim( $emailAddress.val() ),
			password1 = $.trim( $password1.val() ),
			password2 = $.trim( $password2.val() ),
			emailOptIn = $('[name=optIn]', this.$confirm)[0].checked;
		
		var err = false;
		if (firstName == '' && lastName == '' && emailAddress == '' && password1 == '' && password2 == ''){
			alert(this.msg_confirmationValidation1);
			$firstName.focus();
			err = true;
		} else if (firstName == ''){
			alert(this.msg_confirmationValidation2);
			$firstName.focus();
			err = true;
		} else if (lastName == ''){
			alert(this.msg_confirmationValidation3);
			$lastName.focus();
			err = true;
		} else if (emailAddress == ''){
			alert(this.msg_confirmationValidation4);
			$emailAddress.focus();
			err = true;
		} else if (! Utility.isValidEmail(emailAddress)){
			alert(this.msg_confirmationValidation5);
			$emailAddress.focus();
			err = true;
		} else if (password1 == '' && password2 == ''){
			alert(this.msg_confirmationValidation6);
			$password1.focus();
			err = true;
		} else if (password1 == ''){
			alert(this.msg_confirmationValidation7);
			$password1.focus();
			err = true;
		} else if (password2 == ''){
			alert(this.msg_confirmationValidation8);
			$password2.focus();
			err = true;
		} else if (password1 != password2){
			alert(this.msg_confirmationValidation9);
			err = true;
		} else if (password1.length < 6){
			alert(this.msg_confirmationValidation10);
			err = true;
		}
		
		if(err) return;

        var url = Config.servicesUrl + "/Registration.ashx?RegisterFree&jsonp=?",
            data = {
	            accessToken:escape(Home.accessToken),
                username:emailAddress,
                password:password1,
                firstName:firstName,
                lastName:lastName,
                emailAddress:emailAddress,
                timeZoneId:1, // hardcoded to PST
                emailOptIn:emailOptIn
            };

		$('.buttonBar, .signingUp', this.$register).toggle();

        $.getJSON(url, data, function(errorCode){
            if(errorCode == 0){
                Core.authenticate(emailAddress, password1);
            } else {
                //alert('failure: ' + errorCode); // TODO A: make this a nice message
                if(errorCode == -1) alert(Home.msg_confirmationError1);
                else if(errorCode == -2) alert(Home.msg_confirmationError2);
                else if(errorCode == -3) alert(Home.msg_confirmationError3);
                else if(errorCode == -4) alert(Home.msg_confirmationError4);
				else alert(Home.msg_confirmationErrorUnexpected);

				$('.buttonBar, .signingUp', this.$register).toggle();
            }
        });

	},
		
	/* utility stuff
	********************************************************************************** */
	
	getTemplates: function(successFn){
		if (this.templateFiles.length > 0){
			var fileName = this.templateFiles.shift(); // shrinks the queue
			var url = Home.templateRoot + '/' + fileName;
			$.get(Utility.noCache(url), function(template){
				Home.templates[ fileName.split('.')[0] ] = template;
				Home.getTemplates(successFn); // recursive call
			});
		}
		else if (successFn != undefined) successFn();
	}
}

