summaryrefslogtreecommitdiff
path: root/public/assets/javascripts/ui/SignUpModal.js
blob: 160323ba31ef7c31065761a1f9d50c9bd255fb2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var SignUpModal = ModalView.extend({
	el: ".mediaDrawer.signup",
	action: "/auth/signup",
	
	events: {
		"submit form": "submit",
	},
	
	initialize: function(){
		this.$form = this.$("form")
		this.$errors = this.$(".errors")
		this.$errorList = this.$(".errorList")
	},

	reset: function(){
		this.$("input").not("[type='submit']").not("[type='hidden']").val("")
	},
	
	load: function(){
		this.reset()
		this.show()
	},
	
	validate: function(){
		var errors = []

		var username = this.$("#usernameInput").val()
		var email = this.$("#emailInput").val()		
		var pw1 = this.$("#passwordInput1").val()
		var pw2 = this.$("#passwordInput2").val()

		if (! username.length) {
			errors.push("Please enter a username");
		}
		if (! pw1.length) {
			errors.push("Please enter a password");
		}
		if (! email.length) {
			errors.push("Please enter an email address");
		}
		else if (email.indexOf("@") === -1) {
			errors.push("Please enter a valid email address");
		}
		if (pw1 !== pw2) {
			errors.push("Passwords don't match");
		}

		if (errors.length) {
			this.$errors.show();
			for (var i in errors) {
				this.$errorList.append('<div>' + errors[i] + '</div>');
			}
		}

		return ! errors.length
	},

	submit: function(e){
		e.preventDefault()

		this.$errors.hide();
		this.$errorList.empty()

		if (! this.validate()) return
		
		var fields = this.$form.serializeArray()
		fields.forEach(function(pair){
			if (pair.name == "password" && pair.value.length > 0) {
				pair.value = SHA1.hex('lol$' + pair.value + '$vvalls')
			}
		})
		var request = $.post(this.action, $.param(fields));
		request.done($.proxy(function (response) {
			if (response.error) {
				this.$errors.show();
				for (var key in response.error.errors) {
					this.$errorList.append('<div>' + response.error.errors[key].message + '</div>');
				}
				return;
			}
			else {
				window.location.href = "/profile"
			}
		}, this));
	}

})