summaryrefslogtreecommitdiff
path: root/StoneIsland/www/js/vendor/util.js
blob: 6523d50e32d11050c37052409c50d034473c8489 (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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
if (window.$) {
  $.fn.int = function() { return parseInt($(this).val(),10) }
  $.fn.float = function() { return parseFloat($(this).val()) }
  $.fn.string = function() { return trim($(this).val()) }
  $.fn.enable = function() { return $(this).attr("disabled",null) }
  $.fn.disable = function() { return $(this).attr("disabled","disabled") }
  $.fn.sanitize = function(s) { return trim(sanitize($(this).val())) }
  $.fn.stripHTML = function(s) { return trim(stripHTML($(this).val())) }
  $.fn.sanitizeName = function(s) { return trim(sanitizeName($(this).val())) }
  $.fn.htmlSafe = function(s) { return $(this).html(sanitize(s)) }
  $.fn.toDollars = function(i) { return $(this).html((i/100).toFixed(2)) }
}

function trim (s){ return s.replace(/^\s+/,"").replace(/\s+$/,"") }
function sanitize (s){ return (s || "").replace(new RegExp("[<>&]", 'g'), "") }
function sanitizeName (s){ return (s || "").replace(new RegExp("[^-_a-zA-Z0-9]", 'g'), "") }
function stripHTML (s){ return (s || "").replace(/<[^>]+>/g, "") }
function sanitizeHTML (s){ return (s || "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;") }
function capitalize (s){ return s.split(" ").map(capitalizeWord).join(" ") }
function capitalizeWord (s){ return s.charAt(0).toUpperCase() + s.slice(1) }
function slugify (s){ return (s || "").toLowerCase().replace(/\s/g,"-").replace(/[^-_a-zA-Z0-9]/g, '-').replace(/-+/g,"-") }
function rgb_string (rgb) { return "rgb(" + rgb.map(Math.round).join(",") + ")" }
function rgba_string (rgb,a) { return "rgba(" + rgb.map(Math.round).join(",") + "," + a + ")" }
function hex_string (rgb) { return "#" + rgb.map(Math.round).map(function(n){ var s = n.toString(16); return s.length == 1 ? "0"+s : s }).join("") }
function parse_rgba_string (s) { return s.match(/(\d+)/g).slice(0,3) }

function title_case (str) {
  return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
function pluralize (n,s,ss) { return n + " " + s + ( n == 1 ? "" : (ss || "s") ) }

var E = Math.E
var PI = Math.PI
var PHI = (1+Math.sqrt(5))/2
var TWO_PI = PI*2
var HALF_PI = PI/2
var LN10 = Math.LN10
function clamp(n,a,b){ return n<a?a:n<b?n:b }
function norm(n,a,b){ return (n-a) / (b-a) }
function lerp(n,a,b){ return (b-a)*n+a }
function mix(n,a,b){ return a*(1-n)+b*n }
function abs(n){ return Math.abs(n) }
function sign(n){ return n ? Math.abs(n)/n : 0 }
function random(){ return Math.random() }
function rand(n){ return (Math.random()*n) }
function randint(n){ return rand(n)|0 }
function randrange(a,b){ return a + rand(b-a) }
function choice(a){ return a[randint(a.length)] }
function noop(){}

function range(m,n,s){
	var a = []
	s = s || 1
	for (var i = m; i <= n; i += s) {
		a.push(i)
	}
	return a
}

function defaults (dest, src) {
	dest = dest || {}
	for (var i in src) {
		dest[i] = typeof dest[i] == 'undefined' ? src[i] : dest[i]
	}
	return dest
}

function pairs(h){
	var a = []
	for (var i in h) {
		if(h.hasOwnProperty(i)) {
			a.push([i, h[i]])
		}
	}
	return a
}
function invert_hash (h) {
	var k = {}
	for (var i in h) { if (h.hasOwnProperty(i)) k[h[i]] = i }
	return k
}
function filenameFromUrl (url) {
  var partz = url.split( "/" )
  return partz[partz.length-1].split(".")[0]
}

// Function.bind polyfill
if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          return fToBind.apply(this instanceof fNOP && oThis
                 ? this
                 : oThis,
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

// rAF polyfill
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] 
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }
 
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
 
    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

// Identify browser based on useragent string
(function( ua ) {
  ua = ua.toLowerCase();
  var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
    /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
    /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
    /(msie) ([\w.]+)/.exec( ua ) ||
    ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
    [];
  var matched = {
    browser: match[ 1 ] || "",
    version: match[ 2 ] || "0"
  };
  browser = {};
  if ( matched.browser ) {
      browser[ matched.browser ] = true;
      browser.version = matched.version;
  }
  // Chrome is Webkit, but Webkit is also Safari.
  if ( browser.chrome ) {
    browser.webkit = true;
  } else if ( browser.webkit ) {
    browser.safari = true;
  }
  if (window.$) $.browser = browser;
  return browser;
})( navigator.userAgent );

// Naive useragent detection pattern
var is_iphone = (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))
var is_ipad = (navigator.userAgent.match(/iPad/i))
var is_android = (navigator.userAgent.match(/Android/i))
var is_mobile = is_iphone || is_ipad || is_android
var is_desktop = ! is_mobile;
var transformProp = browser.safari ? "WebkitTransform" : "transform";
if (is_android) {
  document.body.parentNode.classList.add("android")
}
else {
  document.body.parentNode.classList.add("ios")
}

function selectElementContents(el) {
  if (window.getSelection && document.createRange) {
    var sel = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(el);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (document.selection && document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    textRange.moveToElementText(el);
    textRange.select();
  }
}