﻿"use strict";

var base = {

	accessability: function () {
		$('*[onclick]', document.body).not('[onkeypress]').attr('onkeypress', 'if (event.keyCode == 13 || event.keyCode == 32) { $(this).trigger(\'click\'); return base.nope(event); }');
		$('.dialog').attr('role', 'dialog');
	},

	audio: null,

	audioInit: function () {
		if (window.proj.still) { return false; }
		var a = window.proj.audio;
		if (a.id) {
			var ctx = window.AudioContext || false;
			if (ctx) { ctx = new AudioContext(); }
			var ap = '';
			if (base.cookieGet('mute') != '1') {
				ap = ' autoplay';
				base.audioPlaying = true;
				if (!(ctx) || (ctx.state == 'suspended')) {
					$(window).bind(base.clickevent, base.audioResume);
				}
			}
			base.audio = $('<audio loop' + ap + '>')[0];
			base.audio.volume = base.audioMax;
			$(base.audio).appendTo(document.body).bind('canplaythrough', function () {
				base.trigger('audio');
			}).attr('src', a.file);
			base.subscribe('mute', base.audioToggle);
		}
		if ($('.player').length == 0) { base.autoPlayCheck(); }
	},

	audioFade: 1500,

	audioMax: 0.15,

	audioPlaying: false,

	audioResume: function () {
		if (base.audio) {
			if (base.audio.paused) {
				base.audio.play();
				base.audioPlaying = true;
			}
		}
		$(window).unbind(base.clickevent, base.audioResume);
		base.cookieSet('mute', base.audio.paused ? 1 : 0);
		base.trigger('audio');
	},

	audioToggle: function (m) {
		if (base.audioVol.t == 0) { return false; }
		if (base.audio) {
			if (base.audio.paused) {
				base.audio.play();
				base.audioPlaying = true;
			}
			else {
				base.audio.pause();
				base.audioPlaying = false;
			}
		}
		base.cookieSet('mute', base.audio.paused ? 1 : 0);
		base.trigger('audio');
	},

	audioUpdate: function () {
		if (base.audio) {
			if (!base.audioPlaying) {
				if (!base.audio.paused) { base.audio.pause(); }
				base.audioVol.n = 1;
				base.audio.volume = base.audioMax;
			}
			else {
				if (base.audioVol.n != base.audioVol.t) {
					var l = (new Date()).getTime();
					var m = ((l - base.audioVol.l) / base.audioFade) * ((base.audioVol.n > base.audioVol.t) ? -1 : 1);
					var n = base.audioVol.n + m;
					if (n < 0) { n = 0; } else if (n > 1) { n = 1; }
					base.audioVol.n = n;
					base.audio.volume = n * base.audioMax;
					base.audioVol.l = l;
					window.setTimeout(base.audioUpdate, 10);
					if (n == 0) {
						if (!base.audio.paused) { base.audio.pause(); }
					}
					else {
						if (base.audio.paused) { base.audio.play(); }
					}
				}
			}
		}
	},

	audioVol: { l: null, n: 1, t: 1 },

	audioVolSet: function (t) {
		console.log('audioVolSet=' + t);
		if ((t == 1) && (document.hasFocus) && (document.hasFocus() === false)) { return false; }
		base.audioVol.t = t;
		base.audioVol.l = (new Date()).getTime();
		base.audioUpdate();
		if (t == 0) { base.trigger('musicoff'); }
		if (t == 1) { base.trigger('musicon'); }
	},

	autoplay: true,

	autoPlayCheck: function () {
		if (base.autoplay) {
			var hasMediaView = false;
			for (var a = 0; a < base.events.length; a++) { if (base.events[a].event == 'mediaset') { hasMediaView = true; } }
			if (hasMediaView) { base.mediaPlay(); }
		}
	},

	cleanText: function (t) {
		return (t || '').replace(/[\t\r\n]/g, ' ').trim();
	},

	clickevent: 'click',

	crlf: String.fromCharCode(13) + String.fromCharCode(10),

	contact: function () {
		// console.log(window.contact);
		if (window.contact) {
			contact.open.apply(this);
		}
		else {
			base.decrypt.apply(this);
		}
	},

	cookieGet: function (n) {
		var r = '';
		$(document.cookie.split('; ')).each(function (i, o) {
			if (o.substr(0, n.length + 1) == n + '=') { r = o.substr(n.length + 1); }
		});
		return r;
	},

	cookieSet: function (n, v) {
		var d = new Date();
		d.setFullYear(d.getFullYear() + 1);
		document.cookie = n + '=' + escape(v) + '; path=/; expires=' + d.toUTCString();
	},

	decrypt: function () {
		if ($(this).hasClass('colist')) {
			$(this).attr('href', unescape(window.proj.contact2.split('').reverse().join('')));
		}
		else {
			$(this).attr('href', unescape(window.proj.contact.split('').reverse().join('')));
		}
	},

	events: [],

	fixMoney: function (f) {
		var v = $(f).val();
		if (v == '') { return true; }
		var n = Number(base.moneyStripComma(v));
		if (isNaN(n)) {
			$(f).css({ boxShadow: '0 0 0 3px #f00' }).focus();
			return false;
		}
		else {
			$(f).css({ boxShadow: '' }).val(base.moneySimple(n));
			return true;
		}
	},

	footerSnap: function () {
		var fh = 0;
		var f = $('.footersnap').each(function (i, o) { fh += $(o).outerHeight(); }).first();
		if (f.length) {
			var ft = f.offset().top;
			var m = $(window).height() - (ft + fh) + Number(f.css('margin-top').replace('px', ''));
			if (m < 0 || ft == 0) {
				f.css({ marginTop: 0 });
				$('body').css({ overflowY: '' });
			}
			else {
				f.css({ marginTop: m });
				$('body').css({ overflowY: 'hidden' });
			}
		}
	},

	fullscreenFlag: false,

	fullScreen: function (m) {
		if (m == undefined) {
			m = !base.isFullScreen();
		}
		if (base.isMobile()) {
			base.fullscreenFlag = m;
		}
		else {
			if (m) {
				if (document.body.requestFullscreen) { document.body.requestFullscreen(); }
				else if (document.body.webkitRequestFullscreen) { document.body.webkitRequestFullscreen(); }
				else if (document.body.mozRequestFullScreen) { document.body.mozRequestFullScreen(); }
				else if (document.body.msRequestFullscreen) { document.body.msRequestFullscreen(); }
			}
			else {
				if (document.exitFullscreen) { document.exitFullscreen(); }
				else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); }
				else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); }
				else if (document.msExitFullscreen) { document.msExitFullscreen(); }
			}
		}
		base.trigger('resize');
		base.trigger('resize');
	},

	fullstop: false,

	geocode: function (adr, fn, f) { //address, optional result functionName, optional passthrough variable/function
		//this function calls a local (on the page that calls base.geocode) geocodeResult function, if exists, when the results have been retreived.
		var funcName = 'geocodeResult';
		if (fn != undefined) //override the name of the function if provided
			funcName = fn;

		$.ajax({
			url: '/Admin/Map/Geocode.asp?sAddress=' + encodeURIComponent(adr),
			error: function (jqXHR, s, e) {
				if (typeof self[funcName] === 'function') //using self[funcName] compares the string name as the function name
					return self[funcName]({ 'error': e }, f);
				else
					return { 'error': e };
			},
			success: function (d) {
				//console.log(d);
				if (d && d.error == undefined) {
					var l = { 'lat': d.lat, 'lng': d.lng, 'resultTypeAcceptable': d.resultTypeAcceptable, 'resultTypeAccurate': d.resultTypeAccurate, 'queryScore': d.queryScore, 'source': d.source };
					if (typeof self[funcName] === 'function')
						return self[funcName](l, f);
					else
						return l;
				} else {
					var l = { 'lat': d.lat, 'lng': d.lng, 'resultTypeAcceptable': d.resultTypeAcceptable, 'resultTypeAccurate': d.resultTypeAccurate, 'queryScore': d.queryScore, 'source': d.source, 'error': d.error };
					if (typeof self[funcName] === 'function')
						//return self[funcName]({ 'error': 'There was a problem retrieving Lat/Lng.' }, f);
						return self[funcName](l, f);
					else
						//return { 'error': 'There was a problem retrieving Lat/Lng.' }
						return l
				}
			}
		});
	},

	getMediaSize: function (s, w, h, d1, d2, f, m) {
		var l = s.split(d1);
		for (var a = 0; a < l.length; a++) {
			l[a] = l[a].split(d2);
			l[a][1] = parseInt(l[a][1]);
			l[a][2] = parseInt(l[a][2]);
		}
		for (var a = 0; a < l.length - 1; a++) {
			if (l[a][1] > l[a + 1][1]) {
				var t = l[a].slice(0);
				l[a] = l[a + 1].slice(0);
				l[a + 1] = t;
				if (a > 0) { a -= 2; } else { a--; }
			}
		}
		var p;

		if (f === true) {
			for (var a = 0; a < l.length; a++) {
				p = l[a];
				if ((p[1] > w) || (p[2] > h)) {
					return { s: p[0], w: p[1], h: p[2] };
				}
			}
		}
		else {
			if (m === true) { w *= 2; h *= 2; }
			for (var a = 0; a < l.length; a++) {
				p = l[a];
				if ((p[1] > w) && (p[2] > h)) {
					return { s: p[0], w: p[1], h: p[2] };
				}
			}
		}
		return { s: p[0], w: p[1], h: p[2] };
	},

	getMediaUrl: function (s, w, h, e, f, m) {
		if (s == '-') { return { u: '/art/pixel.gif', s: s, w: 1, h: 1 }; }
		if (s.substr(0, 1) == '*') { return { u: '/art/pixel.gif', s: s, w: 1, h: 1, v: s.substr(1) }; }
		if (w == 0 || h == 0) { return { u: '/art/pixel.gif', s: s, w: 1, h: 1 }; }
		var pr = Math.min(window.devicePixelRatio, 2);
		if (pr) { w *= pr; h *= pr; }
		if (s.substr(0, 1) == '@') {
			return { u: 'https://videodelivery.net/' + s.substr(1).split('/')[0] + '/thumbnails/thumbnail.jpg?fit=crop&time=' + ((s.substr(1) + '/').split('/')[1] || '5s') + ((w) ? '&width=' + parseInt(w) : '') + ((h) ? '&height=' + parseInt(h) : ''), s: s, w: w, h: h };
		}
		var o = base.getMediaSize(s, w, h, ',', ':', f, m);
		if (e == undefined || e == '') { e = 'jpg'; }
		if (o.s.substr(0, 1) == '~') {
			return { u: 'https://i.vimeocdn.com/video/' + o.s.substr(1) + '.jpg?r=pad', s: o.s, w: o.w, h: o.h };
		}
		else if ((o.w > (w * (m ? 4 : 2))) && (o.w > 500) && (o.h > (h * (m ? 4 : 2))) && (o.h > 500) && (window.noresizepicbox !== true)) {
			if (f === true) {
				var r = (w / h) < (o.w / o.h);
				var ww = Math.round(r ? w : h * (o.w / o.h));
				var hh = Math.round(r ? (w * (o.h / o.w)) : h);
				return { u: '/media/sized.aspx?k=' + o.s + '&e=' + e + '&w=' + ww + '&h=' + hh, s: o.s, w: ww, h: hh };
			}
			else {
				return { u: '/media/sized.aspx?k=' + o.s + '&e=' + e + '&w=' + w + '&h=' + h + (((f != undefined) && (f != false)) ? '&f=' + (f || 'c') : ''), s: o.s, w: w, h: h };
			}
		}
		else {
			return { u: '//' + window.proj.host + '/' + o.s + '.' + e, s: o.s, w: o.w, h: o.h };
		}
	},

	getVideoUrl: function (m, w, h) {
		if (m.u.toLowerCase().indexOf('videodelivery.net/') > -1) {
			return { u: 'https://cloudflarestream.com/' + m.u.toLowerCase().split('videodelivery.net/')[1].split('/')[0] + '/manifest/video.m3u8', s: m.sa, w: w, h: h };
		}
		if (m.u.toLowerCase().indexOf('vimeo.com/') > -1) {
			if (m.sa.toLowerCase().indexOf('.m3u8') > -1) {
				return { u: m.sa, s: m.sa, w: 1, h: 1 };
			}
			else {
				$.ajax({
					url: '/media/video.asp?h=' + m.id,
					success: function (d) {
						if (d.url) {
							if (d.url.toLowerCase().indexOf('.m3u8') > -1) {
								m.sa = d.url;
								$('video.mid' + m.id).each(function (i, o) { if (o.hls) { o.hls.loadSource(d.url); } else { $(o).attr('src', d.url); } });
							}
						}
					}
				});
				return { u: '', s: m.sa, w: 1, h: 1 };
			}
		}
		return { u: '/art/pixel.gif', s: m.sa, w: 1, h: 1 };
	},

	guid: function (s) {
		if (s == undefined) { s = ''; }
		s = base.onlyHex(base.iD(s));
		if (s.length == 32) {
			s = '{' + s.substr(0, 8) + '-' + s.substr(8, 4) + '-' + s.substr(12, 4) + '-' + s.substr(16, 4) + '-' + s.substr(20) + '}';
		}
		else {
			s = '';
		}
		return s;
	},

	htmlEncode: function (v) {
		return $('<textarea/>').text(v).html();
	},

	iD: function (s) { //we can worry about case if we want. I made it cap "D" to make it more intentional to use. (function should match ASP function)
		if (s == undefined) { s = ''; }
		return s.replace(/[{}-]+$/, '');
	},

	init: function () {
		base.timeMultiInit();
		var m = window.proj.media;
		base.media.length = m.length;
		base.media.duration = (m.length) ? m[m.length - 1].le : 0;
		$(window).resize(base.resize).scroll(function () { base.picbox() }).keydown(base.keydown).blur(function () { window.setTimeout(base.winBlur, 10); }).focus(base.winFocus).scroll(base.scroll);
		if (base.isMobile()) { base.clickevent = 'touchstart'; }
		$(window).bind('scroll', base.noScroll);
		$(function () {
			base.stripPhone();
			base.popin();
			base.popup();
			base.resize();
			base.mediaSet(window.proj.media[0]);
			base.audioInit();
			base.videoInit();
			base.accessability();
			window.setTimeout(function () { $(window).unbind('scroll', base.noScroll); }, 100);
			window.setTimeout(base.resize, 1000);
		});
		$('.colgroup-item').each(function (i, o) { if ($('> div', o).children().length == 0) { $(o).hide(); } });
		$('.no-context').bind('contextmenu dragstart', base.nope);
		window.setTimeout(base.scroll, 10);
		if (window.proj.still) { base.autoplay = false; }
	},

	inView: function () {
		var st = $(document).scrollTop() + $(window).height();
		$('.inview').each(function (i, o) {
			var ot = $(o).offset().top;
			if (st > ot) {
				var cb = $(o).removeClass('inview').attr('hd-inview');
				if (cb) { eval(cb); }
			}
		});
	},

	isFullScreen: function () {
		if (base.isMobile()) {
			return base.fullscreenFlag;
		}
		else {
			var fse = document.fullscreenElement || document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
			return (fse != undefined);
		}
	},

	isHlsNative: function (vid) {
		if (base.isIOS()) {
			return Boolean(vid.canPlayType('application/vnd.apple.mpegURL') || vid.canPlayType('audio/mpegurl'));
		}
		else {
			return false;
		}
	},

	isIOS: function () {
		return (/iPhone|iPod|iPad/).test(navigator.userAgent);
	},

	isMobile: function () {
		return (/Mobile|iPhone|iPod|iPad|Android|BlackBerry/).test(navigator.userAgent);
	},

	isPhone: function () {
		//return (($(window).width() < 640) || (base.winHeight() < 640));
		return ((screen.width < 640) || (screen.height < 640));
	},

	isValidEmail: function (e) {
		var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		return re.test(String(e).toLowerCase());
	},

	isValidPhone: function (p, c) {
		if (c == undefined) { c = 1; } //country. Gives us latitude
		var b = base.justNumbers(p || '');
		return b.length >= ('1,2'.indexOf(c.toString()) == -1 ? 6 : 10);
	},

	isValidReferralCode: function (rc) {
		var b = base.justNumbers(rc || '');
		return (b.length == 5);
	},

	justNumbers: function (v) {
		return $.grep(v, function (c) { return ('0123456789'.indexOf(c) > -1 ? c : ''); }).join('');
	},

	keydown: function (e) {
		var keyCode = e.keyCode || e.which;
		base.trigger('keydown', keyCode);
	},

	logHit: function (i) {
		if (base.media.counted.indexOf(',' + i + ',') < 0 && !window.proj.nohit) {
			$.ajax('/view/hit.asp?m=' + i + '&r=' + escape(window.proj.referrer));
			base.media.counted += i + ',';
		}
	},

	loop: false,

	loopset: function (n) {
		if (n == undefined) {
			base.loop = !base.loop;
		}
		else {
			base.loop = n;
		}
		base.trigger('loop');
	},

	mapLoad: function (o) {
		console.log('mapLoad', o);
		var u = 'https://' + window.proj.maphost + '/view/map.asp?s=' + window.proj.id + ((base.mapType) ? '&t=' + base.mapType : '');
		if (o === true) {
			if (base.mapLoaded < 1) {
				$.ajax({
					url: u + '&pre=1',
					complete: function () {
						if (base.mapLoaded == 3) { base.mapFrame.attr('src', u); }
						base.mapLoaded = 2;
					}
				});
				base.mapLoaded = 1;
			}
		}
		else if (base.mapLoaded < 3) {
			base.mapFrame = $('<iframe ' + ((base.mapLoaded != 1) ? 'src="' + u + '"' : '') + ' frameborder="0" style="width: 100%; height: 100%; position: relative; z-index: 10;" title="map"></iframe>').appendTo(o);
			base.mapLoaded = 3;
		}
	},

	mapLoaded: 0,

	mapType: 'roadmap',

	media: { counted: ',', duration: -1, index: 0, length: -1, loop: false, size: { w: 160, h: 120 }, time: 0 },

	mediaNext: function () {
		if (base.media.index < (base.media.length - 1)) {
			base.mediaStop();
			base.mediaSet(window.proj.media[base.media.index + 1]);
		}
	},

	mediaPlay: function () {
		if (base.media.time >= base.media.duration) { base.media.time = 0; }
		base.playing = true;
		base.media.starttime = (new Date()).getTime() - (base.media.time * 1000);
		base.trigger('play');
		base.mediaUpdate();
	},

	mediaPlayToggle: function () {
		if (base.playing) {
			base.mediaStop();
		}
		else {
			base.mediaPlay();
		}
	},

	mediaPrev: function () {
		if (base.media.index > 0) {
			base.mediaStop();
			base.mediaSet(window.proj.media[base.media.index - 1]);
		}
	},

	mediaSet: function (o) {
		if (o) {
			base.media.index = o.i;
			base.trigger('mediaSet', o);
			base.mediaSetTime(o.lb);
			base.logHit(o.id);
		}
	},

	mediaSetTime: function (n) {
		base.media.time = n;
		base.trigger('mediaSetTime', n);
	},

	mediaStop: function () {
		if (base.playing) {
			base.playing = false;
			window.clearTimeout(base.media.updatetmr);
			base.trigger('stop');
		}
	},

	mediaUpdate: function () {
		var m = base.media;
		var t;
		if (base.media.holdtime !== undefined) {
			t = base.media.holdtime;
		}
		else {
			var n = (new Date()).getTime();
			t = ((n - m.starttime) / 1000);
		}
		if (t > m.duration) {
			if (base.loop) {
				m.starttime = n
				m.time = 0;
				if (base.media.index == 0) {
					if ((window.proj.media[0]) && window.proj.media[0].t == 6) {
						if (player) {
							player.media = null;
							base.mediaSet(window.proj.media[0]);
						}
					}
				}
			}
			else {
				m.time = m.duration;
				base.mediaStop();
			}
		}
		else {
			m.time = t;
			var mm = window.proj.media;
			var i = -1;
			for (var a = 0; a < mm.length; a++) {
				if (t >= mm[a].lb && t < mm[a].le) {
					i = a;
					a = mm.length;
				}
			}
			if (i != m.index) {
				base.mediaSet(mm[i]);
			}
		}
		base.trigger('mediaSetTime', m.time);
		window.clearTimeout(base.media.updatetmr);
		if (base.playing) { base.media.updatetmr = window.setTimeout(base.mediaUpdate, 10); }
	},

	metricDisplay: false,

	money: function (n, d) {
		if (d == undefined) { d = 0; }
		n = base.round(Number(n), d);
		return new Intl.NumberFormat((base.moneyCulture.length > 1 ? base.moneyCulture : 'en-US'), { minimumFractionDigits: d, style: 'currency', currency: (base.moneyCurrency.length > 1 ? base.moneyCurrency : 'USD') }).format(n);
	},

	//if the expansion to this function causes issues anywhere else, we might want to split it out and revert moneyClean to its original state (OG one commented out below this function) and create another one to use - Should just be more robust and not an issue
	//returns as a string by default. outputNumeric is now an optional parameter
	moneyClean: function (v, stripComma = false, outputNumeric = false) {
		if (v != undefined) {
			v = base.moneySimple(base.moneyStripComma(base.moneyStripSymbol(v))); //handle 123.45, 1234.56, '1,234.56', '$1234.56', '$1,234.56' (returns '123.45' or '1,234.56')
			if (stripComma) {
				v = base.moneyStripComma(v);
			}
			if (outputNumeric) {
				return Number(v); //it will trim any trailing zeroes after the decimal point.  Use something like hd.moneySimple (or don't outputNumeric) on the page if wanting trailing zeroes in decimals (will be a string)
			}
			else { //legacy support
				return v;
			}
		}
		else {
			if (outputNumeric) {
				return NaN;
			}
			else { //legacy support
				return '';
			}
		}
	},

	//moneyClean: function (v, stripComma = false) {
	//	if (v != undefined) {
	//		v = base.moneyStripSymbol(v);
	//		if (stripComma) {
	//			v = base.moneyStripComma(v);
	//		}
	//		return v;
	//	}
	//	else {
	//		return '';
	//	}
	//},

	moneyCulture: 'en-US',

	moneyCurrency: 'USD',

	moneySimple: function (n, d = 2) {
		return base.moneyStripSymbol(base.money(n, d));
	},

	moneyStripComma: function (v) {
		if (v != undefined) {
			v = v.toString(); //make sure we have a string
			v = v.trim();
			var swapped = false;
			var thousandDelimiter = '';

			//Euro (non-English countries)
			if (base.moneyCulture.toLowerCase().substr(0, 2) != 'en' && base.moneyCurrency.toUpperCase() == 'EUR') {
				swapped = true;
				thousandDelimiter = '.';
			}
			//Canada (French)
			else if (base.moneyCulture.toLowerCase().substr(0, 2) == 'fr' && base.moneyCurrency.toUpperCase() == 'CAD') {
				swapped = true;
				thousandDelimiter = ' ';
			}
			//Switzerland
			else if (base.moneyCulture.toLowerCase().substr(0, 2) == 'fr' && base.moneyCurrency.toUpperCase() == 'CHF') {
				thousandDelimiter = ' ';
			}

			if (swapped) {
				//if we have a comma to the right of a period, we have a comma that is in the proper decimal of the number, or we have a period to the left of a potential decimal location we should have an EUR format
				if (v.indexOf(',') > v.indexOf(thousandDelimiter) || (v.lastIndexOf(',') == v.length - 3) || (v.lastIndexOf(thousandDelimiter) < v.length - 3)) {
					if (thousandDelimiter == '.')
						v = v.replace(/\./g, '').replace(/,/g, '.');
					else if (thousandDelimiter == ' ')
						v = v.replace(/\s/g, '').replace(/,/g, '.');
				}
			}
			else if (thousandDelimiter.length > 0) {
				v = v.replace(/\s/g, '');
			}
			v = v.replace(/,/g, '').replace(/\u00A0/g, ''); //remove any trailing commas (standard currency or otherwise)

			if (v.length)
				v = base.round(v, 2).toFixed(2); //protection for invalid decimal points
			return v.trim();
		}
		else {
			return '';
		}
	},

	moneyStripSymbol: function (v) {
		//should be able to just add symbols here as we add more currencies (for js) [and in functions.asp - CleanMoney()]
		if (v != undefined) {
			v = v.toString() //make sure we have a string
			v = v.replace('$', '').replace('€', '').replace('£', '').replace('CHF', '').replace('CA', '').replace(/\&nbsp;/g, ' ').trim();
			return v;
		}
		else {
			return '';
		}
	},

	nope: function (e) {
		e.preventDefault();
		e.stopPropagation();
		return false;
	},

	noScroll: function (e) {
		$(document).scrollTop(0);
		return false;
	},

	number: function (n, d) {
		if (d == undefined) { d = 0; }
		return Number(n).toFixed(d).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
	},

	onlyHex: function (s) {
		if (s == undefined) { s = ''; }
		return s.replace(/^[^0-9a-fA-F]+$/, '');
	},

	parallax: function () {
		var st = $(document).scrollTop();
		var wh = base.winHeight();
		$('.parallax').each(function (i, o) {
			var os = $(o).offset();
			var t = os.top;
			var oh = $(o).height();
			if ((t < (st + wh)) && ((t + oh) > st)) {
				var p = (st - t) / (wh - oh);
				var oo = $(':first-child', o).first();
				$(oo).css({ marginTop: ($(oo).height() - oh) * p });
			}
		});
	},

	phoneMode: false,

	picbox: function (d) {
		if (d == undefined) { d = $('body'); }
		var wt = $(window).scrollTop();
		var wb = wt + $(window).height();
		$('.picbox', d).each(function (i, o) {
			var ln = $(o).hasClass('loadnow');
			if (!o.picboxprocessed || ln) {
				var et = $(o).offset().top;
				var eb = et + $(o).height();
				if ((et == 0) || ((et <= wb) && (eb >= wt)) || ln) {
					o.picboxprocessed = true;
					var s = $(o).attr('hd-media');
					var mt = $(o).attr('hd-mediatype');
					if ((s == undefined) || (s == '')) {
						if ($(o).attr('hd-mediahideifempty') != undefined) { $(o).hide(); $(o).closest('.hdmediahide').hide(); }
					}
					else if (mt == 5) {
						var pw = $(o).width();
						var ph = $(o).height();
						var m = base.getMediaUrl(s, pw * 3, ph * 3, ext, fit);
						var eu = $(o).attr('hd-spherepan');
						if (eu) {
							if (eu != m.u) {
								$(o).attr('hd-spherepan', m.u);
								o.viewer.setPanorama(m.u);
							}
						}
						else {
							base.sphere_init();
							$(o).attr('hd-spherepan', m.u);
							var il = ($(o).attr('hd-sphereinline') !== undefined);
							o.viewer = new PhotoSphereViewer({
								container: o,
								panorama: m.u,
								navbar: false,
								min_fov: 50,
								default_lat: 0,
								default_long: 0,
								default_fov: 80,
								move_speed: 1.3,
								time_anim: false,
								mousewheel: !il,
								touchmove_two_fingers: il
							});
							o.sphereanim = $(o).attr('hd-sphereanim');
							if (o.sphereanim) { base.sphere_anim(o); }
						}
						o.viewer.resize({ width: pw + 'px', height: ph + 'px' });
					}
					else {
						var img = $('> img', o);
						if (img.length == 0) { img = $('<img>').appendTo(o); }
						var fit = $(o).attr('hd-mediafit');
						var ext = $(o).attr('hd-mediaext');
						var sdiv = $(o).attr('hd-mediashrinkdiv');
						if ($(o).attr('hd-mediashrinkdivclear') !== undefined) { $(o).css({ width: '', height: '' }); }
						var pw = $(o).width();
						var ph = $(o).height();
						var m, x, y, iw, ih;
						if (fit == 'face') {
							var ss = s.split(',');
							if (ss && ss[0] && ss[0].split(':') && ss[0].split(':')[3] && ss[0].split(':')[3].length > 1) {
								var x1, y1, x2, y2;
								$(ss[0].split(':')[3].split('|')).each(function (i, o) {
									var oo = o.split('`');
									if (x1 == undefined || x1 > Number(oo[0])) { x1 = Number(oo[0]); }
									if (y1 == undefined || y1 > Number(oo[1])) { y1 = Number(oo[1]); }
									if (x2 == undefined || x2 < Number(oo[2])) { x2 = Number(oo[2]); }
									if (y2 == undefined || y2 < Number(oo[3])) { y2 = Number(oo[3]); }
								});
								var fw = Math.min((x2 - x1) * 0.017, 1);
								var fh = Math.min((y2 - y1) * 0.017, 1);
								var pm = 1 / Math.max(fw, fh);
								m = base.getMediaUrl(s, pw * pm, ph * pm, ext);
								var r = ((pw / ph) < (m.w / m.h));
								iw = (r ? ph * (m.w / m.h) : pw) * pm;
								ih = (r ? ph : pw / (m.w / m.h)) * pm;
								x = Math.max(Math.min((((iw * ((x1 + x2) * 0.005)) - (pw * 0.5)) / (iw - pw)) || 0, 1), 0);
								y = Math.max(Math.min((((ih * ((y1 + y2) * 0.005)) - (ph * 0.5)) / (ih - ph) || 0), 1), 0);
							}
							else {
								fit = undefined;
							}
						}
						if (fit != 'face') {
							m = base.getMediaUrl(s, pw, ph, ext, (fit != undefined));
							var r = ((pw / ph) < (m.w / m.h));
							x = 0.5;
							y = 0.5;
							if (fit != undefined) {
								r = !r;
								fit = ' ' + fit.toLowerCase() + ' ';
								if (fit.indexOf(' left ') > -1) { x = 0; } else if (fit.indexOf(' right ') > -1) { x = 1; }
								if (fit.indexOf(' top ') > -1) { y = 0; } else if (fit.indexOf(' bottom ') > -1) { y = 1; }
							}
							iw = Math.ceil(r ? ph * (m.w / m.h) : pw);
							ih = Math.ceil(r ? ph : pw / (m.w / m.h));
						}
						$(img[0]).off('error', base.picbox_error).on('error', base.picbox_error).attr('alt', ($(o).closest('[role=img]').attr('aria-label') != undefined ? $(o).closest('[role=img]').attr('aria-label') : ''));
						if (sdiv == undefined) {
							iw += 2; ih += 2;
							$(img[0]).attr('src', m.u).css({ left: ((pw - iw) * x), top: ((ph - ih) * y), width: iw, height: ih });
						}
						else {
							$(img[0]).attr('src', m.u).css({ left: 0, top: 0, width: iw, height: ih });
							$(o).css({ width: iw, height: ih });
						}
					}
				}
			}
		});
	},

	picbox_error: function () {
		var src = $(this).attr('src');
		var s = src.split('/');
		var f1 = 'hdphotohub-' + s[3] + '.s3.us-east-2.wasabisys.com';
		var f2 = 'hdphotohub-' + s[3] + '.s3.us-west-002.backblazeb2.com';
		if (s[2] == window.proj.host) { s[2] = f1; } else if (s[2] == f1) { s[2] = f2; } else {
			var e = base.picbox_errors;
			e.count++;
			e.last = src;
			if (e.first == undefined) { e.first = src; }
			if (e.timer) { window.clearTimeout(e.timer); }
			e.timer = window.setTimeout(base.picbox_errorlog, 2000);
			return false;
		}
		$(this).attr('src', s.join('/'));
	},

	picbox_errors: { count: 0 },

	picbox_errorlog: function (d) {
		var e = base.picbox_errors;
		console.log(e);
		$.ajax('/view/mediaerror.asp?c=' + e.count + '&f=' + encodeURIComponent(e.first) + '&l=' + encodeURIComponent(e.last));
		base.picbox_errors = { count: 0 };
	},

	picbox_resize: function (d) {
		$('.picbox').each(function (i, o) { o.picboxprocessed = false; });
		base.picbox(d);
	},

	playing: false,

	popin: function () {
		$('.popin').click(function () {
			if (base.isMobile()) { return true; }
			var u = $(this).attr('href');
			if ((String(document.location.href).toLowerCase().substr(0, 8) == 'https://') && (u.toLowerCase().substr(0, 7) == 'http://')) { return true; }
			$('.popin-container').remove();
			var pic = $('<div class="popin-container blackout fsize" hd-fsize="3"><div class="popin-close ion-close-circled"></div><iframe class="popin-content"></iframe></div>').appendTo(document.body).click(base.popinClose);
			$('.popin-close', pic).bind(base.clickevent, base.popinClose);
			base.resizeFonts();
			$('.popin-content', pic).attr('src', u);
			$(pic).stop(true, false).css({ opacity: 0 }).show().animate({ opacity: 1 }, 300);
			return false;
		});

	},

	popinClose: function () {
		$('.popin-container').stop(true, false).animate({ opacity: 0 }, 500, function () { $(this).hide(); });
	},

	popup: function () {
		$('.popup').click(function () {
			var p;
			var s = $(this).attr('hd-popup');
			if (s != '') {
				var w = s.split(',')[0];
				var h = s.split(',')[1];
				p = (s == '' ? '' : 'width=' + w + ',height=' + h + ',left=' + ((screen.width - w) * 0.5) + ',top=' + ((screen.height - h) * 0.3) + ',menubar=0,status=0,titlebar=0');
			}
			window.open($(this).attr('href'), '_blank', p);
			return false;
		});
	},

	preload: true,

	resize: function () {
		base.resizeFonts();
		base.trigger('resize');
		base.resizeFonts();
		var pm = base.isPhone();
		var v = ($(window).width() < base.winHeight());
		if ((base.phoneMode != pm) || (base.vert != v)) {
			base.phoneMode = pm;
			base.vert = v;
			if (pm) {
				$('.phoneshow').show(); $('.phonehide').hide();
				if (v) { $(document.body).addClass('phone-vert').removeClass('phone-horz'); } else { $(document.body).addClass('phone-horz').removeClass('phone-vert'); }
			}
			else {
				$('.phoneshow').hide(); $('.phonehide').show();
				$(document.body).removeClass('phone-vert phone-horz');
			}
		}
		$('.propheight').each(function (i, o) { var oo = $(o); oo.height(oo.width() * Number(oo.attr('hd-propheight')) * 0.01); });
		base.resizeFonts();
		base.parallax();
		base.footerSnap();
		base.trigger('resize');
		window.setTimeout(base.picbox_resize, 0);
	},

	resizeFonts: function (e) {
		if (e == undefined) { e = '.fsize'; }
		var wh = base.winHeight();
		$(e).each(function (i, o) {
			var fs = $(o).attr('hd-fsize');
			if (fs == '%h') { fs = ($(o).height() / wh) * 100; }
			$(o).css({ fontSize: wh * (parseFloat(fs) / 100) });
		});
	},

	round: function (number, precision) {
		var shift = function (number, exponent) {
			var numArray = ('' + number).split('e');
			return +(numArray[0] + 'e' + (numArray[1] ? (+numArray[1] + exponent) : exponent));
		};
		return shift(Math.round(shift(number, +precision)), -precision);
	},

	script_add: function (s) {
		$('<script>').attr('src', s).appendTo('body');
	},

	style_add: function (s) {
		$('<link>').attr({ rel: 'stylesheet', href: s }).appendTo('body');
	},

	scroll: function () {
		base.trigger('scroll');
		base.inView();
		base.parallax();
	},

	scrollHide: function () {
		if (!$(document.body).attr('hd-overflowy')) {
			$(document.body).attr('hd-overflowy', $(document.body).css('overflow-y'));
		}
		$(document.body).css('overflow-y', 'hidden');
	},

	scrollShow: function () {
		$(document.body).css('overflow-y', $(document.body).attr('hd-overflowy'));
		base.resize();
	},

	scrollTo: function (t) {
		$('html, body').stop(true, false).animate({ scrollTop: ($(t).offset().top - $('.header, .navbar').height()) + 1 }, 700, 'easeOutQuart');
		return false;
	},

	sphere_anim: function (o) {
		var a = o.sphereanim;
		if (a) {
			var p = o.viewer.getPosition();
			p.longitude += parseFloat(a);
			o.viewer.rotate(p);
			window.setTimeout(function () { base.sphere_anim(o); }, 20);
		}
	},

	sphere_init: function () {
		base.style_add('/art/photo-sphere-viewer.min.css');
		base.script_add('/js/three.min.js');
		base.script_add('/js/doT.min.js');
		base.script_add('/js/uEvent.js');
		base.script_add('/js/photo-sphere-viewer.min.js');
		base.sphere_init = function () { }
	},

	stripPhone: function () {
		if (!base.isMobile()) {
			$('a').each(function (i, o) {
				var h = $(o).attr('href');
				if (h != undefined) {
					if (h.substr(0, 4).toLowerCase() == 'tel:') {
						$(o).removeAttr('href');
					}
				}
			});
		}
	},

	subscribe: function (e, f) {
		var ee = e.toLowerCase().split(' ');
		for (var a = 0; a < ee.length; a++) {
			if (ee[a] != '') {
				var i = -1;
				for (var b = 0; b < base.events.length; b++) {
					if (base.events[b].event == ee[a]) {
						i = b;
						b = base.events.length;
					}
				}
				if (i < 0) {
					base.events.push({ event: ee[a], f: [f] });
				}
				else {
					var ff = base.events[i].f;
					for (var b = 0; b < ff.length; b++) { if (ff[b] == f) { return false; } }
					base.events[i].f.push(f);
				}
			}
		}
		return true;
	},

	timeMulti: 1,

	timeMultiInit: function () {
		var t = base.timeMulti;
		if (t == 1) { return false; }
		var m = window.proj.media;
		var pe = 0;
		for (var a = 0; a < m.length; a++) {
			if (m[a].t != 6) { m[a].l = m[a].l * t; }
			m[a].lb = pe;
			pe = m[a].le = (m[a].lb + m[a].l);
			// console.log(m[a]);
		}
		// console.log(window.proj.media);
	},

	trigger: function (e, p) {
		var ee = e.toLowerCase();
		for (var a = 0; a < base.events.length; a++) {
			if (base.events[a].event == ee) {
				var ff = base.events[a].f;
				for (var b = 0; b < ff.length; b++) { ff[b](p); }
				return true;
			}
		}
		return false;
	},

	vert: false,

	videoInit: function () {
		$('.stream-singleplay').load(function () {
			var player = Stream(this);
			player.addEventListener('play', () => {
				window.setTimeout(function () {
					base.videoPlaying = true;
					base.audioVolSet(0);
				}, 50);
			});
			player.addEventListener('pause', () => {
				base.videoPlaying = false;
				base.audioVolSet(1);
			});
		});
		$('.vimeo-singleplay').load(function () {
			var player = new Vimeo.Player(this);
			player.setLoop(true);
			player.on('play', function () {
				player.getCuePoints().then(function (d) {
					if (d.length == 0) {
						player.getDuration().then(function (d) {
							player.addCuePoint(d - 0.5, {});
						});
					}
				});
				window.setTimeout(function () {
					base.videoPlaying = true;
					base.audioVolSet(0);
				}, 50);
			});
			player.on('cuepoint', function () {
				player.pause();
				player.setCurrentTime(0);
			});
			player.on('pause', function () {
				base.videoPlaying = false;
				base.audioVolSet(1);
			});
		});
		$('.youtubeplayer').load(base.youtubePlayer);
	},

	videoPlaying: false,

	winBlur: function () {
		if ($('iframe').is(':focus') || ($(document.activeElement).hasClass('nomute'))) {
			window.clearTimeout(base.winBlurTimer);
			base.winBlurTimer = window.setTimeout(base.winBlur, 100);
		}
		else {
			if ((base.audio) && !base.audio.paused) {
				base.audioVolSet(0);
			}
		}
	},

	winBlurTimer: null,

	winFocus: function () {
		window.clearTimeout(base.winBlurTimer);
		if ((base.audio) && (base.audioPlaying == true) && (base.videoPlaying == false)) {
			base.audioVolSet(1);
		}
	},

	winHeight: function () {
		var ww = $(window).width();
		var h = Math.min((window.proj.winHeight) ? window.proj.winHeight : Math.max(Math.min($(window).height(), ww * 1.2), ww * 0.5), screen.height);
		return h;
	},

	youtubeReady: false,

	youtubePlayer: function () {
		if (!base.youtubeReady) {
			var t = this;
			window.setTimeout(function () { base.youtubePlayer.apply(t); }, 100);
		}
		else {
			var player = new YT.Player(this, {
				events: {
					onStateChange: function (e) {
						if (e.data == YT.PlayerState.PLAYING) {
							window.setTimeout(function () {
								base.videoPlaying = true;
								base.audioVolSet(0);
							}, 50);
						}
						if (e.data == YT.PlayerState.PAUSED || e.data == YT.PlayerState.ENDED) {
							base.videoPlaying = false;
							base.audioVolSet(1);
						}
					}
				}
			});
		}
	}
};

function onYouTubeIframeAPIReady() { base.youtubeReady = true; }

if ($('script').last().attr('src').toLowerCase().indexOf('noinit') == -1) {
	$(base.init);
}

