
LW.objects.createHandler('hasUniqId', 'usernameCheck', LW.vars.jsonPath + '/account/free.html?username=');


LW.signup = LW.signup || {
	haveDoneGreatEvil:   false,
	inBetaSignup:        false,
	phoneCheckCountries: {
		US: 1,
		CA: 1,
		GB: 44,
		IN: 91,
		AU: 61,
		NZ: 64
	},
	phoneLooksCheckable: function (number, country) {
		if (!LW.signup.phoneCheckCountries[country]) {
			return false;
		}
		number = number.replace(/\D/g, '');

		return (number.length >= 10);
	},
	gotoPage: function (index, callback) {
		$('#signup input, #signup select, #signup a').attr('tabindex', -1);
		$('#signup' + index).find('input, select, a').attr('tabindex', 0);

		var left = (index - 1) * -900;
		var dest = { left: left + 'px' };
		$('#signup .plane').animate(dest, 1300, 'swing', callback);
	},
	save: function(args) {
		if (LW.signup.haveDoneGreatEvil) {
			return;
		}

		$.postJSON(LW.vars.jsonPath + '/account/save.html', args, function (res) {
			LW.signup.haveGoneGreatEvil = true;
		});
	},
	show: function () {
		var loc = location;
		// Make sure we are in the smartserver section 
		if ( ! location.pathname.match(/^\/SmartServers\//) ) {
			location = LW.vars.sslRoot + '/SmartServers/' + '#showsignup';
			return;
		}
		if (location.protocol == 'http:') {
			location = LW.vars.sslRoot + location.pathname + '#showsignup';
			return;
		}
		// we can't use LW.DHTML.showPopup, because we aren't doing the mouse tracking stuff
		if ($.browser.msie && parseInt($.browser.version) < 7) {
			$(window).scrollTop(0);
			$('#signup .button').toggleClass("");
		}

		if (LW.signup.coupon_email) {
			$('#email').val(LW.signup.coupon_email);
			LW.signup.coupon_email = null;
		}

		$('#signup input, #signup select, #signup a').attr('tabindex', -1);
		$('#signup1 input, #signup1 select, #signup1 a').attr('tabindex', 0);
		LW.DHTML.greyOut('slow');
		$('#signup').fadeIn('slow');
	},
	hide: function () {
		var signup = $('#signup');
		LW.DHTML.unGreyOut('slow');
		signup.fadeOut('slow', function () {
			signup.find('.plane').css({ left: '0px' });
			signup.find('form').get(0).reset();
			LW.validation.removeAllHighlights(signup.find('form'));
			signup.find('.invalid').empty();
			signup.find('.enroll').fadeIn();
			signup.find('.enrolled').hide();
			signup.find('.enroll .button').show();
			signup.find('.enroll img').hide();
			$('#verify_phone_msg').show();
			$('#verify_phone_input, #verify_phone_error').hide();
		});
	},
	handleError: function (res) {
		if (!res.error_class) {
			return false;
		}

		if (res.error_class == 'LW::Exception::CCTrans::Declined') {
			var signup = $('#signup');
			signup.find('#ccerror').text(res.error);
			$('#signup .plane').animate({
				left: '-900px'
			}, 1300, 'swing', function () { });

			return true;
		} else {
			return LW.JSON.handleError(res);
		}
	},
	init: function () {
		LW.validation.doScroll = false;
		if (location.hash == '#showsignup' && location.protocol == 'https:') {
			LW.signup.show();
		}
		

		$('.signuplink').live('click', function (event) {
			event.preventDefault();
			LW.signup.show();
		});

		LW.event.watch('usernameCheck.load', function (username) {
			var res = LW.usernameCheck.find(username);

			if (!res.available) {
				LW.validation.highlight('#username', "Username '" + username + "' is already in use.");
			}
		});

		$('#username').change(function () {
			if (!LW.validation.validateInput('#username', { type: 'username' })) {
				return;
			}

			var username = $(this).val();
			if (username.length > 0) {
				LW.usernameCheck.load(username);
			}
		});
		
		$('#payment_method').change(function () {
			var value = $(this).find('option:selected').val();
			if (value == 'credit_card') {
				$('#cc_info').fadeIn(100);
			}
			else {
				$('#cc_info').fadeOut(100);
			}
		});

		$('#signup .close_greyout, .enrolled a').live('click', function (event) {
			event.preventDefault();
			LW.signup.hide();
		});

		$('#gotosignup1').click(function (event) {
			event.preventDefault();

			LW.signup.gotoPage(1);
		});

		$('.cvv2explain').click(function (event) {
			event.preventDefault();
			var howto = $('.cvv2howto');
			if (howto.is(':hidden')) {
				howto.fadeIn(500);
			} else {
				howto.fadeOut(500);
			}
		});


		$('#gotosignup2').click(function (event) {
			event.preventDefault();

			var pass = LW.validation.validateForm("#signup1", [
				{
					name:      'username',
					required:  true,
					type:      'username',
					minlength: 2,
					maxlength: 20
				},
				{
					name: 'pass1',
					required:  true,
					minlength: 6,
					maxlength: 30,
					type:      'password'
				},
				{
					name:      'pass2',
					required:  true,
					minlength: 6,
					maxlength: 30,
					equals:    'pass1',
					type:      'password'
				},
				{
					name:      'tosagree',
					required:  true,
					type:      'tosagree'
				}
			]);

			if (pass) {
				LW.signup.gotoPage(2);
			}

			return false;
		});
		$('#gotosignup3').click(function () {
			var country     = $('#signup form select[name=country] option:selected').val();
			var usrequired  = (country == 'US');
			var spec = [
				{
					name:      'fname',
					required:  true,
					minlength: 2,
					maxlength: 80,
					type:      'mailing_field'
				},
				{
					name:      'lname',
					required:  true,
					minlength: 2,
					maxlength: 120,
					type:      'mailing_field'
				},
				{
					name:      'email',
					required:  true,
					maxlength: 60,
					type:      'email'
				},
				{
					name:      'address',
					required:  true,
					minlength: 2,
					maxlength: 150,
					type:      'mailing_field'
				},
				{
					name:      'city',
					required:  true,
					minlength: 2,
					maxlength: 80,
					type:      'mailing_field'
				},
				{
					name:      'country',
					required:  true
				},
				{
					name:      'state',
					required:  usrequired,
					minlegnth: 2,
					maxlength: 80,
					type:      'mailing_field'
				},
				{
					name:      'zip',
					required:  usrequired,
					minlength: 2,
					maxlength: 40,
					type:      'mailing_field'
				},
				{
					name:      'phone',
					required:  true,
					minlength: 2,
					maxlength: 25,
					type:      'phone'
				},
				{
					name:      'payment_method',
					required:  true
				}
			];
			
			if ($('#payment_method option:selected').val() == 'credit_card') {
				spec.push(
					{
						name:      'ccnum',
						required:  true,
						type:      'cc'
					},
					{
						name:      'cvv2',
						required:  true,
						type:      'integer'
					},
					{
						name:      'cctype',
						required:  true
					},
					{
						name:      'ccmon',
						type:      'ccmon',
						required:  true
					},
					{
						name:      'ccyear',
						type:      'ccyear',
						required:  true
					}
				);
			}
			
			var pass = LW.validation.validateForm("#signup2", spec);

			if (pass) {
				var form = $('#signup form').get(0);
				if (LW.signup.phoneLooksCheckable(form.phone.value, country)) {
					$('#signup span.phonenum').text(form.phone.value);
					LW.signup.save({
						name:    form.fname.value + ' ' + form.lname.value,
						email:   form.email.value,
						address: form.address.value,
						city:    form.city.value,
						country: form.country.value,
						state:   form.state.value,
						zip:     form.zip.value,
						phone:   form.phone.value
					});
					LW.signup.gotoPage(3);
				}
				else {
					$('.createaccount').eq(0).click();
				}
			}
		});
		$('.createaccount').click(function (event) {
			event.preventDefault();

			LW.signup.gotoPage(4, function () {
				var form = $('#signup form').get(0);
				var vars = {
					username:       form.username.value,
					pass1:          form.pass1.value,
					fname:          form.fname.value,
					lname:          form.lname.value,
					tax_id:         form.tax_id.value,
					address:        form.address.value,
					email:          form.email.value,
					city:           form.city.value,
					country:        form.country.value,
					phone:          form.phone.value,
					ccnum:          form.ccnum.value,
					ccmon:          form.ccmon.value,
					ccyear:         form.ccyear.value,
					state:          form.state.value,
					zip:            form.zip.value,
					cvv2:           form.cvv2.value,
					payment_method: form.payment_method.value,
					phone_code:     form.phone_code.value,
					phone_check:    form.phone_check.value,
					rid:            $.cookie('RID')
				};

				if (LW.signup.inBetaSignup) {
					vars.betasignup = LW.signup.signupkey;
				}

				if (LW.signup.coupon_code) {
					vars.coupon = LW.signup.coupon_code;
				}

				$.postJSON(LW.vars.jsonPath + '/account/create.html', vars, function (res) {
					if (LW.signup.handleError(res)) {
						return;
					}

					LW.campaign.deleteCouponCookie();
					LW.campaign.hideCouponTag();
					
					if (parseInt(res.active) != 0) {
						var login = $('#loginform');
						login.find('input[name=login_username]').val(vars.username);
						login.find('input[name=login_password]').val(vars.pass1);
						login.find('input[name=login_redirect]').val(LW.vars.managePath + '/welcome.html');
						login.submit();
					}
					else {
						LW.signup.gotoPage(5);
					}
				});
			});

			return false;
		});

		$('#backto2').click(function (event) {
			LW.signup.gotoPage(2);
		});

		$('#do_verify_phone').click(function (event) {
			$(this).unbind('click');
			var country = $('#signup form select[name=country] option:selected').val();

			var vars = {
				phone:       $('#signup input[name=phone]').val(),
				countrycode: LW.signup.phoneCheckCountries[country]
			};

			$('#verify_phone_msg').fadeOut();
			$.postJSON(LW.vars.jsonPath + '/verify/phone.html', vars, function (res) {
				if (res.error_class) {
					$('#verify_phone_error').fadeIn();
				}
				else {
					$('#signup input[name=phone_check]').val(res.id);
					$('#verify_phone_input').fadeIn();
				}
			});
		});

		$('#beta_info_signup form').submit(function (event) {
			event.preventDefault();

			var pass = LW.validation.validateForm("#beta_info_signup form", [
				{
					name:      'email',
					required:  true,
					maxlength: 60,
					type:      'email'
				}
			]);

			if (!pass) {
				return;
			}

			var args = {
				email: this.email.value
			};

			var form = $(this);

			form.find('.button').hide();
			form.find('img').show();
			$.postJSON(LW.vars.jsonPath + '/account/beta_enroll.html', args, function (res) {
				if (res.error_class) {
					form.find('.button').show();
					form.find('img').hide();

					if (res.error_class == 'LW::Exception::DuplicateRecord') {
						LW.validation.highlight('#email', 'This email address is already enrolled.');
					}
					else {
						LW.JSON.handleError(res);
					}
					return;
				}

				$('#beta_info_signup .enroll').fadeOut('slow', function () {
					$('#beta_info_signup .enrolled').fadeIn('slow');
				});
			});
		});
		$('#beta_info_signup form .button').click(function(event) {
			event.preventDefault();
			$('#beta_info_signup form').submit();
		});

	}
};

LW.event.watch('campaign.loaded', LW.signup.init);

$(function () {
	LW.DHTML.buildButton('.button');
	LW.DHTML.setButtonHover('.button');
	LW.event.fire('user.loggedIn');
});

