summaryrefslogtreecommitdiff
path: root/public/assets/javascripts/rectangles/util/measurement.js
blob: d6a0b35ba5fa48f0c6cfd21b62c90384ceb80740 (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
$.fn.resetUnitVal = function(){
	this.each(function(){
		var n = $(this).data("px")
		$(this).unitVal(n)
	});
}

$.fn.unitVal = function(n){
	var s
	if (typeof n === "undefined") {
		s = $(this).val()
		n = stringToMeasurement( s )
		if (! n || isNaN(n)) {
			n = $(this).data("px")
		}
	}
	s = measurementToString( n )
	$(this).val( s ).data("px", n)
	return n
}

function measurementToString( n ) {
	var s, ft, inch
	switch (app.units) {
		case 'm':
			s = round(n/36 * 0.3048 * 100) / 100 + " m"
			break
		case 'ft':
			ft = floor(n / 36)
			inch = abs(round((n % 36) / 3))
			s = ft + "'"
			if (inch > 0) {
				s += " " + inch + '"'
			}
			break
		case 'px':
		default:
			s = round(n) + " px"
			break
	}
	return s
}
function stringToMeasurement( s ) {
	var ft, inch, ft_in, type
	if (! s.match(/[0-9]/)) {
		return NaN
	}
	if (s.indexOf("'") !== -1 || s.indexOf('"') !== -1 || s.indexOf('ft') !== -1) {
		ft_in = s.match(/[0-9.]+/g)
		if (ft_in.length >= 2) {
			ft = parseFloat( ft_in[0] )
			inch = parseFloat( ft_in[1] )
		}
		else if (ft_in.length == 1) {
			if (s.indexOf('"') !== -1) {
				ft = 0
				inch = parseFloat( ft_in[0] )
			}
			else {
				ft = parseFloat( ft_in[0] )
				inch = 0
			}
		}
		else {
			ft = inch = 0
		}
		n = ft * 36 + inch * 3
	}
	else if (s.indexOf("m") !== -1) {
		n = parseFloat(s.match(/[0-9.]+/)) * 36 / 0.3048
	}
	else if (s.indexOf("px") !== -1) {
		n = parseFloat(s.match(/[0-9.]+/))
	}
	else {
		n = abs( stringToMeasurement( s + app.units ) )
	}
	if (s.indexOf('-') !== -1) {
		n *= -1
	}
	return n
}