(function($) {

O_O.widget.SlideShowControls.Controller = function($elem, props, msgSys, env) {
	O_O.lib.Controller.apply(this, arguments);

	this.view = O_O.mm.oNew(O_O.widget.SlideShowControls.View, $elem, props,
		scopeC(this._controllerCb, this), env);
};

O_O.widget.SlideShowControls.Controller.prototype = {
	cfgDefault: null,
	locked: null,

	delegateInterfaces: {
		Gallery: {
			required: false,
			functions: ['load']
		},
		Images: {
			required: false,
			functions: ['set']
		},
		Page: {
			required: false,
			functions: ['goTo', 'chrome']
		},
		Play: {
			required: false,
			functions: ['toggle']
		},
		Meta: {
			required: false,
			functions: ['toggle']
		},
		Thumbs: {
			required: false,
			functions: ['toggle', 'filter']
		},
		Share: {
			required: false,
			functions: ['toggle']
		},
		Buy: {
			required: false,
			functions: ['toggle']
		},
		JumpTo: {
			required: false,
			functions: ['image']
		}
	},

	implementInterfaces: {
		State: {
			count: function(pageInfo, imageSize, id) {
				this.view.image_id = id;
				this.view.setImageSize(imageSize);
				this.view._updateCount(pageInfo);
			}
		},
		Meta: {
			remove: function() {
				var previous = this.view.config.f_meta;
				this.view.config.f_meta = 'n';
				if (previous !== this.view.config.f_meta)
					this.view.render(this.gallery);
			}
		},
		Gallery: {
			set: function(gallery) {
				this.imgs = false;
				this.gallery = gallery;
				this.delegate('Gallery', 'load')(this.gallery);
				this.view.render(this.gallery);
			},
			load: function(g_id, size, id, c_id) {
				if (!isset(g_id)) return;
				this.imgs = false;
				this.view.config = jQuery.extend(true, {}, this.config);
				var gallery = O_O.model.get('Gallery', g_id);
				gallery.load().done(scopeC(function(galleryData){
					if (this.gallery === false || this.gallery.id !== galleryData.id)
						this.gallery = galleryData;
					if (this.view.config.f_thumbs !== 'n' && this.view.config.f_thumbs !== 'a') {
						if (typeof id === 'string' && this.view.config.f_thumbs === 't')
							this.view.config.f_thumbs = 'f';
						else if (((id === null || !id) && !!this.view.config.f_thumbs_force) ||
								!isset(id)) {
							if (this.view.config.f_play === 't')
								this.view.config.f_play = 'f';
							this.view.config.f_thumbs = 't';
						}
					}
					this.delegate('Gallery', 'load')(
						this.gallery,
						true,
						id,
						(this.view.config.f_thumbs === 't'),
						c_id
					);
					this.view.render(this.gallery);
				}, this));
			}
		},
		Galleries: {
			load: function(gals) {
				var id, type, m, fullModels = [], dfrA = [];
				if (!isset(gals) || !isset(this.config)) return;
				this.view.config = jQuery.extend(true, {}, this.config);

				for (var i = 0, len = gals.length; i < len; i++) {
					id = gals[i].id;
					if (id.charAt(0) === 'C') type = 'Collection';
					else if (id.charAt(0) === 'G') type = 'Gallery';
					else throw 'Home mode: unknown id: ' + id;

					m = O_O.model.get(type, id);
					fullModels[id] = m;

					// FIXME: using f_force for now to guarantee key_image data
					dfrA.push(m.load({f_force: true}));
				}

				return $.when.apply(this, dfrA).done(scopeC(function() {
					var models = [];
					var m;
					for (var i=0, len=arguments.length; i<len; i++) {
						// TODO: Combine this and Herotab code into one
						// error handling function for DRYness
						m = arguments[i];

						if (m.type === 'error') console.log('error detected, skipping', m.args);
						else if (!m.key_image || is_array(m.key_image)) console.log('empty tab, skipping', m);
						else models.push(fullModels[m.id]);
					}

					return this.view.render(models)
						.done(scopeC(function() {
							return this._loadGals(models);
						}, this));
				}, this));
			},
			filter: function(g_id, id) {
				this.g_id = g_id;
				this.id = id;
				if (isset(this.config) && !!this.imgs)
					this.filter(g_id, id);
			}
		},
		Thumbs: {
			toggle: function(what) {
				if (what === 'caption') {
					this.view._meta();
					return;
				}

				this.view.config = jQuery.extend(true, {}, this.config);
				if (this.view.config.f_thumbs !== 'a' && this.view.config.f_thumbs !== 'n')
					this.view.config.f_thumbs = 'f';
				if (this.view.config.f_play === 't')
					this.view._playState(false);

				this.view._thumbs(true);
			}
		},
		Pricing: {
			toggle: function(f) {
				this.pricing = !!f;
				if (this.config.buyMenu === 't')
					this.view._toggleBuy(this.pricing);
			}
		}
	},

	f_meta_override: null,

	render: function(cfg) {
		var $dfd = new $.Deferred();
		//Force handhelds not to show captions on load.
		if (O_O.browser.getResponsiveState() === 'handhelds') {
			if (cfg.f_meta === 't') {
				cfg.f_meta = 'f';
			}
			else if (cfg.f_meta === 'a')
				cfg.f_meta = 'n';
		}

		// REVIEWME: Was forcing play to false for something ELEMENT?
		// if (typeof this.view.config !== 'undefined' &&
		// 	this.view.config.f_play === 'f' &&
		// 	cfg.f_play !== 'n')
		// 	cfg.f_play = 'f';

		this.config = jQuery.extend(true, {}, cfg);
		this.view.config = cfg;
		this.cfgDefault = jQuery.extend(true, {}, cfg);

		var $makeObjA;

		switch (cfg.dataSource) {
		case 'user':
			$makeObjA = this._makeUserObjA(cfg.userLinks);
			break;
		case 'recent':
			$makeObjA = this._makeRecentGalObjA();
			break;
		default:
			//==dynamic
			$makeObjA = this._makeDynamicObjA();
		}

		$makeObjA.fail(function() {
			$dfd.reject();
		}).done(scopeC(function(objA) {
			if (cfg.dataSource === 'dynamic') {
				this.gallery = this.gallery || false;
				this.imgs = this.imgs || false;
			} else {
				this.gallery = objA[0];
				this.delegate('Gallery', 'load')(this.gallery);
			}
			if (!!this.gallery || !!this.imgs) {
				this.view.render(this.gallery).fail(function() {
					$dfd.reject();
				}).done(scopeC(function() {
					if (this.config.buyMenu === 't')
						this.view._toggleBuy(this.pricing);
					$dfd.resolve();
				}, this));
			} else {
				$dfd.resolve();
			}
		}, this));

		return $dfd.promise();
	},

	_makeDynamicObjA: function() {
		var $dfr = $.Deferred().resolve([false]);
		return $dfr.promise();
	},

	_makeUserObjA: function(idA) {
		this._clcMods = {};

		var i, l, type, id, mod, modA = [];
		for (i = 0, l = idA.length; i < l; i++) {
			type = idA[i].type; // 'Collection' || 'Gallery'
			id = idA[i].id;

			mod = O_O.model.get(type, id);
			this._clcMods[id] = mod; // keep models to load clc contents
			modA.push(mod);
		}

		return O_O.model.batchDfrAction(modA, 'load', [{f_force: true}],
			function (errA) { console.log('error loading GalleryNav user item, skipping', errA); });
	},

	_makeRecentGalObjA: function() {
		return O_O.model.get('RecentGalleries').load().then(scopeC(function(modA) {
			//f_force necessary until RecentGalleries returns same data as Gallery endpoint
			return O_O.model.batchDfrAction(modA, 'load', [{f_force: true}],
				function (errA) { console.log('error loading GalleryNav user item, skipping', errA); });
		}, this));
	},

	toggle: function(id) {
		this.id = id || this.id;
		this.delegate('Gallery','load')(this.id, this.showing, this.cfg.f_spacing);
	},

	_closeViewer: function() {
		if (!!this.config.f_thumbs_force) {
			if (this.delegateMap.Thumbs)
				this.delegate('Thumbs', 'toggle')(
					(isset(this.imgs) && !!this.imgs) ? this.imgs : this.gallery,
					true
				);
		}
		//this._msgCloseViewer();
		return this.msgSys.pub('Shell', {
			msg: 'event',
			data: {
				type: 'closeViewer',
				data: {
					id: this.view.image_id
				}
			}
		});
	},

	_playOnReturn: function() {
		if (this.view.config.f_play !== 't') return;
		this.view._updateButton('play');
		if (this.delegateMap.Play)
			this.delegate('Play', 'toggle')({f_play: 't'}, true);
	},

	_msgCb: function(channel, payload) {
		var d = payload.data;
		switch (payload.msg) {
		case 'event':
			return this._eventH(d.type, d.data);
		case 'closeThumbs':
			if (this.cfgDefault !== null && this.cfgDefault.f_play === 't') {
				this.view.config.f_play = 't';
				this._playOnReturn();
			}
			if (this.view.$thumbs)
				this.view.$thumbs.removeClass('on');
			if (isset(this.view.config) && this.view.config.f_thumbs === 't')
				this.view.config.f_thumbs = 'f';
			break;
		case 'closeShare':
			this._playOnReturn();
			this.overlay = false;
			if (this.view.$share)
				this.view.$share.removeClass('on');
			break;
		case 'closeMeta':
			if (this.view.$meta)
				this.view.$meta.removeClass('on');
			break;
		case 'closeBuy':
			this._playOnReturn();
			this.overlay = false;
			if (this.view.$buy)
				this.view.$buy.removeClass('on');
			break;
		}
	},

	/* unused functions (here to override abstract controller) */

	_controllerCb: function(type, payload) {
		var to;
		if (type !== 'meta' && !this.gallery && !this.imgs &&
			(type !== 'closeViewer' || type !== 'editWidget'))
			return;
		switch (type) {
		case 'page':
			if (typeof payload.isChromeOff === 'undefined')
				this.delegate('Page', 'goTo')(payload);
			else
				this.delegate('Page', 'chrome')(payload);
			break;
		case 'play':
			to = (payload.f_play === 't') ? true : false;
			if (!!to) {
				if (this.delegateMap.Thumbs)
					this.delegate('Thumbs', 'toggle')(
						(isset(this.imgs) && !!this.imgs) ? this.imgs : this.gallery,
						this.config.f_thumbs !== 'a' ? false : true
					);
				if (this.delegateMap.Share)
					this.delegate('Share', 'toggle')(false);
			}
			this.delegate('Play', 'toggle')(payload);
			break;
		case 'meta':
			to = (payload.f_meta === 't' ||
				payload.f_meta === 'a') ? true : false;
			this.delegate('Meta', 'toggle')(to);
			if (!!to) {
				if (this.delegateMap.Share)
					this.delegate('Share', 'toggle')(false);
				if (this.delegateMap.Thumbs && this.config.f_thumbs !== 'a' &&
					(!!this.gallery || !!this.imgs))
					this.delegate('Thumbs', 'toggle')(
						(isset(this.imgs) && !!this.imgs) ? this.imgs : this.gallery,
						false
					);
			}
			break;
		case 'thumbs':
			to = (payload.config.f_thumbs === 't' ||
				payload.config.f_thumbs === 'a') ? true : false;
			if(!!to && payload.config.f_thumbs !== 'a') {
				// default to path vars, fall back to query vars
				// this is only used when loading the thumb view
				// so do not set imgId, only clcId and galId
				var url = O_O.lib.Util.parseUrl(),
				    data = {
					clcId: url.clc_id || url.queryGet('C_ID'),
					galId: url.gal_id || url.queryGet('G_ID')
				    };

				if (!!data.galId) {
					this.msgSys.pub('Shell', {
						msg: 'event',
						data: {
							type: 'updatePath',
							data: data
						}
					});
				}
				if (this.delegateMap.Play)
					this.delegate('Play', 'toggle')({f_play: 'f'});
				if (this.delegateMap.Share)
					this.delegate('Share', 'toggle')(false);
			} else {
				if (payload.config.f_play === 'f' &&
						this.config.f_play === 't') {
					this.view.config.f_play = 't';
					this.view._updateButton('play');
					if (this.delegateMap.Play)
						this.delegate('Play', 'toggle')({f_play: 't'}, true);
				}
			}
			var galState = jQuery.extend(true, {idx: payload.idx}, this.gallery);

			if (this.delegateMap.Thumbs)
				this.delegate('Thumbs', 'toggle')(
						(isset(this.imgs) && !!this.imgs) ? this.imgs : galState,
						to
					);
			break;
		case 'share':
			this.overlay = true;
			this.delegate('Play', 'toggle')({f_play: 'f'}, false);
			if (this.delegateMap.Share)
				this.delegate('Share', 'toggle')(payload.toggle, payload.id);
			break;
		case 'buy':
			this.overlay = true;
			this.delegate('Play', 'toggle')({f_play: 'f'}, false);
			if (this.delegateMap.Buy)
				this.delegate('Buy', 'toggle')(payload.toggle);
			break;
		case 'closeViewer':
			return this._closeViewer();
		case 'editWidget':
			return this.msgSys.pub('Shell', {
				msg: 'editWidget',
				data: {
					view: payload.view,
					cfgId: this.getCfg()
				}
			});
		}
	},

	disableLinks: function(f_lock) {
		this.locked = !!f_lock;
		this.view.disableLinks(!!f_lock);
	},

	_eventH: function(type, data) {
		switch (type) {
		case 'lockMode':
			this.disableLinks(!!data.f_lock);
			break;
		case 'keyDown':
			if (!this.f_active) break;
			if (this.overlay) break;
			if (this.locked) break;
			if (data.key === 'left')
				this._controllerCb('page', 'backward');
			else if (data.key === 'right')
				this._controllerCb('page', 'forward');
			break;
		}
	},

	/* local functions */

	_makeMetaImgUrl: function(imgUrl, hasExt) {
		if (hasExt) imgUrl = imgUrl.substr(0, imgUrl.lastIndexOf('/'));
		return imgUrl.substr(0, imgUrl.lastIndexOf('/')) + '/fill=600x600';
	},

	//DEALING WiTH MULTIPLE GALLERIES//

	HASH_PREFIX: 'gal',
	galHashA: [],
	galleries: [],
	idx: 0,

	jumpTo: function(id) {
		if (!!this.imgs) {
			if (this.delegateMap.JumpTo)
				this.delegate('JumpTo', 'image')(id);
		} else
			this.id = id;
	},

	filter: function() {
		var gallery;
		if (this.g_id === 'all') {
			this.currentImgs = this.imgs;
			if (this.delegateMap.Images)
				this.delegate('Images', 'set')(this.currentImgs, null, true);
			if (this.delegateMap.Thumbs)
				this.delegate('Thumbs', 'filter')('*');
			return;
		}
		gallery = O_O.model.get('Gallery', this.g_id);
		gallery.load().done(scopeC(function(galleryData){
			if (this.delegateMap.Thumbs)
				this.delegate('Thumbs', 'filter')(this.g_id);

			if (this.gallery === false || this.gallery.id !== galleryData.id)
				this.gallery = galleryData;
			if (this.delegateMap.Gallery)
				this.delegate('Gallery', 'load')(
					galleryData,
					isset(this.id) && !!this.id,
					this.id,
					!!this.id,
					null
				);
			this.view.render(this.gallery);
		}, this));
		this.g_id = 0;
		this.id = false;
	},

	_loadGals: function(models) {
		var whenA = [];
		this.galleries = {};
		for (var i = 0, count = models.length; i < count; i++) {
			whenA.push(this._processGallery(models[i]));
		}

		return $.when.apply(this, whenA)
			.done(scopeC(function() {
				if (!this.config.uses_isotope) {
					var metaImgs = [];
					for (var key in this.galleries) {
						if (this.galleries.hasOwnProperty(key)) {
							var gal = this.galleries[key];
							if (gal.images.length > 0)
								metaImgs.push(this._makeMetaImgUrl(gal.images[0].src, true));
						}
					}
					this._controllerCb('setMetaTags', {
						props: {
							'og:title': this.env('custom').site_name + ' ' + window.location,
							'og:description': this.env('custom').site_name + ' ' + window.location,
							'og:url': window.location,
							'og:image': metaImgs
						}
					});
				}
				this._processImages();
			}, this));
	},

	_processGallery: function(galMod) {
		//get images from first gallery here
		var g = galMod.extractPrimitiveData(),
			images = [],
			$dfd = $.Deferred();
		var hash = this.HASH_PREFIX + this.galHashA.length;
		this.galHashA.push(g.id);

		this.galleries[g.id] = {
			id: g.id,
			name: g.name,
			hash: hash
		};

		// FIXME: DRY this up once getKeyImages correctly returns model
		// (right now returns bare data, requiring manual URL assembly)

		if (this.config.f_showOnlyKeyImages) {
			galMod.getKeyImage().done(scopeC(function(imgD) {

				var keyImgMod = galMod.getKeyImageModel();
				var imgMod = keyImgMod.getImageModel();

				var url = keyImgMod.getLinkForSize({
					width: this.config.image_width,
					height: this.config.image_height,
					mode: this.config.image_mode
				});

				images.push($.extend(true, {}, imgMod.extractPrimitiveData(), {
					g_id: g.id,
					g_hash: hash,
					src: url,
					g_name: g.name
				}));

				this.galleries[g.id].images = images;
				$dfd.resolve();
			}, this));
		}
		else {
			galMod.getImages().done(scopeC(function(imageModels) {
				for (var i = 0, count = imageModels.length; i < count; i++) {
					var img = imageModels[i];
					var imgD = img.getImageModel().extractPrimitiveData();

					/** TEMPORARY fix for the Chrome 53 bug that is killing East & Shuffle - PB 9/2/2016 **/
					var themeId = this.env('custom').theme;
					if ( themeId === 'Theme6' || themeId === 'Theme2') {
						images.push($.extend(false, {}, img, $.extend(true, {}, {
							g_id: g.id,
							g_hash: hash,
							src: img.getLinkForSize({
								width: this.config.image_width,
								height: this.config.image_height,
								mode: this.config.image_mode
							})
						})));
					} else {
						images.push($.extend(true, {}, img, {
							g_id: g.id,
							g_hash: hash,
							src: img.getLinkForSize({
								width: this.config.image_width,
								height: this.config.image_height,
								mode: this.config.image_mode
							})
						}));
					}
				}

				this.galleries[g.id].images = images;
				$dfd.resolve();
			}, this));
		}

		return $dfd.promise();
	},

	/*
	Formats the gallery images for insertion into the template.
	The first image in the first gallery ->
	The first image in the second gallery ->
	The first image in the third gallery, etc.
	See: Spec
	*/
	_processImages: function() {
		var gals = this.galleries,	//Galeries
			galsLs = [],		//Gallery Lengths
			imgs = [],		//Images
			imgsC,			//Images counter
			i, t, gs = 0;

		for (i in gals) {
			if (gals.hasOwnProperty(i)) {
				gs++;
				if (this.isPhantom) {
					gals[i].href = this.env('#c1_url', gals[i]);
				} else {
					gals[i].href = '#';
				}
				galsLs.push(gals[i].images.length);
			}
		}

		if (!empty(galsLs)) imgsC = Math.max.apply(Math, galsLs);
		else imgsC = 0;

		for (var img = 0; img < imgsC; img++) {
			for (i in gals) {
				if (gals.hasOwnProperty(i) && isset(gals[i].images[img])) {
					t = gals[i].images[img];
					// HACK: copy gallery name
					t.g_name = gals[i].name;
					imgs.push(t);
				}
			}
		}

		this.imgs = imgs;
		this.currentImgs = this.imgs;
		if (this.delegateMap.Images)
			this.delegate('Images', 'set')(this.currentImgs, this.id, !!this.id);
		if (this.delegateMap.Thumbs)
			this.delegate('Thumbs', 'toggle')(this.currentImgs, true);
		if (isset(this.g_id) && this.g_id !== 0 && this.g_id !== 'all')
			this.filter();
	},
};

O_O.obj.inherit(O_O.lib.Controller, O_O.widget.SlideShowControls.Controller);

})(ps$);
(function($) {

O_O.widget.SlideShowControls.View = function($elem, props, controllerCb, env) {
	O_O.lib.View.apply(this, arguments);
};

O_O.widget.SlideShowControls.View.prototype = {
	startX: 0,
	startY: 0,
	endX: 0,
	endY: 0,
	isChromeOff: null,
	gallery: false,

	$meta: null,
	$share: null,
	$thumbs: null,
	$buy: null,
	isFullScreen: false,

	countData: {
		current: ' ',
		count: ' '
	},

	_init: function() {
		this._bindEvents();
	},
	render: function(gallery, skipInit)
	{
		var dfr = $.Deferred().resolve();
		if (typeof gallery !== 'undefined' && gallery)
			this.gallery = gallery;

		if (this.config.f_meta === 't' &&
			isset(this.config.f_meta_force_false_mobile) &&
			this.config.f_meta_force_false_mobile &&
			O_O.browser.getResponsiveState({stops: [768,1024,1365,1800]}) === 'handhelds' &&
			$('#c2').width < 768) {
				this.config.f_meta = 'f';
		}

		if (this.gallery) {
			this.tpl('main', {
				config: this.config,
				gallery: this.gallery,
				countData: this.countData
			}, scopeC(function(html){
				this._clearElem();
				this.$elem.append(html);
				this.$meta = this.$elem.find('.info');
				this.$share = this.$elem.find('.social');
				this.$thumbs = this.$elem.find('.thumbs');
				this.$buy = this.$elem.find('.buy');
				if (!isset(skipInit) || !!skipInit) {
					this._meta(true);
					this._thumbs(true);
					this._playState(false);
				}
				if (this.countData)
					this._updateButton('count', this.countData);
			}, this));
			/**
			 * Send gallery name to embedded iframe for accessibility
			 */
			this.targetWindow = window.parent;
			this.targetWindow.postMessage(this.gallery.name, '*');
		}

		return dfr.promise();
	},
	setImageSize: function(size) {
		this.$elem.attr('data-size', size);
	},
	_toggleChrome: function() {
		if (this.config.f_thumbs === 't' ||
				(this.config.f_meta === 't' &&
					O_O.browser.getResponsiveState() === 'handhelds'))
				return;
		if (this.isChromeOff) {
			this.isChromeOff = false;
			this.controllerCb('meta', this.config);
		} else {
			this.isChromeOff = true;
			this.controllerCb('meta', {f_meta: 'f'});
		}
		if ((C2_CFG.theme === 'Theme5' && $(document).width() < 1024)) {
			this.$elem.toggleClass('chrome-off', settings.isChromeOff);
		} 
		this.controllerCb('page', {isChromeOff: this.isChromeOff});
	},
	_changePage: function(e) {
		e.preventDefault();
		this.controllerCb('page', e.currentTarget.className);
	},
	_playState: function(toggle) {
		if (toggle) {
			if (this.config.f_play === 't') {
				this.config.f_play = 'f';
			} else {
				this.config.f_play = 't';
			}
			this._gaEvent('SlideShowControls', 'play',
				(this.config.f_play === 't') ? 'start' : 'stop');
		}
		this.$thumbs.removeClass('on');
		this.$share.removeClass('on');
		this._updateButton('play');
		this.controllerCb('play', this.config);
	},
	_stopPlaying: function() {
		this.config.f_play = 'f';
		this._updateButton('play');
	},
	_pausePlaying: function() {
		var state = this.config.f_play;
		this.config.f_play = 'f';
		this._updateButton('play');
		this.config.f_play = state;
	},
	_updateCount: function(data) {
		this.ids = data.ids;
		var oldCountData = this.countData;
		this.countData = data;
		this._updateButton('count', data);
		if (oldCountData.count !== data.count ||
			oldCountData.galName !== data.galName) {
			this.render(null,true);
		}
	},
	_meta: function(init) {
		if (init !== true && this.config.f_meta !== 'n' &&
			this.config.f_meta !== 'a') {
			this.$meta.toggleClass('on');
			if (this.config.f_meta === 'f')
				this.config.f_meta = 't';
			else
				this.config.f_meta = 'f';
			this._gaEvent('SlideShowControls', 'meta',
				(this.config.f_meta === 't') ? 'open' : 'close');
		}
		this.$share.removeClass('on');
		this.controllerCb('meta', this.config);
		if (init !== true && this.config.f_thumbs !== 'n' &&
			this.config.f_thumbs !== 'a') {
				this.config.f_thumbs = 'f';
		}
	},
	_thumbs: function(init) {
		if (init !== true && this.config.f_thumbs !== 'n' &&
				this.config.f_thumbs !== 'a') {
			this.$thumbs.toggleClass('on');
			if (this.config.f_thumbs === 'f')
				this.config.f_thumbs = 't';
			else
				this.config.f_thumbs = 'f';
			this._stopPlaying();
			this._gaEvent('SlideShowControls', 'thumbs',
				(this.config.f_thumbs === 't') ? 'open' : 'close');
			// HACK: Otis' architecture is much different than all other themes.
			if (C2_CFG.theme !== 'Otis')
				this.controllerCb('closeViewer', {});
		}
		if (this.$share)
			this.$share.removeClass('on');
		this.controllerCb('thumbs', {config: this.config, idx: this.countData.current-1});
	},
	_share: function() {
		this._gaEvent('SlideShowControls', 'share');
		this.$share.toggleClass('on');
		this._pausePlaying();
		this.controllerCb('share', {
			toggle: (this.config.f_share_what === 'image') ? true : null,
			id: (this.config.f_share_what === 'image') ? this.image_id : null
		});
	},
	_buy: function() {
		this._gaEvent('SlideShowControls', 'buy');
		this.$buy.toggleClass('on');
		this._pausePlaying();
		this.controllerCb('buy', {
			toggle: (this.config.buyWhat === 'image') ? true : null,
			id: (this.config.buyWhat === 'image') ? this.image_id : null
		});
	},
	_toggleBuy: function(f) {
		if (this.$buy === null) return;
		this.$buy.toggleClass('hidden', !f);
	},
	_close: function() {
		if (this._disabled) return;
		//when in mobile, if the meta is open, close it instead.
		if (O_O.browser.getResponsiveState() === 'handhelds' &&
			this.config.f_meta === 't' &&
				$('#c2').width < 768)
					return this._meta();
		this._cancelFullScreen();
		this._gaEvent('SlideShowControls', 'close');
		this.controllerCb('closeViewer', {});
	},
	_touchH: function(e) {
		e.stopPropagation();
		e.preventDefault();
		switch(e.type) {
		case 'touchstart':
			e.preventDefault();
			this.$elem.onC('touchmove touchend', '.controls button', this._touchH, this);
			this.startX = this._getPageX(e);
			this.startY = this._getPageY(e);
			break;
		case 'touchmove':
			e.preventDefault();
			break;
		case 'touchend':
			this.$elem.off('touchmove touchend', '.controls button');
			this.endX = this._getPageX(e);
			this.endY = this._getPageY(e);
			if(C2_CFG.theme === 'Theme10') {
				if(Math.abs(this.endX - this.startX) > 
				Math.abs(this.endY - this.startY)) {
					if (this.config.f_toggleChrome === 't')
						this._toggleChrome();
					else
						this._changePage(e);
				} else if(Math.abs(this.endX - this.startX) < 
						  Math.abs(this.endY - this. startY) && 
						  this.config.f_closeable === 't') {
							  $('.close').click();
							  $('#ubernav').toggleClass('fullscreen-mode', false);
							  $('#ubernav-block').toggleClass('fullscreen-mode', false);
							  $('.gallerySingleImage').toggleClass('fullscreen-img', false);
				} else if(Math.abs(this.endX - this.startX) < 1 && Math.abs(this.endY - this.startY) < 1) {
					$('.close').click();
					$('#ubernav').toggleClass('fullscreen-mode', false);
					$('#ubernav-block').toggleClass('fullscreen-mode', false);
				}
			} else if(C2_CFG.theme === 'Theme4' || C2_CFG.theme === 'Theme6' || C2_CFG.theme === 'Theme3' || C2_CFG.theme === 'Theme2') {
				if(this.isFullScreen) {
					if(Math.abs(this.endX - this.startX) < Math.abs(this.endY - this.startY)){
						this._iOSFullscren(false, false);
					} else if(Math.abs(this.endX - this.startX) > Math.abs(this.endY - this.startY)) {
						if(this.config.f_toggleChrome === 't' && C2_CFG.theme !== 'Theme2') 
							this._toggleChrome();
						//else
							//this._changePage(e);
					} else if(Math.abs(this.endX - this.startX) < 1 && Math.abs(this.endY - this.startY) < 1) {
						this._iOSFullscren(false, false);
					}
				} else if(!this.isFullScreen) {
					if(Math.abs(this.endX - this.startX) < 5) {
						if(this.config.f_toggleChrome === 't')
							this._toggleChrome();
						else
							this._changePage(e);
					}
				}
			} else if(C2_CFG.theme === 'Theme5') {
				if(Math.abs(this.endX - this.startX) < Math.abs(this.endY - this.startY) || Math.abs(this.endX - this.startX) < 1 && Math.abs(this.endY - this.startY) < 1) {
					$('.SlideShowControls').toggleClass('chrome-off');
					$('.ImageStage').toggleClass('chrome-off');
					$('#ubernav').toggle();
					$('#ubernav-block').toggle();
					$('#c2').toggleClass('fullscreen-mode');
				}
			}
			else {
				if(Math.abs(this.endX - this.startX) < 5) {
					if(this.config.f_toggleChrome === 't')
						this._toggleChrome();
					else
						this._changePage(e);
				}
			}
			break;
		}
		if (this.countData.count > 1)
			this.controllerCb('page', e);
	},
	_bindEvents: function() {
		this.$elem.onC('click', '.controls button', function(e) {
				this._gaEvent('SlideShowControls', 'page ' +
					e.currentTarget.className, 'overlay');
				this._changePage(e);
			}, this)
			.onC('click', '.count button', function(e) {
				this._gaEvent('SlideShowControls', 'page ' +
					e.currentTarget.className, 'button');
				this._changePage(e);
			}, this)
			.onC('touchstart', '.controls button', this._touchH, this)
			.onC('click', '.play', scopeC(function(e){
				e.preventDefault();
				this._playState(true);
			}, this), this)
			.onC('click', '.info', this._meta, this)
			.onC('click', '.archive', this._goToArchive, this)
			.onC('click', '.thumbs', this._thumbs, this)
			.onC('click', '.social', this._share, this)
			.onC('click', '.buy', this._buy, this)
			.onC('click', '.close', this._close, this)
			.onC('touchend', '.close', function(e) {
				e.preventDefault();
				this._close(e);
			}, this)
			.onC('click', '.fullscreen', this._toggleFullScreen, this);
	},
	_updateButton: function(button, config) {
		config = config || this.config;
		this.tpl(button, {
			config: this.config,
			countData: this.countData
		}, scopeC(function(html){
			this.$elem.find('.' + button).replaceWith(html);
		}, this));
	},

	_goToArchive: function() {
		this._gaEvent('SlideShowControls', 'archive');
		this._cancelFullScreen();
		var t = {
			id: isset(this.ids) ? this.ids.image_id : this.image_id
		};
		if (this.gallery && this.gallery.id) {
			t.g_id = this.gallery.id;
			t.g_name = this.gallery.name;
		}
		window.open(this.env('#c1_url', t),'_self',false);
	},

	//Utilities

	_getPageX: function(e) {
		if (typeof e.originalEvent.changedTouches !== 'undefined')
			return e.originalEvent.changedTouches[0].pageX;
		else
			return e.originalEvent.pageX;
	},

	_getPageY: function(e) {
		if (typeof e.originalEvent.changedTouches !== 'undefined')
			return e.originalEvent.changedTouches[0].pageY;
		else
			return e.originalEvent.pageY;
	},


	_toggleFullScreen: function(e) {
		var act = 'start';
		e.preventDefault();
		if(this._isFullscreen()) {
			act = 'end';
			this._cancelFullScreen();
		} else {
			this._requestFullScreen();
		}
		this._gaEvent('SlideShowControls', 'fullscreen', act);
	},
	_requestFullScreen: function() {
		var $el = this.$elem.closest('.fullscreen-target'),
			el = $el[0];
		if((!el.requestFullscreen && !el.webkitRequestFullScreen && !el.mozRequestFullScreen) || $(document).width() < 1024) {
			this._iOSFullscren(true, true)
		}
		else if (el.requestFullscreen) {
			el.requestFullscreen();
		} else if (el.webkitRequestFullScreen) {
			el.webkitRequestFullScreen();
		} else if (el.mozRequestFullScreen) {
			el.mozRequestFullScreen();
		} 
	},
	_cancelFullScreen: function() {
		if (document.webkitCancelFullScreen) {
			document.webkitCancelFullScreen();
		} else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		} else if(document.cancelFullScreen) {
			document.cancelFullScreen();
		}
	},
	_isFullscreen: function() {
		if (isset(document.webkitIsFullScreen))
			return document.webkitIsFullScreen;
		else if (isset(document.mozFullScreen))
			return document.mozFullScreen;
		else if (isset(document.fullscreen))
			return document.fullscreen;
		else return false;
	},

	_iOSFullscren: function(fullscreen, isFullScreen) {
		$(location).attr('href');
		if((C2_CFG.theme === 'Theme4' || C2_CFG.theme === 'Theme6' || C2_CFG.theme === 'Theme3' || C2_CFG.theme === 'Theme2')) {
			if(C2_CFG.theme === 'Theme3' || C2_CFG.theme === 'Theme2') {
				this._meta(false)
			}
 			$('nav').toggleClass('fullscreen-mode', fullscreen);
			$('#ubernav').toggleClass('fullscreen-mode', fullscreen);
			$('#ubernav-block').toggleClass('fullscreen-mode', fullscreen);
			$('header').toggleClass('fullscreen-mode', fullscreen);
			$('.SlideShowControls').toggleClass('fullscreen', fullscreen);
			$('footer').toggleClass('fullscreen-mode', fullscreen);
			$('.ImageStage').toggleClass('fullscreen-img', fullscreen);
			$('.MetaViewer').toggleClass('fullscreen', fullscreen)
			this.isFullScreen = isFullScreen; 
		}
	},

	/* event handlers */

	_disabled: null,

	disableLinks: function(f_disabled) {
		this._disabled = f_disabled;
	}
};

O_O.obj.inherit(O_O.lib.View, O_O.widget.SlideShowControls.View);

})(ps$);
;(function($, undefined) {
'use strict';

O_O.widget.ThumbViewer.Controller = function($elem, props, msgSys, env) {
	O_O.lib.Controller.call(this, $elem, props, msgSys, env);

	this.view = O_O.mm.oNew(O_O.widget.ThumbViewer.View, $elem, props,
		scopeC(this._controllerCb, this), env);
};

O_O.widget.ThumbViewer.Controller.prototype = {
	frozen: null,

	delegateInterfaces: {
		JumpTo: {
			required: false,
			functions: ['image']
		},
		Thumbs: {
			required: false,
			functions: ['toggle']
		}
	},

	implementInterfaces: {
		Thumbs: {
			toggle: function(galState, f) {
				if (isset(galState.galId) || isset(galState.id))
					this.toggle(galState, f);
				else
					this.toggleImgs(galState, f);
				if(f === false) this.freeze();
			},
			filter: function(g_id) {
				this.view.filter(g_id);
			}
		}
	},

	freeze: function() {
		O_O.lib.Controller.prototype.freeze.call(this);
		if (!this.frozen)
			this.view.freeze();
		this.frozen = true;
	},

	thaw: function() {
		O_O.lib.Controller.prototype.thaw.call(this);
		if (this.frozen)
			this.view.thaw();
		this.frozen = false;
	},

	render: function(config) {
		this.config = config;
		return new $.Deferred().resolve().promise();
	},

	toggle: function(galState, f) {
		if (!galState || (!galState.id && !galState.galId)) return;
		var galId = galState.galId || galState.id,
			gallery = O_O.model.get('Gallery', galId);
		this.clcId = galState.clcId;
		gallery.load().done(scopeC(function(galleryData){
			this.view.toggle(this.config, gallery, galleryData,
				galState.clcId, galState.idx, f);
		}, this));
	},

	toggleImgs: function(imgs, f) {
		this.view.toggleImages(this.config, imgs, f);
	},

	leaveThumbs: function(target, data) {
		if(typeof this.model !== 'undefined') {
			data = this.model.extractPrimitiveData();
			data.size = 'full';
			data.target = target;
			data.newStep = false;
			this.model.update(data);
		}
	},

	_setModel: function(d) {
		var model = d.model;
		this.model = this.model || O_O.model.get(model.type, model.id);
		this.model.sub(this._modelCB, this);
		this.id = 0;
	},

	_modelCB: function(d) {
		if(typeof d.current !== 'undefined') {
			var id = d.gals[d.current].id;
			if((this.id !== id && d.size ==='thumb') || d.size === 'thumb') {
				this.toggle({ galId: id });
				this.id = id;
			} else if (d.size !== 'thumb') {
				this.view.hide();
			}
		}
	},

	_controllerCb: function(data) {
		this.msgSys.pub('Shell', {msg: 'event', data: data});
		switch(data.type) {
		case 'imageOpen':
			var payload = {
				msg: 'closeThumbs',
				data: {}
			};
			this.msgSys.pub('SlideShowControls:Controller', payload);
			this.leaveThumbs(data.data.index);
			break;
		case 'modified':
			this.msgSys.pub('PageControl:Controller', {
				msg: 'modified',
				data: {}
			});
			break;
		}
	},

	_msgCb: function(channel, payload) {
		var d = payload.data;
		switch (payload.msg) {
		case 'event':
			return this._eventH(d.type, d.data);
		case 'useModel':
			this._setModel(d);
			break;
		}
	},

	_eventH: function(type, data) {
		switch(type) {
		case 'ImageViewer:home':
			this.view.hide();
			break;
		case 'imageOpen':
			if (this.delegateMap) {
				if (this.delegateMap.JumpTo)
					this.delegate('JumpTo', 'image')(data.index);
				if (this.delegateMap.Thumbs)
					this.delegate('Thumbs', 'toggle')();
			}
			break;
		case 'windowResize':
			this.view.resize(data);
			break;
		}
	}
};

O_O.obj.inherit(O_O.lib.Controller, O_O.widget.ThumbViewer.Controller);

}(ps$));
;(function($, undefined) {
'use strict';

O_O.widget.ThumbViewer.View = function($elem, props, controllerCb, env) {
	O_O.lib.View.call(this, $elem, props, controllerCb, env);
};

O_O.widget.ThumbViewer.View.prototype = {
	page: 0,
	totalImages: null,
	max: 50,
	canScroll: null,

	HEIGHTS: [],
	scrollbarWidth: O_O.browser.getScrollWidth(),
	transEndEventName: O_O.browser.transEndEventName(),

	$imgs: [],
	images: null,
	filterId: '*',
	bodyHeight: null,
	lazyThreshhold: 200,
	animId: null,
	noHide: false,

	$columns: null,

	f_active: false,

	_destroyNano: function() {
		if (this.$elem[0].nanoscroller && this.$elem[0].nanoscroller !== null) {
			this.$elem.nanoScroller({ stop: true });
			this.$elem[0].nanoscroller = null;
		}
	},
	_startIsotope: function() {
		var dataH, dataW, ratio, $img,
			$imgs = this.$elem.find('img');
		if (!isset(this.images) || this.images === null) return;
		for (var i = 0, ct = this.images.length; i < ct; i++) {
			$img = $($imgs[i]);
			dataH = $img.data('height');
			dataW = $img.data('width');
			ratio = dataH / dataW * 100;
			$img.parent().css('padding-bottom', ratio + '%');
		}
		this.$columns = this.$elem.find('.columns');
		this._destroyIsotope();
		this._setColumnsWidth();
		this.$columns.isotope({
			transitionDuration: 0,
			isResizeBound: false
		});
		this._setScrolling();
		this.beLazy();
	},
	_isIsotope: function() {
		return typeof this.$columns !== 'undefined' &&
			this.$columns !== null &&
			typeof this.$columns.data('isotope') !== 'undefined';
	},
	_destroyIsotope: function() {
		if (this._isIsotope()) {
			this.$columns.isotope('destroy');
		}
	},
	filter: function(g_id) {
		if (this._isIsotope()) {
			this.galleryData = {
				id: g_id
			};
			this.filterId = g_id === '*' ? '*' :
				'[data-gid="' + g_id + '"]';
			this.beLazy();
			this.$columns.isotope({
				filter: this.filterId,
				transitionDuration: '0.4s'
			});
		}
	},
	render: function(config, gallery, galleryData, idx) {
		if (gallery) this.gallery = gallery;
		if (galleryData) this.galleryData = galleryData;
		if (config)	{
			this.config = config;
			if (typeof this.config.pageCount === 'undefined')
				this.config.pageCount = this.max;
			if (typeof this.config.f_scrollbar !== 'undefined' &&
				!this.config.f_scrollbar)
				this.scrollbarWidth = 0;
			if (typeof this.config.f_layout === 'undefined')
				this.config.f_layout = 'j';
		}

		if (idx > -1 && this.config.pageCount > -1) this.page = Math.floor(idx/this.max);

		return this.tpl('main', {}, scopeC(function(html){
			this._clearElem();
			this.$elem.append(html);
			this.canScroll = 0;
			if (this.gallery) this.renderGallery(idx);
		}, this));
	},
	freeze: function() {
		this.f_active = false;
		this._unbindEvents();
		if (isset(this.config) && isset(this.config.f_layout) &&
				this.config.f_layout === 'm')
			this._destroyIsotope();
	},
	thaw: function() {
		if (!this.f_active) {
			this.f_active = true;
			this._bindEvents();
			if (isset(this.config) && isset(this.config.f_layout) &&
					this.config.f_layout === 'm') {
				this._startIsotope();
			}
			if (this.canScroll)
				this._setScrolling();
			this.beLazy();
		}
	},
	beLazy: function($html) {
		if (typeof $html === 'undefined') $html = this.$elem;
		this.$imgs = $html.find('img:not(.loaded,.loading)');
		if (this.$imgs.length > 0 &&
			!this.animId)
			this.animId = window.requestAnimationFrame(scopeC(this.animationTasks, this));
	},
	renderGallery: function(idx) {
		var galId = this.gallery._id.id;
		this.gallery.getImages()
			.done(scopeC(function(imageModels){
				//HACK: the returned imageModels have no context, so I have to
				//store the galId locally in order to prevent earlly requests from
				//overwriting late requests when they run slowly.
				if (galId !== this.gallery._id.id) return;
				this.renderImgs(imageModels, idx);
			}, this));
	},
	renderImgs: function(imageModels, idx, renderGID) {
		var images = [],
			width = this.config.f_layout === 'j' ? 1200 : 350,
			height = this.config.f_layout === 'j' ? 350 : 1200;
		if (this.config.f_layout === 's') {
			width = 350;
			height = 350;
		}
		this.totalImages = imageModels.length;
		for (var i = 0, count = imageModels.length; i < count; i++) {
			var img = imageModels[i],
				imgD = img.getImageModel().extractPrimitiveData();
			imgD.src = img.getLinkForSize({
						width: width,
						height: height,
						mode: this.config.f_layout === 's' ? 'fill' : 'fit'
					});
			imgD.g_id = imageModels[i].g_id;
			images.push(imgD);
		}
		this.images = images;
		return this.tpl('images', {
				images: images,
				page: this.page,
				start: this.page * this.config.pageCount,
				full: this.config.pageCount,
				max: this.config.pageCount > 0 ?
					this.config.pageCount:
					images.length,
				loading: this.LOADING_HTML,
				config: this.config,
				renderGID: renderGID
			}, scopeC(function(html, $content){
				if (this.config.f_layout === 'j')
					$content = this.justify($(html));
				else $content = $(html);
				this._clearElem();
				this.$elem.append($content);
				this.$imgs = [];
				if (this.config.f_layout === 'm' && this.f_active) {
					this._startIsotope();
				}
				this.canScroll = 1;

				// special behavior for Theme5/Sonnet
				if ($('.ThumbViewer + .GalleryViewer').length > 0) {
					this.thaw();
				}

				var thumb = $('a[data-index="'+idx+'"]');
				if (thumb.length) {
					// ensure current image thumb is visible
					var top = $(thumb).position().top;
					$('.scrollable', this.$elem).scrollTop(top - 10);
				}
				this.bodyHeight = $('body').height();
				this.controllerCb({type: 'modified'});
			}, this));
	},
	_setScrolling: function() {
		if (typeof this.config !== 'undefined' &&
				typeof this.config.f_innerScroll !== 'undefined' &&
				this.config.f_innerScroll) {
			this._destroyNano();
			this.$elem.nanoScroller({ iOSNativeScrolling: true });
		}
	},
	toggle: function(config, gallery, galleryData, clcId, idx, f) {
		if(typeof f === 'undefined') f = null;
		// special behavior for Theme5/Sonnet
		if ($('.ThumbViewer + .GalleryViewer').length > 0) {
			this.$elem.addClass('on', f);

			$('.style-select button').removeClass('active');
			$('.style-select .thumb').addClass('active');
			if (this.$elem.hasClass('on')) {
				this.beLazy();
			}
		} else {
			this.$elem.toggleClass('on', f);
		}

		if (this.gallery !== gallery || this.config !== config || this.galleryData !== galleryData || this.idx !== idx) {
			if (config.f_layout === 'm')
				this._destroyIsotope();
			this.render(config, gallery, galleryData, idx).done(scopeC(function() {
				if (f || this.$elem.hasClass('on')) this.thaw();
				else this.freeze();
			}, this));
		} else {
			if (f || this.$elem.hasClass('on')) this.thaw();
			else this.freeze();
		}
	},
	toggleImages: function(config, imgs, f) {
		this.noHide = true;
		if(typeof f === 'undefined') f = null;

		if (this.imgs !== imgs || this.config !== config) {
			this.imgs = imgs;
			this.config = config;
			this.renderImgs(imgs, 0, true).done(scopeC(function() {
				if (f) this.thaw();
				else this.freeze();
			}, this));
		} else {
			if (f) this.thaw();
			else this.freeze();
		}
	},
	hide: function() {
		if (!!this.noHide) return;
		this.$elem.removeClass('on');
		this.freeze();
	},
	_goToPage: function(page) {
		if(this.page !== page) {
			this.page = page;
			this.render();
		}
	},
	_pageCB: function(e) {
		e.preventDefault();
		var type = $(e.currentTarget).data('type'),
			page = this.page,
			lastPage = Math.ceil(this.totalImages/this.config.pageCount)-1;

		switch (type) {
		case 'prev':
			page--;
			if(page===-1) {
				page=lastPage;
			}
			break;
		case 'next':
			page++;
			if(page>lastPage) {
				page=0;
			}
			break;
		}
		this._goToPage(page);
	},
	_imgCB: function(e) {
		e.preventDefault();
		var $this = $(e.currentTarget),
			index = isset($this.data('id')) ? $this.data('id') : $this.data('index');
		this.page = 0;  // To reset thumbnail page on exit.
		this.controllerCb({
			type: 'imageOpen',
			data: {
				collection_id: this.clcId,
				gallery_id: isset(this.galleryData) ? this.galleryData.id : null,
				index: index
			}
		});
		this.hide();
	},
	_bindEvents: function() {
		this.$elem
			.onC('click', '.arrow', this._pageCB, this)
			.onC('click', 'a', this._imgCB, this)
			.onC('touchend', 'a', function(e) {
				this.endY = this._getPageY(e);
				if (Math.abs(this.endY - this.startY) < 10) {
					e.stopPropagation();
					this._imgCB(e);
				}
				this.startY = 0;
				this.endY = 0;
			}, this)
			.onC('touchstart', function(e) {
				this.startY = this._getPageY(e);
			}, this)
			.onC('touchstart touchmove', function(e){
				if (typeof this.config !== 'undefined' &&
					typeof this.config.f_innerScroll !== 'undefined' &&
					this.config.f_innerScroll) {
						e.stopPropagation();
				}
			}, this);
	},
	_unbindEvents: function() {
		this.$elem.off('click', '.arrow')
			.off('click', 'a');
	},

	_getheight: function(images, width, margin) {
		width -= images.length * margin;
		var h = 0;
		for (var i = 0; i < images.length; ++i) {
			h += $(images[i]).data('width') / $(images[i]).data('height');
		}
		return width / h;
	},

	setheight: function(images, height) {
		this.HEIGHTS.push(height);
		for (var i = 0; i < images.length; ++i) {
			$(images[i]).css({
				width: height * $(images[i]).data('width') / $(images[i]).data('height'),
				height: height
			});
		}
	},

	columnsCount: function(count, wResponse) {
		wResponse = O_O.browser.getResponsiveState({
			stops: [768,1024,1365,1800]
		});

		switch (wResponse) {
		case 'handhelds':
			count = 2;
			break;
		case 'tablets':
			count = 3;
			break;
		case 'medium-screens':
		case 'wide-screens':
			count = 5;
			break;
		case 'mega-screens':
			count = 7;
		}
		return count;
	},

	_setColumnsWidth: function(width, count, correction) {
		width = this.$elem.width();
		count = this.columnsCount();
		correction = width % count;
		if (!isset(this.$columns)) return;
		this.$columns.css('width',width - correction + 'px').parent()
			.css('padding-right', correction + 'px');
	},

	resize: function(data) {
		if (typeof this.config === 'undefined') return;
		this.bodyHeight = data.height;
		var size = this.$elem.width() - this.scrollbarWidth - 1;
		if (isset(this.config) && isset(this.config.f_layout) &&
				this.config.f_layout === 'j')
			this.rejustify(size);
		else if (isset(this.config) && isset(this.config.f_layout) &&
				this.config.f_layout === 'm') {
			this._setColumnsWidth();
			this._startIsotope();
		}
	},

	rejustify: function(size, $html) {
		if(size !== this.displayWidth) {
			$html = $(this.$elem.html());
			this.displayWidth = size;
			this.$elem.html(this.justify($html));
			this._setScrolling();
			this.controllerCb({type: 'modified'});
		}
	},

	justify: function($html, max_height) {
		this.displayWidth = this.displayWidth ||
			this.$elem.width() - this.scrollbarWidth - 1;
		var holder = this.$elem.find('.holder'),
			size = this.displayWidth -
				parseFloat(holder.css('padding-left')) -
				parseFloat(holder.css('padding-right')),
			margin = 0,
			$marginTest = $('<div class="holder"><a class="margin-test"/></div>');
		max_height = Math.max(100, Math.min(size/4, 350));
		var n = 0,
			images = $html.find('img'),
			slice = [],
			h = 0;
		this.$elem.append($marginTest);
		margin = parseFloat($marginTest.find('.margin-test').css('margin-right'));
		margin += parseFloat($marginTest.find('.margin-test').css('margin-left'));
		$marginTest.remove();
		w: while (images.length > 0) {
			for (var i = 1; i < images.length + 1; ++i) {
				slice = images.slice(0, i);
				h = this._getheight(slice, size, margin);
				if (h < max_height) {
					this.setheight(slice, h);
					n++;
					images = images.slice(i);
					continue w;
				}
			}
			scopeC(this.setheight(slice, Math.min(max_height, h)), this);
			n++;
			break;
		}

		this.beLazy($html);

		return $html;
	},

	loaded: function(e) {
		$(e.currentTarget).one(this.transEndEventName, function(e){
			e.preventDefault();
			e.stopPropagation();
		}).addClass('loaded');
	},

	lazyLoad: function() {
		var $img, dist = 0, skip = -1, loaded = 0, $skip;
		for(var i = 0, ct = this.$imgs.length; i < ct; i++) {
			$img = $(this.$imgs[i]);
			dist = $img[0].getBoundingClientRect().top;
			if (dist !== 0 &&
				dist > -2 * this.bodyHeight &&
				dist < this.bodyHeight + this.lazyThreshhold) {
				if (skip === -1) skip = i;
				$img.one('load', scopeC(this.loaded,this))
					.attr({
						'src': $img.data('src'),
						'class': 'loading'
					});
				loaded++;
			} else if (dist > this.bodyHeight + this.lazyThreshhold) {
				if (skip === -1) skip = i;
				break;
			}
		}
		if (i > 0) {
			$skip = this.$imgs.slice(0, skip === -1 ? Number.MAX_VALUE : skip);
			if (i === ct) {
				if (skip > 0 ||
					loaded === 0)
					this.$imgs = $skip;
				else
					this.$imgs = [];
			} else {
				this.$imgs = this.$imgs.slice(i);
				if(skip > 0)
					this.$imgs = $skip.add(this.$imgs);
			}
		}
	},

	animationTasks: function() {
		this.lazyLoad();

		if (!!this.f_active && this.$imgs.length > 0)
			this.animId = window.requestAnimationFrame(scopeC(this.animationTasks, this));
		else {
			this.animId = false;
			if (!!this.f_active)
				this.beLazy();
		}
	},

	_getPageY: function(e) {
		if (typeof e.originalEvent.changedTouches !== 'undefined')
			return e.originalEvent.changedTouches[0].pageY;
		else
			return e.originalEvent.pageY;
	}
};

O_O.obj.inherit(O_O.lib.View, O_O.widget.ThumbViewer.View);

}(ps$));
;(function($, undefined) {
'use strict';

O_O.widget.BuyMenu.Controller = function($elem, props, msgSys, env) {
	O_O.lib.Controller.apply(this, arguments);

	this.view = O_O.mm.oNew(O_O.widget.BuyMenu.View, $elem, props,
		scopeC(this._controllerCb, this), env);
};

O_O.widget.BuyMenu.Controller.prototype = {
	delegateInterfaces: {
		Pricing: {
			required: false,
			functions: ['toggle']
		}
	},

	implementInterfaces: {
		Buy: {
			toggle: function(f) {
				this.view.toggle(f);
				if (!this.written) this.writeDOM();
			}
		},
		ImageMeta: {
			load: function(image, gallery) {
				if (isset(gallery))
					this.view.gallery = gallery;
				this._setImage(image);
			}
		}
	},

	written: false,

	render: function(config) {
		this.config = config;
		return new $.Deferred().resolve().promise();
	},

	writeDOM: function() {
		this.written = true;
		return this.view.render(this.config, []);
	},

	_setImage: function(image) {
		this.image = image;
		if (isset(image.pricing)) {
			this.pricing = image.pricing;
			if (!isset(this.image._id) && isset(this.image.id))
				this.image._id = {
					image_id: this.image.id
				}
			this._writeImage();
			return;
		}
		this.image.getImageModel().load().done(scopeC(function(imageData){
			if (!isset(imageData.pricing)) {
				this.image.getImageModel().load({f_force:true}).done(scopeC(function(imageData){
					this.pricing = imageData.pricing;
					this._writeImage();
				}, this));
			} else {
				this.pricing = imageData.pricing;
				this._writeImage();
			}
		}, this));
	},

	_writeImage: function() {
		this.written = true;
		this.view.render(this.config, this.pricing, this.image._id);
	},

	_controllerCb: function(type, payload) {
		switch (type) {
		case 'close':
			payload = {
				msg: 'closeBuy',
				data: {}
			};
			this.msgSys.pub('SlideShowControls:Controller', payload);
			break;
		case 'pricing':
			if (this.delegateMap && this.delegateMap.Pricing)
				this.delegate('Pricing', 'toggle')(payload);
			break;
		case 'editWidget':
			return this.msgSys.pub('Shell', {
				msg: 'editWidget',
				data: {
					view: payload.view,
					cfgId: this.getCfg()
				}
			});
		}
	},

	/* unused functions (here to override abstract controller) */

	_eventH: null
};

O_O.obj.inherit(O_O.lib.Controller, O_O.widget.BuyMenu.Controller);

}(ps$));
;(function($, undefined) {
'use strict';

O_O.widget.BuyMenu.View = function($elem, props, controllerCb, env) {
	O_O.lib.View.apply(this, arguments);
};

O_O.widget.BuyMenu.View.prototype = {
	_init: function() {
		this._bindEvents();
	},
	render: function(config, pricing, id) {
		if (isset(config))
			this.config = config;
		if (isset(pricing))
			this.pricing = pricing;
		if (isset(id))
			this._id = id;
		this.cart = this.cart || O_O.model.get('Cart', 'Cart');
		return this.cart.load().then(scopeC(function(data){
			this.cartCount = data.item_count;
			return this.tpl('main', {
					config: this.config,
					pricing: this.pricing,
					cart: this.cartCount,
					find: function(priceType, prices) {
						for (var i = 0, len = prices.length; i < len; i++) {
							if (prices[i].type === priceType)
								return prices[i]; // Return as soon as the object is found
						}
						return false; // The object was not found
					}
				}, scopeC(function(html){
				this._clearElem(); // clear all but config
				this.$elem.append(html);
				this._setScrolling();
				this.controllerCb('pricing', this.pricing.length);
			}, this));
		}, this));
	},
	_setScrolling: function() {
		if (typeof this.config !== 'undefined' &&
				typeof this.config.f_innerScroll !== 'undefined' &&
				this.config.f_innerScroll) {
			this._destroyNano();
			this.$elem.find('.content').scrollTop(0);
			this.$elem.nanoScroller({ iOSNativeScrolling: true });
		}
	},
	_destroyNano: function() {
		if (this.$elem[0].nanoscroller && this.$elem[0].nanoscroller !== null) {
			this.$elem.nanoScroller({ stop: true });
			this.$elem[0].nanoscroller = null;
		}
	},
	toggle: function(f) {
		if (typeof f === 'undefined') f = null;
		if (!this.pricing.length) {
			this.controllerCb('pricing', this.pricing.length);
			return;
		}
		this.$elem.toggleClass('on', f);
		if (f === null || !!f) this.render();
	},
	_goToArchive: function(tab) {
		var t = {
				id: this._id.image_id,
				g_id: this._id.gallery_id || this.gallery.id
			},
			url = '';
		if (this.gallery && this.gallery.name) {
			t.g_name = this.gallery.name;
		}
		this._gaEvent('BuyMenu', tab.toUpperCase());
		url = this.env('custom').url +
			this.env('#c1_url', t) +
			'#cart/' +
			tab.toUpperCase() + '/' +
			t.g_id + '/' +
			t.id;
		window.open(url,'_self',false);
	},
	_bindEvents: function() {
		this.$elem
			.onC('touchstart touchmove', function(e){
				if (typeof this.config !== 'undefined' &&
					typeof this.config.f_innerScroll !== 'undefined' &&
					this.config.f_innerScroll)
						e.stopPropagation();
			}, this)
			.onC('click', '.close', function(e) {
				e.preventDefault();
				this._pageExit();
			}, this)
			.onC('click', function(e) {
				if (!this.config.f_closeable) return;
				if (e.target.className.search('widget') === -1 &&
					e.target.className.search('content') === -1) return;
				e.preventDefault();
				this._pageExit();
			}, this)
			.onC('click', 'a', function(e) {
				var cn = e.currentTarget.className;
				if (cn === 'cart')
					return;
				e.preventDefault();
				var exitEvent = (window.onpageshow || window.onpageshow === null) ?
					'pageshow' :
					'unload';
				$(window).oneC(exitEvent, function(){
					this._pageExit();
				}, this);
				this._goToArchive(cn);
			}, this);
	},
	_pageExit: function() {
		this._gaEvent('BuyMenu', 'close');
		this.toggle(false);
		this.controllerCb('close');
	}
};

O_O.obj.inherit(O_O.lib.View, O_O.widget.BuyMenu.View);

}(ps$));
/*! nanoScrollerJS - v0.7.5 - 2013
* http://jamesflorentino.github.com/nanoScrollerJS/
* Copyright (c) 2013 James Florentino; Licensed MIT */
(function($, window, document) {
  "use strict";
  var BROWSER_IS_IE7, BROWSER_SCROLLBAR_WIDTH, DOMSCROLL, DOWN, DRAG, KEYDOWN, KEYUP, MOUSEDOWN, MOUSEMOVE, MOUSEUP, MOUSEWHEEL, NanoScroll, PANEDOWN, RESIZE, SCROLL, SCROLLBAR, TOUCHMOVE, UP, WHEEL, cAF, defaults, getBrowserScrollbarWidth, hasTransform, isFFWithBuggyScrollbar, rAF, transform, _elementStyle, _prefixStyle, _vendor;
  defaults = {
    /**
      a classname for the pane element.
      @property paneClass
      @type String
      @default 'pane'
    */

    paneClass: 'pane',
    /**
      a classname for the slider element.
      @property sliderClass
      @type String
      @default 'slider'
    */

    sliderClass: 'slider',
    /**
      a classname for the content element.
      @property contentClass
      @type String
      @default 'content'
    */

    contentClass: 'content',
    /**
      a setting to enable native scrolling in iOS devices.
      @property iOSNativeScrolling
      @type Boolean
      @default false
    */

    iOSNativeScrolling: false,
    /**
      a setting to prevent the rest of the page being
      scrolled when user scrolls the `.content` element.
      @property preventPageScrolling
      @type Boolean
      @default false
    */

    preventPageScrolling: false,
    /**
      a setting to disable binding to the resize event.
      @property disableResize
      @type Boolean
      @default false
    */

    disableResize: false,
    /**
      a setting to make the scrollbar always visible.
      @property alwaysVisible
      @type Boolean
      @default false
    */

    alwaysVisible: false,
    /**
      a default timeout for the `flash()` method.
      @property flashDelay
      @type Number
      @default 1500
    */

    flashDelay: 1500,
    /**
      a minimum height for the `.slider` element.
      @property sliderMinHeight
      @type Number
      @default 20
    */

    sliderMinHeight: 20,
    /**
      a maximum height for the `.slider` element.
      @property sliderMaxHeight
      @type Number
      @default null
    */

    sliderMaxHeight: null,
    /**
      an alternate document context.
      @property documentContext
      @type Document
      @default null
    */

    documentContext: null,
    /**
      an alternate window context.
      @property windowContext
      @type Window
      @default null
    */

    windowContext: null
  };
  /**
    @property SCROLLBAR
    @type String
    @static
    @final
    @private
  */

  SCROLLBAR = 'scrollbar';
  /**
    @property SCROLL
    @type String
    @static
    @final
    @private
  */

  SCROLL = 'scroll';
  /**
    @property MOUSEDOWN
    @type String
    @final
    @private
  */

  MOUSEDOWN = 'mousedown';
  /**
    @property MOUSEMOVE
    @type String
    @static
    @final
    @private
  */

  MOUSEMOVE = 'mousemove';
  /**
    @property MOUSEWHEEL
    @type String
    @final
    @private
  */

  MOUSEWHEEL = 'mousewheel';
  /**
    @property MOUSEUP
    @type String
    @static
    @final
    @private
  */

  MOUSEUP = 'mouseup';
  /**
    @property RESIZE
    @type String
    @final
    @private
  */

  RESIZE = 'resize';
  /**
    @property DRAG
    @type String
    @static
    @final
    @private
  */

  DRAG = 'drag';
  /**
    @property UP
    @type String
    @static
    @final
    @private
  */

  UP = 'up';
  /**
    @property PANEDOWN
    @type String
    @static
    @final
    @private
  */

  PANEDOWN = 'panedown';
  /**
    @property DOMSCROLL
    @type String
    @static
    @final
    @private
  */

  DOMSCROLL = 'DOMMouseScroll';
  /**
    @property DOWN
    @type String
    @static
    @final
    @private
  */

  DOWN = 'down';
  /**
    @property WHEEL
    @type String
    @static
    @final
    @private
  */

  WHEEL = 'wheel';
  /**
    @property KEYDOWN
    @type String
    @static
    @final
    @private
  */

  KEYDOWN = 'keydown';
  /**
    @property KEYUP
    @type String
    @static
    @final
    @private
  */

  KEYUP = 'keyup';
  /**
    @property TOUCHMOVE
    @type String
    @static
    @final
    @private
  */

  TOUCHMOVE = 'touchmove';
  /**
    @property BROWSER_IS_IE7
    @type Boolean
    @static
    @final
    @private
  */

  BROWSER_IS_IE7 = window.navigator.appName === 'Microsoft Internet Explorer' && /msie 7./i.test(window.navigator.appVersion) && window.ActiveXObject;
  /**
    @property BROWSER_SCROLLBAR_WIDTH
    @type Number
    @static
    @default null
    @private
  */

  BROWSER_SCROLLBAR_WIDTH = null;
  rAF = window.requestAnimationFrame;
  cAF = window.cancelAnimationFrame;
  _elementStyle = document.createElement('div').style;
  _vendor = (function() {
    var i, transform, vendor, vendors, _i, _len;
    vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'];
    for (i = _i = 0, _len = vendors.length; _i < _len; i = ++_i) {
      vendor = vendors[i];
      transform = vendors[i] + 'ransform';
      if (transform in _elementStyle) {
        return vendors[i].substr(0, vendors[i].length - 1);
      }
    }
    return false;
  })();
  _prefixStyle = function(style) {
    if (_vendor === false) {
      return false;
    }
    if (_vendor === '') {
      return style;
    }
    return _vendor + style.charAt(0).toUpperCase() + style.substr(1);
  };
  transform = _prefixStyle('transform');
  hasTransform = transform !== false;
  /**
    Returns browser's native scrollbar width
    @method getBrowserScrollbarWidth
    @return {Number} the scrollbar width in pixels
    @static
    @private
  */

  getBrowserScrollbarWidth = function() {
    var outer, outerStyle, scrollbarWidth;
    outer = document.createElement('div');
    outerStyle = outer.style;
    outerStyle.position = 'absolute';
    outerStyle.width = '100px';
    outerStyle.height = '100px';
    outerStyle.overflow = SCROLL;
    outerStyle.top = '-9999px';
    document.body.appendChild(outer);
    scrollbarWidth = outer.offsetWidth - outer.clientWidth;
    document.body.removeChild(outer);
    return scrollbarWidth;
  };
  isFFWithBuggyScrollbar = function() {
    var isOSXFF, ua, version;
    ua = window.navigator.userAgent;
    isOSXFF = /(?=.+Mac OS X)(?=.+Firefox)/.test(ua);
    version = /Firefox\/\d{2}\./.exec(ua);
    if (version) {
      version = version[0].replace(/\D+/g, '');
    }
    return isOSXFF && +version > 23;
  };
  /**
    @class NanoScroll
    @param element {HTMLElement|Node} the main element
    @param options {Object} nanoScroller's options
    @constructor
  */

  NanoScroll = (function() {
    function NanoScroll(el, options) {
      this.el = el;
      this.options = options;
      BROWSER_SCROLLBAR_WIDTH || (BROWSER_SCROLLBAR_WIDTH = getBrowserScrollbarWidth());
      this.$el = $(this.el);
      this.doc = $(this.options.documentContext || document);
      this.win = $(this.options.windowContext || window);
      this.$content = this.$el.children("." + options.contentClass);
      this.$content.attr('tabindex', this.options.tabIndex || 0);
      this.content = this.$content[0];
      if (this.options.iOSNativeScrolling && (this.el.style.WebkitOverflowScrolling != null)) {
        this.nativeScrolling();
      } else {
        this.generate();
      }
      this.createEvents();
      this.addEvents();
      this.reset();
    }

    /**
      Prevents the rest of the page being scrolled
      when user scrolls the `.content` element.
      @method preventScrolling
      @param event {Event}
      @param direction {String} Scroll direction (up or down)
      @private
    */


    NanoScroll.prototype.preventScrolling = function(e, direction) {
      if (!this.isActive) {
        return;
      }
      if (e.type === DOMSCROLL) {
        if (direction === DOWN && e.originalEvent.detail > 0 || direction === UP && e.originalEvent.detail < 0) {
          e.preventDefault();
        }
      } else if (e.type === MOUSEWHEEL) {
        if (!e.originalEvent || !e.originalEvent.wheelDelta) {
          return;
        }
        if (direction === DOWN && e.originalEvent.wheelDelta < 0 || direction === UP && e.originalEvent.wheelDelta > 0) {
          e.preventDefault();
        }
      }
    };

    /**
      Enable iOS native scrolling
      @method nativeScrolling
      @private
    */


    NanoScroll.prototype.nativeScrolling = function() {
      this.$content.css({
        WebkitOverflowScrolling: 'touch'
      });
      this.iOSNativeScrolling = true;
      this.isActive = true;
    };

    /**
      Updates those nanoScroller properties that
      are related to current scrollbar position.
      @method updateScrollValues
      @private
    */


    NanoScroll.prototype.updateScrollValues = function() {
      var content;
      content = this.content;
      this.maxScrollTop = content.scrollHeight - content.clientHeight;
      this.prevScrollTop = this.contentScrollTop || 0;
      this.contentScrollTop = content.scrollTop;
      if (!this.iOSNativeScrolling) {
        this.maxSliderTop = this.paneHeight - this.sliderHeight;
        this.sliderTop = this.maxScrollTop === 0 ? 0 : this.contentScrollTop * this.maxSliderTop / this.maxScrollTop;
      }
    };

    /**
      Updates CSS styles for current scroll position.
      Uses CSS 2d transfroms and `window.requestAnimationFrame` if available.
      @method setOnScrollStyles
      @private
    */


    NanoScroll.prototype.setOnScrollStyles = function() {
      var cssValue,
        _this = this;
      if (hasTransform) {
        cssValue = {};
        cssValue[transform] = "translate(0, " + this.sliderTop + "px)";
      } else {
        cssValue = {
          top: this.sliderTop
        };
      }
      if (rAF) {
        if (!this.scrollRAF) {
          this.scrollRAF = rAF(function() {
            _this.scrollRAF = null;
            _this.slider.css(cssValue);
          });
        }
      } else {
        this.slider.css(cssValue);
      }
    };

    /**
      Creates event related methods
      @method createEvents
      @private
    */


    NanoScroll.prototype.createEvents = function() {
      var _this = this;
      this.events = {
        down: function(e) {
          _this.isBeingDragged = true;
          _this.offsetY = e.pageY - _this.slider.offset().top;
          _this.pane.addClass('active');
          _this.doc.bind(MOUSEMOVE, _this.events[DRAG]).bind(MOUSEUP, _this.events[UP]);
          return false;
        },
        drag: function(e) {
          _this.sliderY = e.pageY - _this.$el.offset().top - _this.offsetY;
          _this.scroll();
          _this.updateScrollValues();
          if (_this.contentScrollTop >= _this.maxScrollTop && _this.prevScrollTop !== _this.maxScrollTop) {
            _this.$el.trigger('scrollend');
          } else if (_this.contentScrollTop === 0 && _this.prevScrollTop !== 0) {
            _this.$el.trigger('scrolltop');
          }
          return false;
        },
        up: function(e) {
          _this.isBeingDragged = false;
          _this.pane.removeClass('active');
          _this.doc.unbind(MOUSEMOVE, _this.events[DRAG]).unbind(MOUSEUP, _this.events[UP]);
          return false;
        },
        resize: function(e) {
          _this.reset();
        },
        panedown: function(e) {
          _this.sliderY = (e.offsetY || e.originalEvent.layerY) - (_this.sliderHeight * 0.5);
          _this.scroll();
          _this.events.down(e);
          return false;
        },
        scroll: function(e) {
          if (_this.isBeingDragged) {
            return;
          }
          _this.updateScrollValues();
          if (!_this.iOSNativeScrolling) {
            _this.setOnScrollStyles();
          }
          if (e == null) {
            return;
          }
          if (_this.contentScrollTop >= _this.maxScrollTop) {
            if (_this.options.preventPageScrolling) {
              _this.preventScrolling(e, DOWN);
            }
            if (_this.prevScrollTop !== _this.maxScrollTop) {
              _this.$el.trigger('scrollend');
            }
          } else if (_this.contentScrollTop === 0) {
            if (_this.options.preventPageScrolling) {
              _this.preventScrolling(e, UP);
            }
            if (_this.prevScrollTop !== 0) {
              _this.$el.trigger('scrolltop');
            }
          }
        },
        wheel: function(e) {
          var delta;
          if (e == null) {
            return;
          }
          delta = e.delta || e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail || (e.originalEvent && -e.originalEvent.detail);
          if (delta) {
            _this.sliderY += -delta / 3;
          }
          _this.scroll();
          return false;
        }
      };
    };

    /**
      Adds event listeners with jQuery.
      @method addEvents
      @private
    */


    NanoScroll.prototype.addEvents = function() {
      var events;
      this.removeEvents();
      events = this.events;
      if (!this.options.disableResize) {
        this.win.bind(RESIZE, events[RESIZE]);
      }
      if (!this.iOSNativeScrolling) {
        this.slider.bind(MOUSEDOWN, events[DOWN]);
        this.pane.bind(MOUSEDOWN, events[PANEDOWN]).bind("" + MOUSEWHEEL + " " + DOMSCROLL, events[WHEEL]);
      }
      this.$content.bind("" + SCROLL + " " + MOUSEWHEEL + " " + DOMSCROLL + " " + TOUCHMOVE, events[SCROLL]);
    };

    /**
      Removes event listeners with jQuery.
      @method removeEvents
      @private
    */


    NanoScroll.prototype.removeEvents = function() {
      var events;
      events = this.events;
      this.win.unbind(RESIZE, events[RESIZE]);
      if (!this.iOSNativeScrolling) {
        this.slider.unbind();
        this.pane.unbind();
      }
      this.$content.unbind("" + SCROLL + " " + MOUSEWHEEL + " " + DOMSCROLL + " " + TOUCHMOVE, events[SCROLL]);
    };

    /**
      Generates nanoScroller's scrollbar and elements for it.
      @method generate
      @chainable
      @private
    */


    NanoScroll.prototype.generate = function() {
      var contentClass, cssRule, currentPadding, options, paneClass, sliderClass;
      options = this.options;
      paneClass = options.paneClass, sliderClass = options.sliderClass, contentClass = options.contentClass;
      if (!this.$el.find("." + paneClass).length && !this.$el.find("." + sliderClass).length) {
        this.$el.append("<div class=\"" + paneClass + "\"><div class=\"" + sliderClass + "\" /></div>");
      }
      this.pane = this.$el.children("." + paneClass);
      this.slider = this.pane.find("." + sliderClass);
      if (BROWSER_SCROLLBAR_WIDTH === 0 && isFFWithBuggyScrollbar()) {
        currentPadding = window.getComputedStyle(this.content, null).getPropertyValue('padding-right').replace(/\D+/g, '');
        cssRule = {
          right: -14,
          paddingRight: +currentPadding + 14
        };
      } else if (BROWSER_SCROLLBAR_WIDTH) {
        if (isFFWithBuggyScrollbar()) BROWSER_SCROLLBAR_WIDTH = Math.max(BROWSER_SCROLLBAR_WIDTH, 14);
        cssRule = {
          right: -BROWSER_SCROLLBAR_WIDTH
        };
        this.$el.addClass('has-scrollbar');
      }
      if (cssRule != null) {
        this.$content.css(cssRule);
      }
      return this;
    };

    /**
      @method restore
      @private
    */


    NanoScroll.prototype.restore = function() {
      this.stopped = false;
      if (!this.iOSNativeScrolling) {
        this.pane.show();
      }
      this.addEvents();
    };

    /**
      Resets nanoScroller's scrollbar.
      @method reset
      @chainable
      @example
          $(".nano").nanoScroller();
    */


    NanoScroll.prototype.reset = function() {
      var content, contentHeight, contentStyle, contentStyleOverflowY, paneBottom, paneHeight, paneOuterHeight, paneTop, parentMaxHeight, sliderHeight;
      if (this.iOSNativeScrolling) {
        this.contentHeight = this.content.scrollHeight;
        return;
      }
      if (!this.$el.find("." + this.options.paneClass).length) {
        this.generate().stop();
      }
      if (this.stopped) {
        this.restore();
      }
      content = this.content;
      contentStyle = content.style;
      contentStyleOverflowY = contentStyle.overflowY;
      if (BROWSER_IS_IE7) {
        this.$content.css({
          height: this.$content.height()
        });
      }
      contentHeight = content.scrollHeight + BROWSER_SCROLLBAR_WIDTH;
      parentMaxHeight = parseInt(this.$el.css("max-height"), 10);
      if (parentMaxHeight > 0) {
        this.$el.height("");
        this.$el.height(content.scrollHeight > parentMaxHeight ? parentMaxHeight : content.scrollHeight);
      }
      paneHeight = this.pane.outerHeight(false);
      paneTop = parseInt(this.pane.css('top'), 10);
      paneBottom = parseInt(this.pane.css('bottom'), 10);
      paneOuterHeight = paneHeight + paneTop + paneBottom;
      sliderHeight = Math.round(paneOuterHeight / contentHeight * paneOuterHeight);
      if (sliderHeight < this.options.sliderMinHeight) {
        sliderHeight = this.options.sliderMinHeight;
      } else if ((this.options.sliderMaxHeight != null) && sliderHeight > this.options.sliderMaxHeight) {
        sliderHeight = this.options.sliderMaxHeight;
      }
      if (contentStyleOverflowY === SCROLL && contentStyle.overflowX !== SCROLL) {
        sliderHeight += BROWSER_SCROLLBAR_WIDTH;
      }
      this.maxSliderTop = paneOuterHeight - sliderHeight;
      this.contentHeight = contentHeight;
      this.paneHeight = paneHeight;
      this.paneOuterHeight = paneOuterHeight;
      this.sliderHeight = sliderHeight;
      this.slider.height(sliderHeight);
      this.events.scroll();
      this.pane.show();
      this.isActive = true;
      if ((content.scrollHeight === content.clientHeight) || (this.pane.outerHeight(true) >= content.scrollHeight && contentStyleOverflowY !== SCROLL)) {
        this.pane.hide();
        this.isActive = false;
      } else if (this.el.clientHeight === content.scrollHeight && contentStyleOverflowY === SCROLL) {
        this.slider.hide();
      } else {
        this.slider.show();
      }
      this.pane.css({
        opacity: (this.options.alwaysVisible ? 1 : ''),
        visibility: (this.options.alwaysVisible ? 'visible' : '')
      });
      return this;
    };

    /**
      @method scroll
      @private
      @example
          $(".nano").nanoScroller({ scroll: 'top' });
    */


    NanoScroll.prototype.scroll = function() {
      if (!this.isActive) {
        return;
      }
      this.sliderY = Math.max(0, this.sliderY);
      this.sliderY = Math.min(this.maxSliderTop, this.sliderY);
      this.$content.scrollTop((this.paneHeight - this.contentHeight + BROWSER_SCROLLBAR_WIDTH) * this.sliderY / this.maxSliderTop * -1);
      if (!this.iOSNativeScrolling) {
        this.setOnScrollStyles();
      }
      return this;
    };

    /**
      Scroll at the bottom with an offset value
      @method scrollBottom
      @param offsetY {Number}
      @chainable
      @example
          $(".nano").nanoScroller({ scrollBottom: value });
    */


    NanoScroll.prototype.scrollBottom = function(offsetY) {
      if (!this.isActive) {
        return;
      }
      this.reset();
      this.$content.scrollTop(this.contentHeight - this.$content.height() - offsetY).trigger(MOUSEWHEEL);
      return this;
    };

    /**
      Scroll at the top with an offset value
      @method scrollTop
      @param offsetY {Number}
      @chainable
      @example
          $(".nano").nanoScroller({ scrollTop: value });
    */


    NanoScroll.prototype.scrollTop = function(offsetY) {
      if (!this.isActive) {
        return;
      }
      this.reset();
      this.$content.scrollTop(+offsetY).trigger(MOUSEWHEEL);
      return this;
    };

    /**
      Scroll to an element
      @method scrollTo
      @param node {Node} A node to scroll to.
      @chainable
      @example
          $(".nano").nanoScroller({ scrollTo: $('#a_node') });
    */


    NanoScroll.prototype.scrollTo = function(node) {
      if (!this.isActive) {
        return;
      }
      this.reset();
      this.scrollTop($(node).get(0).offsetTop);
      return this;
    };

    /**
      To stop the operation.
      This option will tell the plugin to disable all event bindings and hide the gadget scrollbar from the UI.
      @method stop
      @chainable
      @example
          $(".nano").nanoScroller({ stop: true });
    */


    NanoScroll.prototype.stop = function() {
      if (cAF) {
        cAF(this.scrollRAF);
      }
      this.stopped = true;
      this.removeEvents();
      if (!this.iOSNativeScrolling) {
        this.pane.hide();
      }
      return this;
    };

    /**
      Destroys nanoScroller and restores browser's native scrollbar.
      @method destroy
      @chainable
      @example
          $(".nano").nanoScroller({ destroy: true });
    */


    NanoScroll.prototype.destroy = function() {
      if (!this.stopped) {
        this.stop();
      }
      if (!this.iOSNativeScrolling && this.pane.length) {
        this.pane.remove();
      }
      if (BROWSER_IS_IE7) {
        this.$content.height('');
      }
      this.$content.removeAttr('tabindex');
      if (this.$el.hasClass('has-scrollbar')) {
        this.$el.removeClass('has-scrollbar');
        this.$content.css({
          right: ''
        });
      }
      return this;
    };

    /**
      To flash the scrollbar gadget for an amount of time defined in plugin settings (defaults to 1,5s).
      Useful if you want to show the user (e.g. on pageload) that there is more content waiting for him.
      @method flash
      @chainable
      @example
          $(".nano").nanoScroller({ flash: true });
    */


    NanoScroll.prototype.flash = function() {
      var _this = this;
      if (this.iOSNativeScrolling) {
        return;
      }
      if (!this.isActive) {
        return;
      }
      this.reset();
      this.pane.addClass('flashed');
      setTimeout(function() {
        _this.pane.removeClass('flashed');
      }, this.options.flashDelay);
      return this;
    };

    return NanoScroll;

  })();
  $.fn.nanoScroller = function(settings) {
    return this.each(function() {
      var options, scrollbar;
      if (!(scrollbar = this.nanoscroller)) {
        options = $.extend({}, defaults, settings);
        this.nanoscroller = scrollbar = new NanoScroll(this, options);
      }
      if (settings && typeof settings === "object") {
        $.extend(scrollbar.options, settings);
        if (settings.scrollBottom) {
          return scrollbar.scrollBottom(settings.scrollBottom);
        }
        if (settings.scrollTop) {
          return scrollbar.scrollTop(settings.scrollTop);
        }
        if (settings.scrollTo) {
          return scrollbar.scrollTo(settings.scrollTo);
        }
        if (settings.scroll === 'bottom') {
          return scrollbar.scrollBottom(0);
        }
        if (settings.scroll === 'top') {
          return scrollbar.scrollTop(0);
        }
        if (settings.scroll && settings.scroll instanceof $) {
          return scrollbar.scrollTo(settings.scroll);
        }
        if (settings.stop) {
          return scrollbar.stop();
        }
        if (settings.destroy) {
          return scrollbar.destroy();
        }
        if (settings.flash) {
          return scrollbar.flash();
        }
      }
      return scrollbar.reset();
    });
  };
  $.fn.nanoScroller.Constructor = NanoScroll;
})(jQuery, window, document);/*!
* ZeroClipboard
* The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface.
* Copyright (c) 2014 Jon Rohan, James M. Greene
* Licensed MIT
* http://zeroclipboard.org/
* v1.3.5
*/
!function(a){"use strict";function b(a){return a.replace(/,/g,".").replace(/[^0-9\.]/g,"")}function c(a){return parseFloat(b(a))>=10}var d,e={bridge:null,version:"0.0.0",disabled:null,outdated:null,ready:null},f={},g=0,h={},i=0,j={},k=null,l=null,m=function(){var a,b,c,d,e="ZeroClipboard.swf";if(document.currentScript&&(d=document.currentScript.src));else{var f=document.getElementsByTagName("script");if("readyState"in f[0])for(a=f.length;a--&&("interactive"!==f[a].readyState||!(d=f[a].src)););else if("loading"===document.readyState)d=f[f.length-1].src;else{for(a=f.length;a--;){if(c=f[a].src,!c){b=null;break}if(c=c.split("#")[0].split("?")[0],c=c.slice(0,c.lastIndexOf("/")+1),null==b)b=c;else if(b!==c){b=null;break}}null!==b&&(d=b)}}return d&&(d=d.split("#")[0].split("?")[0],e=d.slice(0,d.lastIndexOf("/")+1)+e),e}(),n=function(){var a=/\-([a-z])/g,b=function(a,b){return b.toUpperCase()};return function(c){return c.replace(a,b)}}(),o=function(b,c){var d,e,f;return a.getComputedStyle?d=a.getComputedStyle(b,null).getPropertyValue(c):(e=n(c),d=b.currentStyle?b.currentStyle[e]:b.style[e]),"cursor"!==c||d&&"auto"!==d||(f=b.tagName.toLowerCase(),"a"!==f)?d:"pointer"},p=function(b){b||(b=a.event);var c;this!==a?c=this:b.target?c=b.target:b.srcElement&&(c=b.srcElement),K.activate(c)},q=function(a,b,c){a&&1===a.nodeType&&(a.addEventListener?a.addEventListener(b,c,!1):a.attachEvent&&a.attachEvent("on"+b,c))},r=function(a,b,c){a&&1===a.nodeType&&(a.removeEventListener?a.removeEventListener(b,c,!1):a.detachEvent&&a.detachEvent("on"+b,c))},s=function(a,b){if(!a||1!==a.nodeType)return a;if(a.classList)return a.classList.contains(b)||a.classList.add(b),a;if(b&&"string"==typeof b){var c=(b||"").split(/\s+/);if(1===a.nodeType)if(a.className){for(var d=" "+a.className+" ",e=a.className,f=0,g=c.length;g>f;f++)d.indexOf(" "+c[f]+" ")<0&&(e+=" "+c[f]);a.className=e.replace(/^\s+|\s+$/g,"")}else a.className=b}return a},t=function(a,b){if(!a||1!==a.nodeType)return a;if(a.classList)return a.classList.contains(b)&&a.classList.remove(b),a;if(b&&"string"==typeof b||void 0===b){var c=(b||"").split(/\s+/);if(1===a.nodeType&&a.className)if(b){for(var d=(" "+a.className+" ").replace(/[\n\t]/g," "),e=0,f=c.length;f>e;e++)d=d.replace(" "+c[e]+" "," ");a.className=d.replace(/^\s+|\s+$/g,"")}else a.className=""}return a},u=function(){var a,b,c,d=1;return"function"==typeof document.body.getBoundingClientRect&&(a=document.body.getBoundingClientRect(),b=a.right-a.left,c=document.body.offsetWidth,d=Math.round(b/c*100)/100),d},v=function(b,c){var d={left:0,top:0,width:0,height:0,zIndex:B(c)-1};if(b.getBoundingClientRect){var e,f,g,h=b.getBoundingClientRect();"pageXOffset"in a&&"pageYOffset"in a?(e=a.pageXOffset,f=a.pageYOffset):(g=u(),e=Math.round(document.documentElement.scrollLeft/g),f=Math.round(document.documentElement.scrollTop/g));var i=document.documentElement.clientLeft||0,j=document.documentElement.clientTop||0;d.left=h.left+e-i,d.top=h.top+f-j,d.width="width"in h?h.width:h.right-h.left,d.height="height"in h?h.height:h.bottom-h.top}return d},w=function(a,b){var c=null==b||b&&b.cacheBust===!0&&b.useNoCache===!0;return c?(-1===a.indexOf("?")?"?":"&")+"noCache="+(new Date).getTime():""},x=function(b){var c,d,e,f=[],g=[],h=[];if(b.trustedOrigins&&("string"==typeof b.trustedOrigins?g.push(b.trustedOrigins):"object"==typeof b.trustedOrigins&&"length"in b.trustedOrigins&&(g=g.concat(b.trustedOrigins))),b.trustedDomains&&("string"==typeof b.trustedDomains?g.push(b.trustedDomains):"object"==typeof b.trustedDomains&&"length"in b.trustedDomains&&(g=g.concat(b.trustedDomains))),g.length)for(c=0,d=g.length;d>c;c++)if(g.hasOwnProperty(c)&&g[c]&&"string"==typeof g[c]){if(e=E(g[c]),!e)continue;if("*"===e){h=[e];break}h.push.apply(h,[e,"//"+e,a.location.protocol+"//"+e])}return h.length&&f.push("trustedOrigins="+encodeURIComponent(h.join(","))),"string"==typeof b.jsModuleId&&b.jsModuleId&&f.push("jsModuleId="+encodeURIComponent(b.jsModuleId)),f.join("&")},y=function(a,b,c){if("function"==typeof b.indexOf)return b.indexOf(a,c);var d,e=b.length;for("undefined"==typeof c?c=0:0>c&&(c=e+c),d=c;e>d;d++)if(b.hasOwnProperty(d)&&b[d]===a)return d;return-1},z=function(a){if("string"==typeof a)throw new TypeError("ZeroClipboard doesn't accept query strings.");return a.length?a:[a]},A=function(b,c,d,e){e?a.setTimeout(function(){b.apply(c,d)},0):b.apply(c,d)},B=function(a){var b,c;return a&&("number"==typeof a&&a>0?b=a:"string"==typeof a&&(c=parseInt(a,10))&&!isNaN(c)&&c>0&&(b=c)),b||("number"==typeof N.zIndex&&N.zIndex>0?b=N.zIndex:"string"==typeof N.zIndex&&(c=parseInt(N.zIndex,10))&&!isNaN(c)&&c>0&&(b=c)),b||0},C=function(a,b){if(a&&b!==!1&&"undefined"!=typeof console&&console&&(console.warn||console.log)){var c="`"+a+"` is deprecated. See docs for more info:\n    https://github.com/zeroclipboard/zeroclipboard/blob/master/docs/instructions.md#deprecations";console.warn?console.warn(c):console.log(c)}},D=function(){var a,b,c,d,e,f,g=arguments[0]||{};for(a=1,b=arguments.length;b>a;a++)if(null!=(c=arguments[a]))for(d in c)if(c.hasOwnProperty(d)){if(e=g[d],f=c[d],g===f)continue;void 0!==f&&(g[d]=f)}return g},E=function(a){if(null==a||""===a)return null;if(a=a.replace(/^\s+|\s+$/g,""),""===a)return null;var b=a.indexOf("//");a=-1===b?a:a.slice(b+2);var c=a.indexOf("/");return a=-1===c?a:-1===b||0===c?null:a.slice(0,c),a&&".swf"===a.slice(-4).toLowerCase()?null:a||null},F=function(){var a=function(a,b){var c,d,e;if(null!=a&&"*"!==b[0]&&("string"==typeof a&&(a=[a]),"object"==typeof a&&"length"in a))for(c=0,d=a.length;d>c;c++)if(a.hasOwnProperty(c)&&(e=E(a[c]))){if("*"===e){b.length=0,b.push("*");break}-1===y(e,b)&&b.push(e)}},b={always:"always",samedomain:"sameDomain",never:"never"};return function(c,d){var e,f=d.allowScriptAccess;if("string"==typeof f&&(e=f.toLowerCase())&&/^always|samedomain|never$/.test(e))return b[e];var g=E(d.moviePath);null===g&&(g=c);var h=[];a(d.trustedOrigins,h),a(d.trustedDomains,h);var i=h.length;if(i>0){if(1===i&&"*"===h[0])return"always";if(-1!==y(c,h))return 1===i&&c===g?"sameDomain":"always"}return"never"}}(),G=function(a){if(null==a)return[];if(Object.keys)return Object.keys(a);var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},H=function(a){if(a)for(var b in a)a.hasOwnProperty(b)&&delete a[b];return a},I=function(){try{return document.activeElement}catch(a){}return null},J=function(){var a=!1;if("boolean"==typeof e.disabled)a=e.disabled===!1;else{if("function"==typeof ActiveXObject)try{new ActiveXObject("ShockwaveFlash.ShockwaveFlash")&&(a=!0)}catch(b){}!a&&navigator.mimeTypes["application/x-shockwave-flash"]&&(a=!0)}return a},K=function(a,b){return this instanceof K?(this.id=""+g++,h[this.id]={instance:this,elements:[],handlers:{}},a&&this.clip(a),"undefined"!=typeof b&&(C("new ZeroClipboard(elements, options)",N.debug),K.config(b)),this.options=K.config(),"boolean"!=typeof e.disabled&&(e.disabled=!J()),e.disabled===!1&&e.outdated!==!0&&null===e.bridge&&(e.outdated=!1,e.ready=!1,O()),void 0):new K(a,b)};K.prototype.setText=function(a){return a&&""!==a&&(f["text/plain"]=a,e.ready===!0&&e.bridge&&"function"==typeof e.bridge.setText?e.bridge.setText(a):e.ready=!1),this},K.prototype.setSize=function(a,b){return e.ready===!0&&e.bridge&&"function"==typeof e.bridge.setSize?e.bridge.setSize(a,b):e.ready=!1,this};var L=function(a){e.ready===!0&&e.bridge&&"function"==typeof e.bridge.setHandCursor?e.bridge.setHandCursor(a):e.ready=!1};K.prototype.destroy=function(){this.unclip(),this.off(),delete h[this.id]};var M=function(){var a,b,c,d=[],e=G(h);for(a=0,b=e.length;b>a;a++)c=h[e[a]].instance,c&&c instanceof K&&d.push(c);return d};K.version="1.3.5";var N={swfPath:m,trustedDomains:a.location.host?[a.location.host]:[],cacheBust:!0,forceHandCursor:!1,zIndex:999999999,debug:!0,title:null,autoActivate:!0};K.config=function(a){"object"==typeof a&&null!==a&&D(N,a);{if("string"!=typeof a||!a){var b={};for(var c in N)N.hasOwnProperty(c)&&(b[c]="object"==typeof N[c]&&null!==N[c]?"length"in N[c]?N[c].slice(0):D({},N[c]):N[c]);return b}if(N.hasOwnProperty(a))return N[a]}},K.destroy=function(){K.deactivate();for(var a in h)if(h.hasOwnProperty(a)&&h[a]){var b=h[a].instance;b&&"function"==typeof b.destroy&&b.destroy()}var c=P(e.bridge);c&&c.parentNode&&(c.parentNode.removeChild(c),e.ready=null,e.bridge=null)},K.activate=function(a){d&&(t(d,N.hoverClass),t(d,N.activeClass)),d=a,s(a,N.hoverClass),Q();var b=N.title||a.getAttribute("title");if(b){var c=P(e.bridge);c&&c.setAttribute("title",b)}var f=N.forceHandCursor===!0||"pointer"===o(a,"cursor");L(f)},K.deactivate=function(){var a=P(e.bridge);a&&(a.style.left="0px",a.style.top="-9999px",a.removeAttribute("title")),d&&(t(d,N.hoverClass),t(d,N.activeClass),d=null)};var O=function(){var b,c,d=document.getElementById("global-zeroclipboard-html-bridge");if(!d){var f=K.config();f.jsModuleId="string"==typeof k&&k||"string"==typeof l&&l||null;var g=F(a.location.host,N),h=x(f),i=N.moviePath+w(N.moviePath,N),j='      <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" id="global-zeroclipboard-flash-bridge" width="100%" height="100%">         <param name="movie" value="'+i+'"/>         <param name="allowScriptAccess" value="'+g+'"/>         <param name="scale" value="exactfit"/>         <param name="loop" value="false"/>         <param name="menu" value="false"/>         <param name="quality" value="best" />         <param name="bgcolor" value="#ffffff"/>         <param name="wmode" value="transparent"/>         <param name="flashvars" value="'+h+'"/>         <embed src="'+i+'"           loop="false" menu="false"           quality="best" bgcolor="#ffffff"           width="100%" height="100%"           name="global-zeroclipboard-flash-bridge"           allowScriptAccess="'+g+'"           allowFullScreen="false"           type="application/x-shockwave-flash"           wmode="transparent"           pluginspage="http://www.macromedia.com/go/getflashplayer"           flashvars="'+h+'"           scale="exactfit">         </embed>       </object>';d=document.createElement("div"),d.id="global-zeroclipboard-html-bridge",d.setAttribute("class","global-zeroclipboard-container"),d.style.position="absolute",d.style.left="0px",d.style.top="-9999px",d.style.width="15px",d.style.height="15px",d.style.zIndex=""+B(N.zIndex),document.body.appendChild(d),d.innerHTML=j}b=document["global-zeroclipboard-flash-bridge"],b&&(c=b.length)&&(b=b[c-1]),e.bridge=b||d.children[0].lastElementChild},P=function(a){for(var b=/^OBJECT|EMBED$/,c=a&&a.parentNode;c&&b.test(c.nodeName)&&c.parentNode;)c=c.parentNode;return c||null},Q=function(){if(d){var a=v(d,N.zIndex),b=P(e.bridge);b&&(b.style.top=a.top+"px",b.style.left=a.left+"px",b.style.width=a.width+"px",b.style.height=a.height+"px",b.style.zIndex=a.zIndex+1),e.ready===!0&&e.bridge&&"function"==typeof e.bridge.setSize?e.bridge.setSize(a.width,a.height):e.ready=!1}return this};K.prototype.on=function(a,b){var c,d,f,g={},i=h[this.id]&&h[this.id].handlers;if("string"==typeof a&&a)f=a.toLowerCase().split(/\s+/);else if("object"==typeof a&&a&&"undefined"==typeof b)for(c in a)a.hasOwnProperty(c)&&"string"==typeof c&&c&&"function"==typeof a[c]&&this.on(c,a[c]);if(f&&f.length){for(c=0,d=f.length;d>c;c++)a=f[c].replace(/^on/,""),g[a]=!0,i[a]||(i[a]=[]),i[a].push(b);g.noflash&&e.disabled&&T.call(this,"noflash",{}),g.wrongflash&&e.outdated&&T.call(this,"wrongflash",{flashVersion:e.version}),g.load&&e.ready&&T.call(this,"load",{flashVersion:e.version})}return this},K.prototype.off=function(a,b){var c,d,e,f,g,i=h[this.id]&&h[this.id].handlers;if(0===arguments.length)f=G(i);else if("string"==typeof a&&a)f=a.split(/\s+/);else if("object"==typeof a&&a&&"undefined"==typeof b)for(c in a)a.hasOwnProperty(c)&&"string"==typeof c&&c&&"function"==typeof a[c]&&this.off(c,a[c]);if(f&&f.length)for(c=0,d=f.length;d>c;c++)if(a=f[c].toLowerCase().replace(/^on/,""),g=i[a],g&&g.length)if(b)for(e=y(b,g);-1!==e;)g.splice(e,1),e=y(b,g,e);else i[a].length=0;return this},K.prototype.handlers=function(a){var b,c=null,d=h[this.id]&&h[this.id].handlers;if(d){if("string"==typeof a&&a)return d[a]?d[a].slice(0):null;c={};for(b in d)d.hasOwnProperty(b)&&d[b]&&(c[b]=d[b].slice(0))}return c};var R=function(b,c,d,e){var f=h[this.id]&&h[this.id].handlers[b];if(f&&f.length){var g,i,j,k=c||this;for(g=0,i=f.length;i>g;g++)j=f[g],c=k,"string"==typeof j&&"function"==typeof a[j]&&(j=a[j]),"object"==typeof j&&j&&"function"==typeof j.handleEvent&&(c=j,j=j.handleEvent),"function"==typeof j&&A(j,c,d,e)}return this};K.prototype.clip=function(a){a=z(a);for(var b=0;b<a.length;b++)if(a.hasOwnProperty(b)&&a[b]&&1===a[b].nodeType){a[b].zcClippingId?-1===y(this.id,j[a[b].zcClippingId])&&j[a[b].zcClippingId].push(this.id):(a[b].zcClippingId="zcClippingId_"+i++,j[a[b].zcClippingId]=[this.id],N.autoActivate===!0&&q(a[b],"mouseover",p));var c=h[this.id].elements;-1===y(a[b],c)&&c.push(a[b])}return this},K.prototype.unclip=function(a){var b=h[this.id];if(b){var c,d=b.elements;a="undefined"==typeof a?d.slice(0):z(a);for(var e=a.length;e--;)if(a.hasOwnProperty(e)&&a[e]&&1===a[e].nodeType){for(c=0;-1!==(c=y(a[e],d,c));)d.splice(c,1);var f=j[a[e].zcClippingId];if(f){for(c=0;-1!==(c=y(this.id,f,c));)f.splice(c,1);0===f.length&&(N.autoActivate===!0&&r(a[e],"mouseover",p),delete a[e].zcClippingId)}}}return this},K.prototype.elements=function(){var a=h[this.id];return a&&a.elements?a.elements.slice(0):[]};var S=function(a){var b,c,d,e,f,g=[];if(a&&1===a.nodeType&&(b=a.zcClippingId)&&j.hasOwnProperty(b)&&(c=j[b],c&&c.length))for(d=0,e=c.length;e>d;d++)f=h[c[d]].instance,f&&f instanceof K&&g.push(f);return g};N.hoverClass="zeroclipboard-is-hover",N.activeClass="zeroclipboard-is-active",N.trustedOrigins=null,N.allowScriptAccess=null,N.useNoCache=!0,N.moviePath="ZeroClipboard.swf",K.detectFlashSupport=function(){return C("ZeroClipboard.detectFlashSupport",N.debug),J()},K.dispatch=function(a,b){if("string"==typeof a&&a){var c=a.toLowerCase().replace(/^on/,"");if(c)for(var e=d&&N.autoActivate===!0?S(d):M(),f=0,g=e.length;g>f;f++)T.call(e[f],c,b)}},K.prototype.setHandCursor=function(a){return C("ZeroClipboard.prototype.setHandCursor",N.debug),a="boolean"==typeof a?a:!!a,L(a),N.forceHandCursor=a,this},K.prototype.reposition=function(){return C("ZeroClipboard.prototype.reposition",N.debug),Q()},K.prototype.receiveEvent=function(a,b){if(C("ZeroClipboard.prototype.receiveEvent",N.debug),"string"==typeof a&&a){var c=a.toLowerCase().replace(/^on/,"");c&&T.call(this,c,b)}},K.prototype.setCurrent=function(a){return C("ZeroClipboard.prototype.setCurrent",N.debug),K.activate(a),this},K.prototype.resetBridge=function(){return C("ZeroClipboard.prototype.resetBridge",N.debug),K.deactivate(),this},K.prototype.setTitle=function(a){if(C("ZeroClipboard.prototype.setTitle",N.debug),a=a||N.title||d&&d.getAttribute("title")){var b=P(e.bridge);b&&b.setAttribute("title",a)}return this},K.setDefaults=function(a){C("ZeroClipboard.setDefaults",N.debug),K.config(a)},K.prototype.addEventListener=function(a,b){return C("ZeroClipboard.prototype.addEventListener",N.debug),this.on(a,b)},K.prototype.removeEventListener=function(a,b){return C("ZeroClipboard.prototype.removeEventListener",N.debug),this.off(a,b)},K.prototype.ready=function(){return C("ZeroClipboard.prototype.ready",N.debug),e.ready===!0};var T=function(a,g){a=a.toLowerCase().replace(/^on/,"");var h=g&&g.flashVersion&&b(g.flashVersion)||null,i=d,j=!0;switch(a){case"load":if(h){if(!c(h))return T.call(this,"onWrongFlash",{flashVersion:h}),void 0;e.outdated=!1,e.ready=!0,e.version=h}break;case"wrongflash":h&&!c(h)&&(e.outdated=!0,e.ready=!1,e.version=h);break;case"mouseover":s(i,N.hoverClass);break;case"mouseout":N.autoActivate===!0&&K.deactivate();break;case"mousedown":s(i,N.activeClass);break;case"mouseup":t(i,N.activeClass);break;case"datarequested":if(i){var k=i.getAttribute("data-clipboard-target"),l=k?document.getElementById(k):null;if(l){var m=l.value||l.textContent||l.innerText;m&&this.setText(m)}else{var n=i.getAttribute("data-clipboard-text");n&&this.setText(n)}}j=!1;break;case"complete":H(f),i&&i!==I()&&i.focus&&i.focus()}var o=i,p=[this,g];return R.call(this,a,o,p,j)};"function"==typeof define&&define.amd?define(["require","exports","module"],function(a,b,c){return k=c&&c.id||null,K}):"object"==typeof module&&module&&"object"==typeof module.exports&&module.exports&&"function"==typeof a.require?(l=module.id||null,module.exports=K):a.ZeroClipboard=K}(function(){return this}());

ZeroClipboard.config({ debug: false });// methods to load external libraries (used in social share beam widgets).
;(function() {

var SocialShareUtil = {
	setFB_ID: function(f_dev)
	{
		var DEV_ID = '159931337417';
		var PROD_ID = '175862993435';

		this.FB_ID = (f_dev ? DEV_ID : PROD_ID);
	},

	loadFacebook: function(f_dev)
	{
		var DEV_ID = '159931337417';
		var PROD_ID = '175862993435';

		window.fbAsyncInit = function() {
			FB.init({
				appId      : (f_dev) ? DEV_ID : PROD_ID,
				xfbml      : true,
				version    : 'v2.1'
			});
		};
	  (function(d, s, id){
		 var js, fjs = d.getElementsByTagName(s)[0];
		 if (d.getElementById(id)) {return;}
		 js = d.createElement(s); js.id = id;
		 js.src = "//connect.facebook.net/en_US/sdk.js";
		 fjs.parentNode.insertBefore(js, fjs);
	   }(document, 'script', 'facebook-jssdk'));
	},

	loadTwitter: function()
	{
		window.twttr = (function(d, s, id) {
		  var js, fjs = d.getElementsByTagName(s)[0],
		    t = window.twttr || {};
		// twitter script is already loaded, return the existing window.twttr;
		  if (d.getElementById(id)) return window.twttr;
		  js = d.createElement(s);
		  js.id = id;
		  js.src = "https://platform.twitter.com/widgets.js";
		  fjs.parentNode.insertBefore(js, fjs);

		  t._e = [];
		  t.ready = function(f) {
		    t._e.push(f);
		  };

		  return t;
		}(document, "script", "twitter-wjs"));
	},

	loadPinterest: function()
	{
	    window.pAsyncInit = function() {
	        PDK.init({
	            appId: "4792463668828701357",
	            cookie: true
	        });
	    };

	    (function(d, s, id){
	        var js, pjs = d.getElementsByTagName(s)[0];
	        if (d.getElementById(id)) {return;}
	        js = d.createElement(s); js.id = id;
	        js.src = "//assets.pinterest.com/sdk/sdk.js";
	        pjs.parentNode.insertBefore(js, pjs);
	    }(document, 'script', 'pinterest-jssdk'));
	}
};

window.SocialShareUtil = SocialShareUtil;

}());
/**
 * Exports a single sharing function which can open share dialogs for a 
 * variety of social media services, or a native email client. Note that each
 * share service triggers popup windows and as such user interaction
 * must initiate the call to this function to avoid being popup-blocked.
 *
 * @module O_O.lib.SocialShare
 *
 * @requires: twitter, facebook, gplus, and pinterest JavaScript SDKs/libs
 * must be loaded on page for sharing via each respective service. All
 * are optional. See each service's class for details on code to load.
 */

;(function() {


/**
 * Base class
 */
function SocialShare() {}

SocialShare.prototype = {
	constructor: SocialShare,
	share: function(data, cb) {
		throw new Error('share() must be implemented by subclass');
	}
};

/**
 * Share on Facebook
 */
function FacebookShare() { SocialShare.call(this, arguments); }
FacebookShare.prototype = Object.create(SocialShare.prototype);

FacebookShare.prototype.share = function(data, cb) {
	if (data.redirectUrl) _facebookShareRedirect(data);
	else _facebookShare(data, cb);
};

/**
 * @param {Object} data
 * @param {String} data.url
 * @param {Object} cb
 * @requires Facebook JS SDK: https://developers.facebook.com/docs/javascript
 */
_facebookShare = function(data, cb) {
	if (!window.FB) throw new Error('FB library not loaded, what the heck.');
	data = data || {};
	window.FB.ui({
		method: 'share',
		href: data.url || window.location.href
	}, function(response){
		if (response && !response.error_code && cb) {
			cb();
		}
	});
};

/**
 * Allows you to share from a domain that is different from the domain registered
 * with your fb app id. The data.redirectUrl domain must match the registered domain.
 * Useful, eg, for share from beam sites with a cname.
 * @param {Object} data
 * @param {String} data.url
 * @param {String} data.redirectUrl
 * @requires Facebook app id SocialShareUtil.FB_ID
*/
_facebookShareRedirect = function(data) {
	data = data || {};

	var url = encodeURIComponent(data.url);
	var redirectUrl = encodeURIComponent(data.redirectUrl);

	var href ='https://www.facebook.com/dialog/share?app_id=' +
			SocialShareUtil.FB_ID + '&display=popup&href=' + url + '&redirect_uri=' + redirectUrl;

	var onClick = function(e) {
		window.open(e.target.href, '',
					'menubar=no,toolbar=no,resizable=yes,' +
					'scrollbars=yes,height=600,width=600');
		return false;
	};

	simulateAnchorClick({href: href}, {onclick: onClick});
};

/**
 * Share on Twitter
 */
function TwitterShare() { SocialShare.call(this, arguments); }
TwitterShare.prototype = Object.create(SocialShare.prototype);

/**
 * @param {Object} data
 * @param {String} data.url
 * @param {Object} data.twitter
 * @param {String} data.twitter.text
 * @param {Object} cb
 * @requires Twitter SDK: https://dev.twitter.com/web/javascript
 */
TwitterShare.prototype.share = function(data, cb) {
	if (!window.twttr)
		throw new Error('Twitter library not loaded, what the heck.');

	data = data || {};

	this.attachCb(cb);

	var tweetIntentUrl = 'https://twitter.com/intent/tweet?';
	var queryParams = {
		url: data.url || window.location.href,
		text: data && data.twitter ? data.twitter.text : ''
	};
	var href = tweetIntentUrl + makeQueryString(queryParams);
	simulateAnchorClick({href: href});
};

/**
 * Listen for tweet events, and after one has occurred, fire the cb specified
 * then remove the tweet listener to prevent duplicate calls on future tweets.
 * @param {Function} cb
 */
TwitterShare.prototype.attachCb = function(cb) {
	window.twttr.events.bind('tweet', function (ev) {
		cb && cb();
		window.twttr.events.unbind('tweet');
	});
};

/**
 * Share on Google Plus
 */
function GPlusShare() { SocialShare.call(this, arguments); }
GPlusShare.prototype = Object.create(SocialShare.prototype);

/**
 * @param {Object} data
 * @param {String} data.url
 * @requires Google Plus SDK: https://developers.google.com/+/web/api/javascript
 */
GPlusShare.prototype.share = function(data) {
	if (!window.gapi)
		throw new Error('Google plus library not loaded, what the heck.');

	data = data || {};
	var url = data.url || window.location.href;
	url = encodeURIComponent(url);

	var href = 'https://plus.google.com/share?url={'+url+'}';

	var onClick = function(e) {
		window.open(e.target.href, '',
					'menubar=no,toolbar=no,resizable=yes,' +
					'scrollbars=yes,height=600,width=600');
		return false;
	};

	simulateAnchorClick({href: href}, {onclick: onClick});
};

/**
 * Share on Pinterest
 */
function PinterestShare() { SocialShare.call(this, arguments); }
PinterestShare.prototype = Object.create(SocialShare.prototype);

/**
 * @param {Object} data
 * @requires Pinterest JS SDK: https://developers.pinterest.com/docs/sdks/js/
 * The pinterest library must be loaded with the script tag containing the
 * following attribute: data-pin-build="parsePinBtns". This exposes
 * parsePinBtns to the window, so we can run it when necessary. See
 * http://stackoverflow.com/questions/9352021/how-can-i-rerender-pinterests-pin-it-button
 */
PinterestShare.prototype.share = function(data) {
	if (!window.PDK)
		throw new Error('Pinterest library not loaded, what the heck.');

	data = data || {};

	PDK.pin(data.imgUrl, data.note, data.url);
};

/**
 * Share via email
 */
function EmailShare() { SocialShare.call(this, arguments); }
EmailShare.prototype = Object.create(SocialShare.prototype);

/**
 * @param {Object} data

 * @param {String} data.to
 * @param {String} data.subject
 * @param {String} data.body
 */
EmailShare.prototype.share = function(data) {
	data = data || {};

	var mailtoHref = 'mailto:' + (data.to || '') + '?' +
		makeQueryString({subject: data.subject || '', body: data.body || '' });

	simulateAnchorClick({href: mailtoHref}, {});
};

/**
 * Query string building utility: serializes object key/val pairs.
 * @param {Object} obj Each key/value pair will be serialized
 * @returns {String}
 * @example makeQueryString({a: 'b', c: 'd' }) // => 'a=b&c=d'
 */
function makeQueryString(obj) {
  var str = [];
  for(var p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
}

/**
 * Creates an anchor, injects it into the document, simulates a click on it,
 * then cleans up after itself.
 * The purpose is to play nicely with popular APIs without having to manually
 * create anchors in view code all over the place. Instead we do it here once
 * and a caller can just say, e.g., "give me a twitter share!"
 *
 * @param {Object} attrs Key/val pairs, attributes to create on the HTML anchor
 * @param {Object} listeners Key/val pairs, on- style listeners
 * to attach to the HTML anchor
 * @param {Function} onPreClick Hook into the moment right after the anchor
 * has been inserted into the document but not yet clicked.
 */
function simulateAnchorClick(attrs, listeners, onPreClick) {
	var a = createAnchor(attrs, listeners);
	var div = document.createElement('div');
	/**
	 * A hook in case the simulated click needs to be prevented from bubbling
	 * and causing some undesired effect.
	 */
	div.setAttribute('class', 'anchor-wrapper');

	div.appendChild(a);
	document.body.appendChild(div);

	onPreClick && onPreClick();

	/**
	 * X-browser click simulation. Using a wrapper element then grabbing
	 * its first child because some services (lookin at you, pinterest)
	 * replace the original DOM element (i.e. the `a` element above).
	 */
	var el = div.firstChild;

	if (el.click) el.click();
	else if (el.fireEvent) el.fireEvent('onclick');
	else {
		var evObj = document.createEvent('Events');
		evObj.initEvent('click', true, false);
		el.dispatchEvent(evObj);
	}

	document.body.removeChild(div);
}

/**
 * Create an `a` element and add attributes and listeners to it, according
 * to the demands of the DOM.
 * @param {Object} attrs Key/val pairs, attributes to create on the HTML anchor
 * @param {Object} listeners Key/val pairs, on- style listeners
 * to attach to the HTML anchor
 * @return {HTMLElement}
 */
function createAnchor(attrs, listeners) {
	var a = document.createElement('a');

	Object.keys(attrs || {}).forEach(function (k) {
		a.setAttribute(k, attrs[k]);
	});

	Object.keys(listeners || {}).forEach(function (k) {
		a[k] = listeners[k];
	});

	return a;
}

/** 
 * Store of all available services
 */
var services = {
	facebook: new FacebookShare,
	twitter: new TwitterShare,
	gplus: new GPlusShare,
	pinterest: new PinterestShare,
	email: new EmailShare
};

/**
 * @param {String} service The social sharing service to use, e.g., facebook
 * @param {Object} data Payload containing any data that might be needed (see
 * particular share services for details of accepted keys)
 * @param {Function} cb A callback which fires once a share has occurred, if
 * given service provides the ability to register a callback (FB/Twitter only).
 */
function share(service, data, cb) {
	var serv = services[service];
	if (!serv) throw new Error('Pass a valid service');
	serv.share(data, cb);
}

// Conditional exporting for commonJS / window globals
if (typeof module !== 'undefined' && module.exports) {
	// The main thing really used by callers.
	exports.share = share;

	// Both of the following are exported for unit testing:
	exports.constructors = {
		SocialShare: SocialShare,
		FacebookShare: FacebookShare,
		TwitterShare: TwitterShare,
		GPlusShare: GPlusShare,
		PinterestShare: PinterestShare
	};
	exports.utils = {
		simulateAnchorClick: simulateAnchorClick,
		makeQueryString: makeQueryString
	};
} else {
	window.socialShare = share;
}

})();
/*!
 * Isotope PACKAGED v2.0.1
 * Filter & sort magical layouts
 * http://isotope.metafizzy.co
 */

(function(t){function e(){}function i(t){function i(e){e.prototype.option||(e.prototype.option=function(e){t.isPlainObject(e)&&(this.options=t.extend(!0,this.options,e))})}function n(e,i){t.fn[e]=function(n){if("string"==typeof n){for(var s=o.call(arguments,1),a=0,u=this.length;u>a;a++){var p=this[a],h=t.data(p,e);if(h)if(t.isFunction(h[n])&&"_"!==n.charAt(0)){var f=h[n].apply(h,s);if(void 0!==f)return f}else r("no such method '"+n+"' for "+e+" instance");else r("cannot call methods on "+e+" prior to initialization; "+"attempted to call '"+n+"'")}return this}return this.each(function(){var o=t.data(this,e);o?(o.option(n),o._init()):(o=new i(this,n),t.data(this,e,o))})}}if(t){var r="undefined"==typeof console?e:function(t){console.error(t)};return t.bridget=function(t,e){i(e),n(t,e)},t.bridget}}var o=Array.prototype.slice;"function"==typeof define&&define.amd?define("jquery-bridget/jquery.bridget",["jquery"],i):i(t.jQuery)})(window),function(t){function e(e){var i=t.event;return i.target=i.target||i.srcElement||e,i}var i=document.documentElement,o=function(){};i.addEventListener?o=function(t,e,i){t.addEventListener(e,i,!1)}:i.attachEvent&&(o=function(t,i,o){t[i+o]=o.handleEvent?function(){var i=e(t);o.handleEvent.call(o,i)}:function(){var i=e(t);o.call(t,i)},t.attachEvent("on"+i,t[i+o])});var n=function(){};i.removeEventListener?n=function(t,e,i){t.removeEventListener(e,i,!1)}:i.detachEvent&&(n=function(t,e,i){t.detachEvent("on"+e,t[e+i]);try{delete t[e+i]}catch(o){t[e+i]=void 0}});var r={bind:o,unbind:n};"function"==typeof define&&define.amd?define("eventie/eventie",r):"object"==typeof exports?module.exports=r:t.eventie=r}(this),function(t){function e(t){"function"==typeof t&&(e.isReady?t():r.push(t))}function i(t){var i="readystatechange"===t.type&&"complete"!==n.readyState;if(!e.isReady&&!i){e.isReady=!0;for(var o=0,s=r.length;s>o;o++){var a=r[o];a()}}}function o(o){return o.bind(n,"DOMContentLoaded",i),o.bind(n,"readystatechange",i),o.bind(t,"load",i),e}var n=t.document,r=[];e.isReady=!1,"function"==typeof define&&define.amd?(e.isReady="function"==typeof requirejs,define("doc-ready/doc-ready",["eventie/eventie"],o)):t.docReady=o(t.eventie)}(this),function(){function t(){}function e(t,e){for(var i=t.length;i--;)if(t[i].listener===e)return i;return-1}function i(t){return function(){return this[t].apply(this,arguments)}}var o=t.prototype,n=this,r=n.EventEmitter;o.getListeners=function(t){var e,i,o=this._getEvents();if(t instanceof RegExp){e={};for(i in o)o.hasOwnProperty(i)&&t.test(i)&&(e[i]=o[i])}else e=o[t]||(o[t]=[]);return e},o.flattenListeners=function(t){var e,i=[];for(e=0;t.length>e;e+=1)i.push(t[e].listener);return i},o.getListenersAsObject=function(t){var e,i=this.getListeners(t);return i instanceof Array&&(e={},e[t]=i),e||i},o.addListener=function(t,i){var o,n=this.getListenersAsObject(t),r="object"==typeof i;for(o in n)n.hasOwnProperty(o)&&-1===e(n[o],i)&&n[o].push(r?i:{listener:i,once:!1});return this},o.on=i("addListener"),o.addOnceListener=function(t,e){return this.addListener(t,{listener:e,once:!0})},o.once=i("addOnceListener"),o.defineEvent=function(t){return this.getListeners(t),this},o.defineEvents=function(t){for(var e=0;t.length>e;e+=1)this.defineEvent(t[e]);return this},o.removeListener=function(t,i){var o,n,r=this.getListenersAsObject(t);for(n in r)r.hasOwnProperty(n)&&(o=e(r[n],i),-1!==o&&r[n].splice(o,1));return this},o.off=i("removeListener"),o.addListeners=function(t,e){return this.manipulateListeners(!1,t,e)},o.removeListeners=function(t,e){return this.manipulateListeners(!0,t,e)},o.manipulateListeners=function(t,e,i){var o,n,r=t?this.removeListener:this.addListener,s=t?this.removeListeners:this.addListeners;if("object"!=typeof e||e instanceof RegExp)for(o=i.length;o--;)r.call(this,e,i[o]);else for(o in e)e.hasOwnProperty(o)&&(n=e[o])&&("function"==typeof n?r.call(this,o,n):s.call(this,o,n));return this},o.removeEvent=function(t){var e,i=typeof t,o=this._getEvents();if("string"===i)delete o[t];else if(t instanceof RegExp)for(e in o)o.hasOwnProperty(e)&&t.test(e)&&delete o[e];else delete this._events;return this},o.removeAllListeners=i("removeEvent"),o.emitEvent=function(t,e){var i,o,n,r,s=this.getListenersAsObject(t);for(n in s)if(s.hasOwnProperty(n))for(o=s[n].length;o--;)i=s[n][o],i.once===!0&&this.removeListener(t,i.listener),r=i.listener.apply(this,e||[]),r===this._getOnceReturnValue()&&this.removeListener(t,i.listener);return this},o.trigger=i("emitEvent"),o.emit=function(t){var e=Array.prototype.slice.call(arguments,1);return this.emitEvent(t,e)},o.setOnceReturnValue=function(t){return this._onceReturnValue=t,this},o._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},o._getEvents=function(){return this._events||(this._events={})},t.noConflict=function(){return n.EventEmitter=r,t},"function"==typeof define&&define.amd?define("eventEmitter/EventEmitter",[],function(){return t}):"object"==typeof module&&module.exports?module.exports=t:this.EventEmitter=t}.call(this),function(t){function e(t){if(t){if("string"==typeof o[t])return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var e,n=0,r=i.length;r>n;n++)if(e=i[n]+t,"string"==typeof o[e])return e}}var i="Webkit Moz ms Ms O".split(" "),o=document.documentElement.style;"function"==typeof define&&define.amd?define("get-style-property/get-style-property",[],function(){return e}):"object"==typeof exports?module.exports=e:t.getStyleProperty=e}(window),function(t){function e(t){var e=parseFloat(t),i=-1===t.indexOf("%")&&!isNaN(e);return i&&e}function i(){for(var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},e=0,i=s.length;i>e;e++){var o=s[e];t[o]=0}return t}function o(t){function o(t){if("string"==typeof t&&(t=document.querySelector(t)),t&&"object"==typeof t&&t.nodeType){var o=r(t);if("none"===o.display)return i();var n={};n.width=t.offsetWidth,n.height=t.offsetHeight;for(var h=n.isBorderBox=!(!p||!o[p]||"border-box"!==o[p]),f=0,d=s.length;d>f;f++){var l=s[f],c=o[l];c=a(t,c);var y=parseFloat(c);n[l]=isNaN(y)?0:y}var m=n.paddingLeft+n.paddingRight,g=n.paddingTop+n.paddingBottom,v=n.marginLeft+n.marginRight,_=n.marginTop+n.marginBottom,I=n.borderLeftWidth+n.borderRightWidth,L=n.borderTopWidth+n.borderBottomWidth,z=h&&u,S=e(o.width);S!==!1&&(n.width=S+(z?0:m+I));var b=e(o.height);return b!==!1&&(n.height=b+(z?0:g+L)),n.innerWidth=n.width-(m+I),n.innerHeight=n.height-(g+L),n.outerWidth=n.width+v,n.outerHeight=n.height+_,n}}function a(t,e){if(n||-1===e.indexOf("%"))return e;var i=t.style,o=i.left,r=t.runtimeStyle,s=r&&r.left;return s&&(r.left=t.currentStyle.left),i.left=e,e=i.pixelLeft,i.left=o,s&&(r.left=s),e}var u,p=t("boxSizing");return function(){if(p){var t=document.createElement("div");t.style.width="200px",t.style.padding="1px 2px 3px 4px",t.style.borderStyle="solid",t.style.borderWidth="1px 2px 3px 4px",t.style[p]="border-box";var i=document.body||document.documentElement;i.appendChild(t);var o=r(t);u=200===e(o.width),i.removeChild(t)}}(),o}var n=t.getComputedStyle,r=n?function(t){return n(t,null)}:function(t){return t.currentStyle},s=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];"function"==typeof define&&define.amd?define("get-size/get-size",["get-style-property/get-style-property"],o):"object"==typeof exports?module.exports=o(require("get-style-property")):t.getSize=o(t.getStyleProperty)}(window),function(t,e){function i(t,e){return t[a](e)}function o(t){if(!t.parentNode){var e=document.createDocumentFragment();e.appendChild(t)}}function n(t,e){o(t);for(var i=t.parentNode.querySelectorAll(e),n=0,r=i.length;r>n;n++)if(i[n]===t)return!0;return!1}function r(t,e){return o(t),i(t,e)}var s,a=function(){if(e.matchesSelector)return"matchesSelector";for(var t=["webkit","moz","ms","o"],i=0,o=t.length;o>i;i++){var n=t[i],r=n+"MatchesSelector";if(e[r])return r}}();if(a){var u=document.createElement("div"),p=i(u,"div");s=p?i:r}else s=n;"function"==typeof define&&define.amd?define("matches-selector/matches-selector",[],function(){return s}):window.matchesSelector=s}(this,Element.prototype),function(t){function e(t,e){for(var i in e)t[i]=e[i];return t}function i(t){for(var e in t)return!1;return e=null,!0}function o(t){return t.replace(/([A-Z])/g,function(t){return"-"+t.toLowerCase()})}function n(t,n,r){function a(t,e){t&&(this.element=t,this.layout=e,this.position={x:0,y:0},this._create())}var u=r("transition"),p=r("transform"),h=u&&p,f=!!r("perspective"),d={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend",transition:"transitionend"}[u],l=["transform","transition","transitionDuration","transitionProperty"],c=function(){for(var t={},e=0,i=l.length;i>e;e++){var o=l[e],n=r(o);n&&n!==o&&(t[o]=n)}return t}();e(a.prototype,t.prototype),a.prototype._create=function(){this._transn={ingProperties:{},clean:{},onEnd:{}},this.css({position:"absolute"})},a.prototype.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},a.prototype.getSize=function(){this.size=n(this.element)},a.prototype.css=function(t){var e=this.element.style;for(var i in t){var o=c[i]||i;e[o]=t[i]}},a.prototype.getPosition=function(){var t=s(this.element),e=this.layout.options,i=e.isOriginLeft,o=e.isOriginTop,n=parseInt(t[i?"left":"right"],10),r=parseInt(t[o?"top":"bottom"],10);n=isNaN(n)?0:n,r=isNaN(r)?0:r;var a=this.layout.size;n-=i?a.paddingLeft:a.paddingRight,r-=o?a.paddingTop:a.paddingBottom,this.position.x=n,this.position.y=r},a.prototype.layoutPosition=function(){var t=this.layout.size,e=this.layout.options,i={};e.isOriginLeft?(i.left=this.position.x+t.paddingLeft+"px",i.right=""):(i.right=this.position.x+t.paddingRight+"px",i.left=""),e.isOriginTop?(i.top=this.position.y+t.paddingTop+"px",i.bottom=""):(i.bottom=this.position.y+t.paddingBottom+"px",i.top=""),this.css(i),this.emitEvent("layout",[this])};var y=f?function(t,e){return"translate3d("+t+"px, "+e+"px, 0)"}:function(t,e){return"translate("+t+"px, "+e+"px)"};a.prototype._transitionTo=function(t,e){this.getPosition();var i=this.position.x,o=this.position.y,n=parseInt(t,10),r=parseInt(e,10),s=n===this.position.x&&r===this.position.y;if(this.setPosition(t,e),s&&!this.isTransitioning)return this.layoutPosition(),void 0;var a=t-i,u=e-o,p={},h=this.layout.options;a=h.isOriginLeft?a:-a,u=h.isOriginTop?u:-u,p.transform=y(a,u),this.transition({to:p,onTransitionEnd:{transform:this.layoutPosition},isCleaning:!0})},a.prototype.goTo=function(t,e){this.setPosition(t,e),this.layoutPosition()},a.prototype.moveTo=h?a.prototype._transitionTo:a.prototype.goTo,a.prototype.setPosition=function(t,e){this.position.x=parseInt(t,10),this.position.y=parseInt(e,10)},a.prototype._nonTransition=function(t){this.css(t.to),t.isCleaning&&this._removeStyles(t.to);for(var e in t.onTransitionEnd)t.onTransitionEnd[e].call(this)},a.prototype._transition=function(t){if(!parseFloat(this.layout.options.transitionDuration))return this._nonTransition(t),void 0;var e=this._transn;for(var i in t.onTransitionEnd)e.onEnd[i]=t.onTransitionEnd[i];for(i in t.to)e.ingProperties[i]=!0,t.isCleaning&&(e.clean[i]=!0);if(t.from){this.css(t.from);var o=this.element.offsetHeight;o=null}this.enableTransition(t.to),this.css(t.to),this.isTransitioning=!0};var m=p&&o(p)+",opacity";a.prototype.enableTransition=function(){this.isTransitioning||(this.css({transitionProperty:m,transitionDuration:this.layout.options.transitionDuration}),this.element.addEventListener(d,this,!1))},a.prototype.transition=a.prototype[u?"_transition":"_nonTransition"],a.prototype.onwebkitTransitionEnd=function(t){this.ontransitionend(t)},a.prototype.onotransitionend=function(t){this.ontransitionend(t)};var g={"-webkit-transform":"transform","-moz-transform":"transform","-o-transform":"transform"};a.prototype.ontransitionend=function(t){if(t.target===this.element){var e=this._transn,o=g[t.propertyName]||t.propertyName;if(delete e.ingProperties[o],i(e.ingProperties)&&this.disableTransition(),o in e.clean&&(this.element.style[t.propertyName]="",delete e.clean[o]),o in e.onEnd){var n=e.onEnd[o];n.call(this),delete e.onEnd[o]}this.emitEvent("transitionEnd",[this])}},a.prototype.disableTransition=function(){this.removeTransitionStyles(),this.element.removeEventListener(d,this,!1),this.isTransitioning=!1},a.prototype._removeStyles=function(t){var e={};for(var i in t)e[i]="";this.css(e)};var v={transitionProperty:"",transitionDuration:""};return a.prototype.removeTransitionStyles=function(){this.css(v)},a.prototype.removeElem=function(){this.element.parentNode.removeChild(this.element),this.emitEvent("remove",[this])},a.prototype.remove=function(){if(!u||!parseFloat(this.layout.options.transitionDuration))return this.removeElem(),void 0;var t=this;this.on("transitionEnd",function(){return t.removeElem(),!0}),this.hide()},a.prototype.reveal=function(){delete this.isHidden,this.css({display:""});var t=this.layout.options;this.transition({from:t.hiddenStyle,to:t.visibleStyle,isCleaning:!0})},a.prototype.hide=function(){this.isHidden=!0,this.css({display:""});var t=this.layout.options;this.transition({from:t.visibleStyle,to:t.hiddenStyle,isCleaning:!0,onTransitionEnd:{opacity:function(){this.isHidden&&this.css({display:"none"})}}})},a.prototype.destroy=function(){this.css({position:"",left:"",right:"",top:"",bottom:"",transition:"",transform:""})},a}var r=t.getComputedStyle,s=r?function(t){return r(t,null)}:function(t){return t.currentStyle};"function"==typeof define&&define.amd?define("outlayer/item",["eventEmitter/EventEmitter","get-size/get-size","get-style-property/get-style-property"],n):(t.Outlayer={},t.Outlayer.Item=n(t.EventEmitter,t.getSize,t.getStyleProperty))}(window),function(t){function e(t,e){for(var i in e)t[i]=e[i];return t}function i(t){return"[object Array]"===f.call(t)}function o(t){var e=[];if(i(t))e=t;else if(t&&"number"==typeof t.length)for(var o=0,n=t.length;n>o;o++)e.push(t[o]);else e.push(t);return e}function n(t,e){var i=l(e,t);-1!==i&&e.splice(i,1)}function r(t){return t.replace(/(.)([A-Z])/g,function(t,e,i){return e+"-"+i}).toLowerCase()}function s(i,s,f,l,c,y){function m(t,i){if("string"==typeof t&&(t=a.querySelector(t)),!t||!d(t))return u&&u.error("Bad "+this.constructor.namespace+" element: "+t),void 0;this.element=t,this.options=e({},this.constructor.defaults),this.option(i);var o=++g;this.element.outlayerGUID=o,v[o]=this,this._create(),this.options.isInitLayout&&this.layout()}var g=0,v={};return m.namespace="outlayer",m.Item=y,m.defaults={containerStyle:{position:"relative"},isInitLayout:!0,isOriginLeft:!0,isOriginTop:!0,isResizeBound:!0,isResizingContainer:!0,transitionDuration:"0.4s",hiddenStyle:{opacity:0,transform:"scale(0.001)"},visibleStyle:{opacity:1,transform:"scale(1)"}},e(m.prototype,f.prototype),m.prototype.option=function(t){e(this.options,t)},m.prototype._create=function(){this.reloadItems(),this.stamps=[],this.stamp(this.options.stamp),e(this.element.style,this.options.containerStyle),this.options.isResizeBound&&this.bindResize()},m.prototype.reloadItems=function(){this.items=this._itemize(this.element.children)},m.prototype._itemize=function(t){for(var e=this._filterFindItemElements(t),i=this.constructor.Item,o=[],n=0,r=e.length;r>n;n++){var s=e[n],a=new i(s,this);o.push(a)}return o},m.prototype._filterFindItemElements=function(t){t=o(t);for(var e=this.options.itemSelector,i=[],n=0,r=t.length;r>n;n++){var s=t[n];if(d(s))if(e){c(s,e)&&i.push(s);for(var a=s.querySelectorAll(e),u=0,p=a.length;p>u;u++)i.push(a[u])}else i.push(s)}return i},m.prototype.getItemElements=function(){for(var t=[],e=0,i=this.items.length;i>e;e++)t.push(this.items[e].element);return t},m.prototype.layout=function(){this._resetLayout(),this._manageStamps();var t=void 0!==this.options.isLayoutInstant?this.options.isLayoutInstant:!this._isLayoutInited;this.layoutItems(this.items,t),this._isLayoutInited=!0},m.prototype._init=m.prototype.layout,m.prototype._resetLayout=function(){this.getSize()},m.prototype.getSize=function(){this.size=l(this.element)},m.prototype._getMeasurement=function(t,e){var i,o=this.options[t];o?("string"==typeof o?i=this.element.querySelector(o):d(o)&&(i=o),this[t]=i?l(i)[e]:o):this[t]=0},m.prototype.layoutItems=function(t,e){t=this._getItemsForLayout(t),this._layoutItems(t,e),this._postLayout()},m.prototype._getItemsForLayout=function(t){for(var e=[],i=0,o=t.length;o>i;i++){var n=t[i];n.isIgnored||e.push(n)}return e},m.prototype._layoutItems=function(t,e){function i(){o.emitEvent("layoutComplete",[o,t])}var o=this;if(!t||!t.length)return i(),void 0;this._itemsOn(t,"layout",i);for(var n=[],r=0,s=t.length;s>r;r++){var a=t[r],u=this._getItemLayoutPosition(a);u.item=a,u.isInstant=e||a.isLayoutInstant,n.push(u)}this._processLayoutQueue(n)},m.prototype._getItemLayoutPosition=function(){return{x:0,y:0}},m.prototype._processLayoutQueue=function(t){for(var e=0,i=t.length;i>e;e++){var o=t[e];this._positionItem(o.item,o.x,o.y,o.isInstant)}},m.prototype._positionItem=function(t,e,i,o){o?t.goTo(e,i):t.moveTo(e,i)},m.prototype._postLayout=function(){this.resizeContainer()},m.prototype.resizeContainer=function(){if(this.options.isResizingContainer){var t=this._getContainerSize();t&&(this._setContainerMeasure(t.width,!0),this._setContainerMeasure(t.height,!1))}},m.prototype._getContainerSize=h,m.prototype._setContainerMeasure=function(t,e){if(void 0!==t){var i=this.size;i.isBorderBox&&(t+=e?i.paddingLeft+i.paddingRight+i.borderLeftWidth+i.borderRightWidth:i.paddingBottom+i.paddingTop+i.borderTopWidth+i.borderBottomWidth),t=Math.max(t,0),this.element.style[e?"width":"height"]=t+"px"}},m.prototype._itemsOn=function(t,e,i){function o(){return n++,n===r&&i.call(s),!0}for(var n=0,r=t.length,s=this,a=0,u=t.length;u>a;a++){var p=t[a];p.on(e,o)}},m.prototype.ignore=function(t){var e=this.getItem(t);e&&(e.isIgnored=!0)},m.prototype.unignore=function(t){var e=this.getItem(t);e&&delete e.isIgnored},m.prototype.stamp=function(t){if(t=this._find(t)){this.stamps=this.stamps.concat(t);for(var e=0,i=t.length;i>e;e++){var o=t[e];this.ignore(o)}}},m.prototype.unstamp=function(t){if(t=this._find(t))for(var e=0,i=t.length;i>e;e++){var o=t[e];n(o,this.stamps),this.unignore(o)}},m.prototype._find=function(t){return t?("string"==typeof t&&(t=this.element.querySelectorAll(t)),t=o(t)):void 0},m.prototype._manageStamps=function(){if(this.stamps&&this.stamps.length){this._getBoundingRect();for(var t=0,e=this.stamps.length;e>t;t++){var i=this.stamps[t];this._manageStamp(i)}}},m.prototype._getBoundingRect=function(){var t=this.element.getBoundingClientRect(),e=this.size;this._boundingRect={left:t.left+e.paddingLeft+e.borderLeftWidth,top:t.top+e.paddingTop+e.borderTopWidth,right:t.right-(e.paddingRight+e.borderRightWidth),bottom:t.bottom-(e.paddingBottom+e.borderBottomWidth)}},m.prototype._manageStamp=h,m.prototype._getElementOffset=function(t){var e=t.getBoundingClientRect(),i=this._boundingRect,o=l(t),n={left:e.left-i.left-o.marginLeft,top:e.top-i.top-o.marginTop,right:i.right-e.right-o.marginRight,bottom:i.bottom-e.bottom-o.marginBottom};return n},m.prototype.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},m.prototype.bindResize=function(){this.isResizeBound||(i.bind(t,"resize",this),this.isResizeBound=!0)},m.prototype.unbindResize=function(){this.isResizeBound&&i.unbind(t,"resize",this),this.isResizeBound=!1},m.prototype.onresize=function(){function t(){e.resize(),delete e.resizeTimeout}this.resizeTimeout&&clearTimeout(this.resizeTimeout);var e=this;this.resizeTimeout=setTimeout(t,100)},m.prototype.resize=function(){this.isResizeBound&&this.needsResizeLayout()&&this.layout()},m.prototype.needsResizeLayout=function(){var t=l(this.element),e=this.size&&t;return e&&t.innerWidth!==this.size.innerWidth},m.prototype.addItems=function(t){var e=this._itemize(t);return e.length&&(this.items=this.items.concat(e)),e},m.prototype.appended=function(t){var e=this.addItems(t);e.length&&(this.layoutItems(e,!0),this.reveal(e))},m.prototype.prepended=function(t){var e=this._itemize(t);if(e.length){var i=this.items.slice(0);this.items=e.concat(i),this._resetLayout(),this._manageStamps(),this.layoutItems(e,!0),this.reveal(e),this.layoutItems(i)}},m.prototype.reveal=function(t){var e=t&&t.length;if(e)for(var i=0;e>i;i++){var o=t[i];o.reveal()}},m.prototype.hide=function(t){var e=t&&t.length;if(e)for(var i=0;e>i;i++){var o=t[i];o.hide()}},m.prototype.getItem=function(t){for(var e=0,i=this.items.length;i>e;e++){var o=this.items[e];if(o.element===t)return o}},m.prototype.getItems=function(t){if(t&&t.length){for(var e=[],i=0,o=t.length;o>i;i++){var n=t[i],r=this.getItem(n);r&&e.push(r)}return e}},m.prototype.remove=function(t){t=o(t);var e=this.getItems(t);if(e&&e.length){this._itemsOn(e,"remove",function(){this.emitEvent("removeComplete",[this,e])});for(var i=0,r=e.length;r>i;i++){var s=e[i];s.remove(),n(s,this.items)}}},m.prototype.destroy=function(){var t=this.element.style;t.height="",t.position="",t.width="";for(var e=0,i=this.items.length;i>e;e++){var o=this.items[e];o.destroy()}this.unbindResize(),delete this.element.outlayerGUID,p&&p.removeData(this.element,this.constructor.namespace)},m.data=function(t){var e=t&&t.outlayerGUID;return e&&v[e]},m.create=function(t,i){function o(){m.apply(this,arguments)}return Object.create?o.prototype=Object.create(m.prototype):e(o.prototype,m.prototype),o.prototype.constructor=o,o.defaults=e({},m.defaults),e(o.defaults,i),o.prototype.settings={},o.namespace=t,o.data=m.data,o.Item=function(){y.apply(this,arguments)},o.Item.prototype=new y,s(function(){for(var e=r(t),i=a.querySelectorAll(".js-"+e),n="data-"+e+"-options",s=0,h=i.length;h>s;s++){var f,d=i[s],l=d.getAttribute(n);try{f=l&&JSON.parse(l)}catch(c){u&&u.error("Error parsing "+n+" on "+d.nodeName.toLowerCase()+(d.id?"#"+d.id:"")+": "+c);continue}var y=new o(d,f);p&&p.data(d,t,y)}}),p&&p.bridget&&p.bridget(t,o),o},m.Item=y,m}var a=t.document,u=t.console,p=t.jQuery,h=function(){},f=Object.prototype.toString,d="object"==typeof HTMLElement?function(t){return t instanceof HTMLElement}:function(t){return t&&"object"==typeof t&&1===t.nodeType&&"string"==typeof t.nodeName},l=Array.prototype.indexOf?function(t,e){return t.indexOf(e)}:function(t,e){for(var i=0,o=t.length;o>i;i++)if(t[i]===e)return i;return-1};"function"==typeof define&&define.amd?define("outlayer/outlayer",["eventie/eventie","doc-ready/doc-ready","eventEmitter/EventEmitter","get-size/get-size","matches-selector/matches-selector","./item"],s):t.Outlayer=s(t.eventie,t.docReady,t.EventEmitter,t.getSize,t.matchesSelector,t.Outlayer.Item)}(window),function(t){function e(t){function e(){t.Item.apply(this,arguments)}e.prototype=new t.Item,e.prototype._create=function(){this.id=this.layout.itemGUID++,t.Item.prototype._create.call(this),this.sortData={}},e.prototype.updateSortData=function(){if(!this.isIgnored){this.sortData.id=this.id,this.sortData["original-order"]=this.id,this.sortData.random=Math.random();var t=this.layout.options.getSortData,e=this.layout._sorters;for(var i in t){var o=e[i];this.sortData[i]=o(this.element,this)}}};var i=e.prototype.destroy;return e.prototype.destroy=function(){i.apply(this,arguments),this.css({display:""})},e}"function"==typeof define&&define.amd?define("isotope/js/item",["outlayer/outlayer"],e):(t.Isotope=t.Isotope||{},t.Isotope.Item=e(t.Outlayer))}(window),function(t){function e(t,e){function i(t){this.isotope=t,t&&(this.options=t.options[this.namespace],this.element=t.element,this.items=t.filteredItems,this.size=t.size)}return function(){function t(t){return function(){return e.prototype[t].apply(this.isotope,arguments)}}for(var o=["_resetLayout","_getItemLayoutPosition","_manageStamp","_getContainerSize","_getElementOffset","needsResizeLayout"],n=0,r=o.length;r>n;n++){var s=o[n];i.prototype[s]=t(s)}}(),i.prototype.needsVerticalResizeLayout=function(){var e=t(this.isotope.element),i=this.isotope.size&&e;return i&&e.innerHeight!==this.isotope.size.innerHeight},i.prototype._getMeasurement=function(){this.isotope._getMeasurement.apply(this,arguments)},i.prototype.getColumnWidth=function(){this.getSegmentSize("column","Width")},i.prototype.getRowHeight=function(){this.getSegmentSize("row","Height")},i.prototype.getSegmentSize=function(t,e){var i=t+e,o="outer"+e;if(this._getMeasurement(i,o),!this[i]){var n=this.getFirstItemSize();this[i]=n&&n[o]||this.isotope.size["inner"+e]}},i.prototype.getFirstItemSize=function(){var e=this.isotope.filteredItems[0];return e&&e.element&&t(e.element)},i.prototype.layout=function(){this.isotope.layout.apply(this.isotope,arguments)},i.prototype.getSize=function(){this.isotope.getSize(),this.size=this.isotope.size},i.modes={},i.create=function(t,e){function o(){i.apply(this,arguments)}return o.prototype=new i,e&&(o.options=e),o.prototype.namespace=t,i.modes[t]=o,o},i}"function"==typeof define&&define.amd?define("isotope/js/layout-mode",["get-size/get-size","outlayer/outlayer"],e):(t.Isotope=t.Isotope||{},t.Isotope.LayoutMode=e(t.getSize,t.Outlayer))}(window),function(t){function e(t,e){var o=t.create("masonry");return o.prototype._resetLayout=function(){this.getSize(),this._getMeasurement("columnWidth","outerWidth"),this._getMeasurement("gutter","outerWidth"),this.measureColumns();var t=this.cols;for(this.colYs=[];t--;)this.colYs.push(0);this.maxY=0},o.prototype.measureColumns=function(){if(this.getContainerWidth(),!this.columnWidth){var t=this.items[0],i=t&&t.element;this.columnWidth=i&&e(i).outerWidth||this.containerWidth}this.columnWidth+=this.gutter,this.cols=Math.floor((this.containerWidth+this.gutter)/this.columnWidth),this.cols=Math.max(this.cols,1)},o.prototype.getContainerWidth=function(){var t=this.options.isFitWidth?this.element.parentNode:this.element,i=e(t);this.containerWidth=i&&i.innerWidth},o.prototype._getItemLayoutPosition=function(t){t.getSize();var e=t.size.outerWidth%this.columnWidth,o=e&&1>e?"round":"ceil",n=Math[o](t.size.outerWidth/this.columnWidth);n=Math.min(n,this.cols);for(var r=this._getColGroup(n),s=Math.min.apply(Math,r),a=i(r,s),u={x:this.columnWidth*a,y:s},p=s+t.size.outerHeight,h=this.cols+1-r.length,f=0;h>f;f++)this.colYs[a+f]=p;return u},o.prototype._getColGroup=function(t){if(2>t)return this.colYs;for(var e=[],i=this.cols+1-t,o=0;i>o;o++){var n=this.colYs.slice(o,o+t);e[o]=Math.max.apply(Math,n)}return e},o.prototype._manageStamp=function(t){var i=e(t),o=this._getElementOffset(t),n=this.options.isOriginLeft?o.left:o.right,r=n+i.outerWidth,s=Math.floor(n/this.columnWidth);s=Math.max(0,s);var a=Math.floor(r/this.columnWidth);a-=r%this.columnWidth?0:1,a=Math.min(this.cols-1,a);for(var u=(this.options.isOriginTop?o.top:o.bottom)+i.outerHeight,p=s;a>=p;p++)this.colYs[p]=Math.max(u,this.colYs[p])},o.prototype._getContainerSize=function(){this.maxY=Math.max.apply(Math,this.colYs);var t={height:this.maxY};return this.options.isFitWidth&&(t.width=this._getContainerFitWidth()),t},o.prototype._getContainerFitWidth=function(){for(var t=0,e=this.cols;--e&&0===this.colYs[e];)t++;return(this.cols-t)*this.columnWidth-this.gutter},o.prototype.needsResizeLayout=function(){var t=this.containerWidth;return this.getContainerWidth(),t!==this.containerWidth},o}var i=Array.prototype.indexOf?function(t,e){return t.indexOf(e)}:function(t,e){for(var i=0,o=t.length;o>i;i++){var n=t[i];if(n===e)return i}return-1};"function"==typeof define&&define.amd?define("masonry/masonry",["outlayer/outlayer","get-size/get-size"],e):t.Masonry=e(t.Outlayer,t.getSize)}(window),function(t){function e(t,e){for(var i in e)t[i]=e[i];return t}function i(t,i){var o=t.create("masonry"),n=o.prototype._getElementOffset,r=o.prototype.layout,s=o.prototype._getMeasurement;e(o.prototype,i.prototype),o.prototype._getElementOffset=n,o.prototype.layout=r,o.prototype._getMeasurement=s;var a=o.prototype.measureColumns;o.prototype.measureColumns=function(){this.items=this.isotope.filteredItems,a.call(this)};var u=o.prototype._manageStamp;return o.prototype._manageStamp=function(){this.options.isOriginLeft=this.isotope.options.isOriginLeft,this.options.isOriginTop=this.isotope.options.isOriginTop,u.apply(this,arguments)},o}"function"==typeof define&&define.amd?define("isotope/js/layout-modes/masonry",["../layout-mode","masonry/masonry"],i):i(t.Isotope.LayoutMode,t.Masonry)}(window),function(t){function e(t){var e=t.create("fitRows");return e.prototype._resetLayout=function(){this.x=0,this.y=0,this.maxY=0},e.prototype._getItemLayoutPosition=function(t){t.getSize(),0!==this.x&&t.size.outerWidth+this.x>this.isotope.size.innerWidth&&(this.x=0,this.y=this.maxY);var e={x:this.x,y:this.y};return this.maxY=Math.max(this.maxY,this.y+t.size.outerHeight),this.x+=t.size.outerWidth,e},e.prototype._getContainerSize=function(){return{height:this.maxY}},e}"function"==typeof define&&define.amd?define("isotope/js/layout-modes/fit-rows",["../layout-mode"],e):e(t.Isotope.LayoutMode)}(window),function(t){function e(t){var e=t.create("vertical",{horizontalAlignment:0});return e.prototype._resetLayout=function(){this.y=0},e.prototype._getItemLayoutPosition=function(t){t.getSize();var e=(this.isotope.size.innerWidth-t.size.outerWidth)*this.options.horizontalAlignment,i=this.y;return this.y+=t.size.outerHeight,{x:e,y:i}},e.prototype._getContainerSize=function(){return{height:this.y}},e}"function"==typeof define&&define.amd?define("isotope/js/layout-modes/vertical",["../layout-mode"],e):e(t.Isotope.LayoutMode)}(window),function(t){function e(t,e){for(var i in e)t[i]=e[i];return t}function i(t){return"[object Array]"===h.call(t)}function o(t){var e=[];if(i(t))e=t;else if(t&&"number"==typeof t.length)for(var o=0,n=t.length;n>o;o++)e.push(t[o]);else e.push(t);return e}function n(t,e){var i=f(e,t);-1!==i&&e.splice(i,1)}function r(t,i,r,u,h){function f(t,e){return function(i,o){for(var n=0,r=t.length;r>n;n++){var s=t[n],a=i.sortData[s],u=o.sortData[s];if(a>u||u>a){var p=void 0!==e[s]?e[s]:e,h=p?1:-1;return(a>u?1:-1)*h}}return 0}}var d=t.create("isotope",{layoutMode:"masonry",isJQueryFiltering:!0,sortAscending:!0});d.Item=u,d.LayoutMode=h,d.prototype._create=function(){this.itemGUID=0,this._sorters={},this._getSorters(),t.prototype._create.call(this),this.modes={},this.filteredItems=this.items,this.sortHistory=["original-order"];for(var e in h.modes)this._initLayoutMode(e)},d.prototype.reloadItems=function(){this.itemGUID=0,t.prototype.reloadItems.call(this)},d.prototype._itemize=function(){for(var e=t.prototype._itemize.apply(this,arguments),i=0,o=e.length;o>i;i++){var n=e[i];n.id=this.itemGUID++}return this._updateItemsSortData(e),e},d.prototype._initLayoutMode=function(t){var i=h.modes[t],o=this.options[t]||{};this.options[t]=i.options?e(i.options,o):o,this.modes[t]=new i(this)},d.prototype.layout=function(){return!this._isLayoutInited&&this.options.isInitLayout?(this.arrange(),void 0):(this._layout(),void 0)},d.prototype._layout=function(){var t=this._getIsInstant();this._resetLayout(),this._manageStamps(),this.layoutItems(this.filteredItems,t),this._isLayoutInited=!0},d.prototype.arrange=function(t){this.option(t),this._getIsInstant(),this.filteredItems=this._filter(this.items),this._sort(),this._layout()},d.prototype._init=d.prototype.arrange,d.prototype._getIsInstant=function(){var t=void 0!==this.options.isLayoutInstant?this.options.isLayoutInstant:!this._isLayoutInited;return this._isInstant=t,t},d.prototype._filter=function(t){function e(){f.reveal(n),f.hide(r)}var i=this.options.filter;i=i||"*";for(var o=[],n=[],r=[],s=this._getFilterTest(i),a=0,u=t.length;u>a;a++){var p=t[a];if(!p.isIgnored){var h=s(p);h&&o.push(p),h&&p.isHidden?n.push(p):h||p.isHidden||r.push(p)}}var f=this;return this._isInstant?this._noTransition(e):e(),o},d.prototype._getFilterTest=function(t){return s&&this.options.isJQueryFiltering?function(e){return s(e.element).is(t)}:"function"==typeof t?function(e){return t(e.element)}:function(e){return r(e.element,t)}},d.prototype.updateSortData=function(t){this._getSorters(),t=o(t);
var e=this.getItems(t);e=e.length?e:this.items,this._updateItemsSortData(e)},d.prototype._getSorters=function(){var t=this.options.getSortData;for(var e in t){var i=t[e];this._sorters[e]=l(i)}},d.prototype._updateItemsSortData=function(t){for(var e=0,i=t.length;i>e;e++){var o=t[e];o.updateSortData()}};var l=function(){function t(t){if("string"!=typeof t)return t;var i=a(t).split(" "),o=i[0],n=o.match(/^\[(.+)\]$/),r=n&&n[1],s=e(r,o),u=d.sortDataParsers[i[1]];return t=u?function(t){return t&&u(s(t))}:function(t){return t&&s(t)}}function e(t,e){var i;return i=t?function(e){return e.getAttribute(t)}:function(t){var i=t.querySelector(e);return i&&p(i)}}return t}();d.sortDataParsers={parseInt:function(t){return parseInt(t,10)},parseFloat:function(t){return parseFloat(t)}},d.prototype._sort=function(){var t=this.options.sortBy;if(t){var e=[].concat.apply(t,this.sortHistory),i=f(e,this.options.sortAscending);this.filteredItems.sort(i),t!==this.sortHistory[0]&&this.sortHistory.unshift(t)}},d.prototype._mode=function(){var t=this.options.layoutMode,e=this.modes[t];if(!e)throw Error("No layout mode: "+t);return e.options=this.options[t],e},d.prototype._resetLayout=function(){t.prototype._resetLayout.call(this),this._mode()._resetLayout()},d.prototype._getItemLayoutPosition=function(t){return this._mode()._getItemLayoutPosition(t)},d.prototype._manageStamp=function(t){this._mode()._manageStamp(t)},d.prototype._getContainerSize=function(){return this._mode()._getContainerSize()},d.prototype.needsResizeLayout=function(){return this._mode().needsResizeLayout()},d.prototype.appended=function(t){var e=this.addItems(t);if(e.length){var i=this._filterRevealAdded(e);this.filteredItems=this.filteredItems.concat(i)}},d.prototype.prepended=function(t){var e=this._itemize(t);if(e.length){var i=this.items.slice(0);this.items=e.concat(i),this._resetLayout(),this._manageStamps();var o=this._filterRevealAdded(e);this.layoutItems(i),this.filteredItems=o.concat(this.filteredItems)}},d.prototype._filterRevealAdded=function(t){var e=this._noTransition(function(){return this._filter(t)});return this.layoutItems(e,!0),this.reveal(e),t},d.prototype.insert=function(t){var e=this.addItems(t);if(e.length){var i,o,n=e.length;for(i=0;n>i;i++)o=e[i],this.element.appendChild(o.element);var r=this._filter(e);for(this._noTransition(function(){this.hide(r)}),i=0;n>i;i++)e[i].isLayoutInstant=!0;for(this.arrange(),i=0;n>i;i++)delete e[i].isLayoutInstant;this.reveal(r)}};var c=d.prototype.remove;return d.prototype.remove=function(t){t=o(t);var e=this.getItems(t);if(c.call(this,t),e&&e.length)for(var i=0,r=e.length;r>i;i++){var s=e[i];n(s,this.filteredItems)}},d.prototype.shuffle=function(){for(var t=0,e=this.items.length;e>t;t++){var i=this.items[t];i.sortData.random=Math.random()}this.options.sortBy="random",this._sort(),this._layout()},d.prototype._noTransition=function(t){var e=this.options.transitionDuration;this.options.transitionDuration=0;var i=t.call(this);return this.options.transitionDuration=e,i},d.prototype.getFilteredItemElements=function(){for(var t=[],e=0,i=this.filteredItems.length;i>e;e++)t.push(this.filteredItems[e].element);return t},d}var s=t.jQuery,a=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^\s+|\s+$/g,"")},u=document.documentElement,p=u.textContent?function(t){return t.textContent}:function(t){return t.innerText},h=Object.prototype.toString,f=Array.prototype.indexOf?function(t,e){return t.indexOf(e)}:function(t,e){for(var i=0,o=t.length;o>i;i++)if(t[i]===e)return i;return-1};"function"==typeof define&&define.amd?define(["outlayer/outlayer","get-size/get-size","matches-selector/matches-selector","isotope/js/item","isotope/js/layout-mode","isotope/js/layout-modes/masonry","isotope/js/layout-modes/fit-rows","isotope/js/layout-modes/vertical"],r):t.Isotope=r(t.Outlayer,t.getSize,t.matchesSelector,t.Isotope.Item,t.Isotope.LayoutMode)}(window);
