aboutsummaryrefslogtreecommitdiff
path: root/website/resources/js/order-license.js
blob: 82627f2b306afb12c706ab839c378b336ec7ca5c (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
90
91
92
93
94
95
96
97
98
99
100
101
102
"use strict";

(function() {
	var imgDataUrl = null;
	function applyLicense() {
		$("#submit").on("click", function(evt) {
			evt.preventDefault();
			
			var onSuccess = function() {
				alert("Form submitted!");
			};
			
			var onFailure = function() {
				alert("Whoops");
			};
			
			var data = {};
			data.name = $("#name").val();
			var rnd = generateRandom();
			var err = processImageUpload();
			if (err) {
				alert(err);
				$("#logo")[0].value = null;
				return;
			}
			if (imgDataUrl) data.logo = imgDataUrl;
			$.ajax({
				url: "/license-submit/" + rnd,
				method: "PUT",
				contentType: "application/json",
				data: JSON.stringify(data),
				processData: false,
				success: onSuccess,
				failure: onFailure
			});
		});
		
		$("#companyLogo").on("click", function(evt) {
			evt.preventDefault();
			$("#logo").click();
		});
		
		$("#deleteCompanyLogo").on("click", function(evt) {
			evt.preventDefault();
			$("#logo")[0].value = null;
			$("#logoCnt").empty().hide();
			$("#companyLogo").show();
			$("#deleteCompanyLogo").hide();
		});
		
		$("#logo").on("change", function() {
			var err = showImage();
			if (err) {
				alert(err);
				$("#logo")[0].value = null;
			} else {
				$("#companyLogo").hide();
				$("#deleteCompanyLogo").show();
			}
		});
	}
	
	function generateRandom() {
		var buf = new Uint8Array(40);
		window.crypto.getRandomValues(buf);
		return btoa(String.fromCharCode.apply(null, buf)).replace(/\+/g, '_').replace(/\//gi, '-');
	}
	
	function showImage() {
		$("#logoCnt").empty().hide();
		try {
			return processImageUpload(function(dataUrl) {
				var img = $("<img />");
				img.css({
					"max-width": "500px",
					"max-height": "300px"
				});
				$("#logoCnt").append(img).show();
				img.attr("src", dataUrl);
			});
		} catch (e) {
			if (console && console.log) console.log(e);
		}
	}
	
	function processImageUpload(fnc) {
		var f = $("#logo")[0].files[0];
		if (!f) return;
		if (f.size > 10000000) return "Logo too large; please give us a logo below 10MiB in size.";
		var imageType = /^image\//;
		if (!imageType.test(f.type)) return "Please upload an image, for example in PNG format.";
		var reader = new FileReader();
		reader.onload = function(e) {
			imgDataUrl = e.target.result;
			if (fnc) fnc(e.target.result);
		};
		reader.readAsDataURL(f);
		return null;
	}
	
	$(applyLicense);
})();