/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

/*jslint browser: true, white: false, onevar: false */
/*global jQuery, window */

(function ($) {

    /* BEGIN: John Resig's microtemplating stuff */
    var cache = {};

    function tmpl(str, data){
        var fn = !/\W/.test(str) ?
            cache[str] = cache[str] ||
            tmpl(document.getElementById(str).innerHTML) :
            new Function("obj",
                "var p=[],print=function(){p.push.apply(p,arguments);};" +
                "with(obj){p.push('" +
                str
                    .replace(/[\r\t\n]/g, " ")
                    .split("<%").join("\t")
                    .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                    .replace(/\t=(.*?)%>/g, "',$1,'")
                    .split("\t").join("');")
                    .split("%>").join("p.push('")
                    .split("\r").join("\\'")
                + "');}return p.join('');");
        return data ? fn( data ) : fn;
    };
    /* END: John Resig's microtemplating stuff */

    function closer(message, o) {
        function slideComplete() {
            $(this).remove();
        }
        function fadeComplete() {
            $(this).slideUp(100, slideComplete);
        }
        $(message).animate({ opacity: 0 }, { duration: 250, queue: false, complete: fadeComplete });
    }

    function sanitize(str) {
        return str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }

    function displayNotification(el, o){
        var $el = $(el);
        $el.addClass(o.activeClass);
        $el.prepend('<div class="message-closer" aria-label="Close">&times;</div>');
        $el.fadeIn(500);
        if (!$el.hasClass(o.persistentClass) && !$el.hasClass(o.stickyClass) && !$el.hasClass('error')) {
            var timer = $el.attr('data-timer') || o.timer;
            setTimeout(function() {
                closer(el, o);
            }, timer);
        }
    }

    $.fn.notifier = function(options){
        var opts = $.extend({}, $.fn.notify.defaults, options);
        return $(this).each(function() {
            var self = this,
                o = $.metadata ? $.extend(opts, $(this).metadata()) : opts;
            if (o.scrollcss) {
                $(window).scroll(function() {
                    $(self).css(o.scrollcss);
                });
            }
            $('.' + o.messageClass, self).addClass(o.newClass);
            var selector = '.' + o.newClass + '.' + o.messageClass;
            $('body').on("click", selector + ' .message-closer', function(e) {
              closer(this.parentNode, o);
            });
            displayNotification($(selector).get(0), o);
        });
    };

    $.fn.notify = function(msg_or_opts, options) {
        var opts;
        // For backwards compatibility
        if (typeof msg_or_opts === 'string') {
            opts = $.extend({message: msg_or_opts}, $.fn.notify.defaults, options);
        } else {
            opts = $.extend({}, $.fn.notify.defaults, msg_or_opts);
        }
        // For backwards compatibility
        if (opts.status === 'success') {
            opts.status = 'confirm';
        }
        // For compatibility with the TG default of "ok"
        if (opts.status === 'ok') {
            opts.status = 'info';
        }
        return $(this).each(function() {
            if (opts.message) {
                var o = $.metadata ? $.extend(opts, $(this).metadata()) : opts;
                if (o.sanitize) {
                    o.message = sanitize(o.message);
                    o.title = sanitize(o.title);
                }
                var html = tmpl(o.tmpl, o);
                $(this).append(html);
                var newMsgEl = $('.message:last-child', this).get(0);
                displayNotification(newMsgEl, o);
            } else {
                if (window.console) {
                    //#JSCOVERAGE_IF window.console
                    window.console.warn("No message was set in notify's config: ", o);
                    //#JSCOVERAGE_ENDIF
                }
            }
        });
    };

    $.fn.notify.defaults = {
        status: 'info',
        interval: 500,
        timer: 15000,
        sticky: false,
        title: '',
        sanitize: true,
        tmpl: '<div class="message <%=newClass%> <%=status%> <% if (sticky) { %><%=stickyClass %><% } %>" data-timer="<%=timer%>"><% if (title) { %><h6><%=title%></h6><% } %><div class="content"><%=message%></div></div>',
        stickyClass: 'notify-sticky',
		persistentClass: 'notify-persistent',
		persistentCookie: 'notify-persistent-closed',
        newClass: 'notify-new',
        activeClass: 'notify-active',
        inactiveClass: 'notify-inactive',
        messageClass: 'message',
    };

}(jQuery));
;
/*

Tooltipster 3.3.0 | 2014-11-08
A rockin' custom tooltip jQuery plugin

Developed by Caleb Jacob under the MIT license http://opensource.org/licenses/MIT

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

;(function ($, window, document) {

	var pluginName = "tooltipster",
		defaults = {
			animation: 'fade',
			arrow: true,
			arrowColor: '',
			autoClose: true,
			content: null,
			contentAsHTML: false,
			contentCloning: true,
			debug: true,
			delay: 200,
			minWidth: 0,
			maxWidth: null,
			functionInit: function(origin, content) {},
			functionBefore: function(origin, continueTooltip) {
				continueTooltip();
			},
			functionReady: function(origin, tooltip) {},
			functionAfter: function(origin) {},
			hideOnClick: false,
			icon: '(?)',
			iconCloning: true,
			iconDesktop: false,
			iconTouch: false,
			iconTheme: 'tooltipster-icon',
			interactive: false,
			interactiveTolerance: 350,
			multiple: false,
			offsetX: 0,
			offsetY: 0,
			onlyOne: false,
			position: 'top',
			positionTracker: false,
			positionTrackerCallback: function(origin){
				// the default tracker callback will close the tooltip when the trigger is
				// 'hover' (see https://github.com/iamceege/tooltipster/pull/253)
				if(this.option('trigger') == 'hover' && this.option('autoClose')) {
					this.hide();
				}
			},
			restoration: 'current',
			speed: 350,
			timer: 0,
			theme: 'tooltipster-default',
			touchDevices: true,
			trigger: 'hover',
			updateAnimation: true
		};
	
	function Plugin(element, options) {
		
		// list of instance variables
		
		this.bodyOverflowX;
		// stack of custom callbacks provided as parameters to API methods
		this.callbacks = {
			hide: [],
			show: []
		};
		this.checkInterval = null;
		// this will be the user content shown in the tooltip. A capital "C" is used because there is also a method called content()
		this.Content;
		// this is the original element which is being applied the tooltipster plugin
		this.$el = $(element);
		// this will be the element which triggers the appearance of the tooltip on hover/click/custom events.
		// it will be the same as this.$el if icons are not used (see in the options), otherwise it will correspond to the created icon
		this.$elProxy;
		this.elProxyPosition;
		this.enabled = true;
		this.options = $.extend({}, defaults, options);
		this.mouseIsOverProxy = false;
		// a unique namespace per instance, for easy selective unbinding
		this.namespace = 'tooltipster-'+ Math.round(Math.random()*100000);
		// Status (capital S) can be either : appearing, shown, disappearing, hidden
		this.Status = 'hidden';
		this.timerHide = null;
		this.timerShow = null;
		// this will be the tooltip element (jQuery wrapped HTML element)
		this.$tooltip;
		
		// for backward compatibility
		this.options.iconTheme = this.options.iconTheme.replace('.', '');
		this.options.theme = this.options.theme.replace('.', '');
		
		// launch
		
		this._init();
	}
	
	Plugin.prototype = {
		
		_init: function() {
			
			var self = this;
			
			// disable the plugin on old browsers (including IE7 and lower)
			if (document.querySelector) {
				
				// note : the content is null (empty) by default and can stay that way if the plugin remains initialized but not fed any content. The tooltip will just not appear.
				
				// let's save the initial value of the title attribute for later restoration if need be.
				var initialTitle = null;
				// it will already have been saved in case of multiple tooltips
				if (self.$el.data('tooltipster-initialTitle') === undefined) {
					
					initialTitle = self.$el.attr('title');
					
					// we do not want initialTitle to have the value "undefined" because of how jQuery's .data() method works
					if (initialTitle === undefined) initialTitle = null;
					
					self.$el.data('tooltipster-initialTitle', initialTitle);
				}
				
				// if content is provided in the options, its has precedence over the title attribute.
				// Note : an empty string is considered content, only 'null' represents the absence of content.
				// Also, an existing title="" attribute will result in an empty string content
				if (self.options.content !== null){
					self._content_set(self.options.content);
				}
				else {
					self._content_set(initialTitle);
				}
				
				var c = self.options.functionInit.call(self.$el, self.$el, self.Content);
				if(typeof c !== 'undefined') self._content_set(c);
				
				self.$el
					// strip the title off of the element to prevent the default tooltips from popping up
					.removeAttr('title')
					// to be able to find all instances on the page later (upon window events in particular)
					.addClass('tooltipstered');

				// detect if we're changing the tooltip origin to an icon
				// note about this condition : if the device has touch capability and self.options.iconTouch is false, you'll have no icons event though you may consider your device as a desktop if it also has a mouse. Not sure why someone would have this use case though.
				if ((!deviceHasTouchCapability && self.options.iconDesktop) || (deviceHasTouchCapability && self.options.iconTouch)) {
					
					// TODO : the tooltip should be automatically be given an absolute position to be near the origin. Otherwise, when the origin is floating or what, it's going to be nowhere near it and disturb the position flow of the page elements. It will imply that the icon also detects when its origin moves, to follow it : not trivial.
					// Until it's done, the icon feature does not really make sense since the user still has most of the work to do by himself
					
					// if the icon provided is in the form of a string
					if(typeof self.options.icon === 'string'){
						// wrap it in a span with the icon class
						self.$elProxy = $('<span class="'+ self.options.iconTheme +'"></span>');
						self.$elProxy.text(self.options.icon);
					}
					// if it is an object (sensible choice)
					else {
						// (deep) clone the object if iconCloning == true, to make sure every instance has its own proxy. We use the icon without wrapping, no need to. We do not give it a class either, as the user will undoubtedly style the object on his own and since our css properties may conflict with his own
						if (self.options.iconCloning) self.$elProxy = self.options.icon.clone(true);
						else self.$elProxy = self.options.icon;
					}
					
					self.$elProxy.insertAfter(self.$el);
				}
				else {
					self.$elProxy = self.$el;
				}
				
				// for 'click' and 'hover' triggers : bind on events to open the tooltip. Closing is now handled in _showNow() because of its bindings.
				// Notes about touch events :
					// - mouseenter, mouseleave and clicks happen even on pure touch devices because they are emulated. deviceIsPureTouch() is a simple attempt to detect them.
					// - on hybrid devices, we do not prevent touch gesture from opening tooltips. It would be too complex to differentiate real mouse events from emulated ones.
					// - we check deviceIsPureTouch() at each event rather than prior to binding because the situation may change during browsing
				if (self.options.trigger == 'hover') {
					
					// these binding are for mouse interaction only
					self.$elProxy
						.on('mouseenter.'+ self.namespace, function() {
							if (!deviceIsPureTouch() || self.options.touchDevices) {
								self.mouseIsOverProxy = true;
								self._show();
							}
						})
						.on('mouseleave.'+ self.namespace, function() {
							if (!deviceIsPureTouch() || self.options.touchDevices) {
								self.mouseIsOverProxy = false;
							}
						});
					
					// for touch interaction only
					if (deviceHasTouchCapability && self.options.touchDevices) {
						
						// for touch devices, we immediately display the tooltip because we cannot rely on mouseleave to handle the delay
						self.$elProxy.on('touchstart.'+ self.namespace, function() {
							self._showNow();
						});
					}
				}
				else if (self.options.trigger == 'click') {
					
					// note : for touch devices, we do not bind on touchstart, we only rely on the emulated clicks (triggered by taps)
					self.$elProxy.on('click.'+ self.namespace, function() {
						if (!deviceIsPureTouch() || self.options.touchDevices) {
							self._show();
						}
					});
				}
			}
		},
		
		// this function will schedule the opening of the tooltip after the delay, if there is one
		_show: function() {
			
			var self = this;
			
			if (self.Status != 'shown' && self.Status != 'appearing') {
				
				if (self.options.delay) {
					self.timerShow = setTimeout(function(){
						
						// for hover trigger, we check if the mouse is still over the proxy, otherwise we do not show anything
						if (self.options.trigger == 'click' || (self.options.trigger == 'hover' && self.mouseIsOverProxy)) {
							self._showNow();
						}
					}, self.options.delay);
				}
				else self._showNow();
			}
		},
		
		// this function will open the tooltip right away
		_showNow: function(callback) {
			
			var self = this;
			
			// call our constructor custom function before continuing
			self.options.functionBefore.call(self.$el, self.$el, function() {
				
				// continue only if the tooltip is enabled and has any content
				if (self.enabled && self.Content !== null) {
				
					// save the method callback and cancel hide method callbacks
					if (callback) self.callbacks.show.push(callback);
					self.callbacks.hide = [];
					
					//get rid of any appearance timer
					clearTimeout(self.timerShow);
					self.timerShow = null;
					clearTimeout(self.timerHide);
					self.timerHide = null;
					
					// if we only want one tooltip open at a time, close all auto-closing tooltips currently open and not already disappearing
					if (self.options.onlyOne) {
						$('.tooltipstered').not(self.$el).each(function(i,el) {
							
							var $el = $(el),
								nss = $el.data('tooltipster-ns');
							
							// iterate on all tooltips of the element
							$.each(nss, function(i, ns){
								var instance = $el.data(ns),
									// we have to use the public methods here
									s = instance.status(),
									ac = instance.option('autoClose');
								
								if (s !== 'hidden' && s !== 'disappearing' && ac) {
									instance.hide();
								}
							});
						});
					}
					
					var finish = function() {
						self.Status = 'shown';
						
						// trigger any show method custom callbacks and reset them
						$.each(self.callbacks.show, function(i,c) { c.call(self.$el); });
						self.callbacks.show = [];
					};
					
					// if this origin already has its tooltip open
					if (self.Status !== 'hidden') {
						
						// the timer (if any) will start (or restart) right now
						var extraTime = 0;
						
						// if it was disappearing, cancel that
						if (self.Status === 'disappearing') {
							
							self.Status = 'appearing';
							
							if (supportsTransitions()) {
								
								self.$tooltip
									.clearQueue()
									.removeClass('tooltipster-dying')
									.addClass('tooltipster-'+ self.options.animation +'-show');
								
								if (self.options.speed > 0) self.$tooltip.delay(self.options.speed);
								
								self.$tooltip.queue(finish);
							}
							else {
								// in case the tooltip was currently fading out, bring it back to life
								self.$tooltip
									.stop()
									.fadeIn(finish);
							}
						}
						// if the tooltip is already open, we still need to trigger the method custom callback
						else if(self.Status === 'shown') {
							finish();
						}
					}
					// if the tooltip isn't already open, open that sucker up!
					else {
						
						self.Status = 'appearing';
						
						// the timer (if any) will start when the tooltip has fully appeared after its transition
						var extraTime = self.options.speed;
						
						// disable horizontal scrollbar to keep overflowing tooltips from jacking with it and then restore it to its previous value
						self.bodyOverflowX = $('body').css('overflow-x');
						$('body').css('overflow-x', 'hidden');
						
						// get some other settings related to building the tooltip
						var animation = 'tooltipster-' + self.options.animation,
							animationSpeed = '-webkit-transition-duration: '+ self.options.speed +'ms; -webkit-animation-duration: '+ self.options.speed +'ms; -moz-transition-duration: '+ self.options.speed +'ms; -moz-animation-duration: '+ self.options.speed +'ms; -o-transition-duration: '+ self.options.speed +'ms; -o-animation-duration: '+ self.options.speed +'ms; -ms-transition-duration: '+ self.options.speed +'ms; -ms-animation-duration: '+ self.options.speed +'ms; transition-duration: '+ self.options.speed +'ms; animation-duration: '+ self.options.speed +'ms;',
							minWidth = self.options.minWidth ? 'min-width:'+ Math.round(self.options.minWidth) +'px;' : '',
							maxWidth = self.options.maxWidth ? 'max-width:'+ Math.round(self.options.maxWidth) +'px;' : '',
							pointerEvents = self.options.interactive ? 'pointer-events: auto;' : '';
						
						// build the base of our tooltip
						self.$tooltip = $('<div class="tooltipster-base '+ self.options.theme +'" style="'+ minWidth +' '+ maxWidth +' '+ pointerEvents +' '+ animationSpeed +'"><div class="tooltipster-content"></div></div>');
						
						// only add the animation class if the user has a browser that supports animations
						if (supportsTransitions()) self.$tooltip.addClass(animation);
						
						// insert the content
						self._content_insert();
						
						// attach
						self.$tooltip.appendTo('body');
						
						// do all the crazy calculations and positioning
						self.reposition();
						
						// call our custom callback since the content of the tooltip is now part of the DOM
						self.options.functionReady.call(self.$el, self.$el, self.$tooltip);
						
						// animate in the tooltip
						if (supportsTransitions()) {
							
							self.$tooltip.addClass(animation + '-show');
							
							if(self.options.speed > 0) self.$tooltip.delay(self.options.speed);
							
							self.$tooltip.queue(finish);
						}
						else {
							self.$tooltip.css('display', 'none').fadeIn(self.options.speed, finish);
						}
						
						// will check if our tooltip origin is removed while the tooltip is shown
						self._interval_set();
						
						// reposition on scroll (otherwise position:fixed element's tooltips will move away form their origin) and on resize (in case position can/has to be changed)
						$(window).on('scroll.'+ self.namespace +' resize.'+ self.namespace, function() {
							self.reposition();
						});
						
						// auto-close bindings
						if (self.options.autoClose) {
							
							// in case a listener is already bound for autoclosing (mouse or touch, hover or click), unbind it first
							$('body').off('.'+ self.namespace);
							
							// here we'll have to set different sets of bindings for both touch and mouse
							if (self.options.trigger == 'hover') {
								
								// if the user touches the body, hide
								if (deviceHasTouchCapability) {
									// timeout 0 : explanation below in click section
									setTimeout(function() {
										// we don't want to bind on click here because the initial touchstart event has not yet triggered its click event, which is thus about to happen
										$('body').on('touchstart.'+ self.namespace, function() {
											self.hide();
										});
									}, 0);
								}
								
								// if we have to allow interaction
								if (self.options.interactive) {
									
									// touch events inside the tooltip must not close it
									if (deviceHasTouchCapability) {
										self.$tooltip.on('touchstart.'+ self.namespace, function(event) {
											event.stopPropagation();
										});
									}
									
									// as for mouse interaction, we get rid of the tooltip only after the mouse has spent some time out of it
									var tolerance = null;
									
									self.$elProxy.add(self.$tooltip)
										// hide after some time out of the proxy and the tooltip
										.on('mouseleave.'+ self.namespace + '-autoClose', function() {
											clearTimeout(tolerance);
											tolerance = setTimeout(function(){
												self.hide();
											}, self.options.interactiveTolerance);
										})
										// suspend timeout when the mouse is over the proxy or the tooltip
										.on('mouseenter.'+ self.namespace + '-autoClose', function() {
											clearTimeout(tolerance);
										});
								}
								// if this is a non-interactive tooltip, get rid of it if the mouse leaves
								else {
									self.$elProxy.on('mouseleave.'+ self.namespace + '-autoClose', function() {
										self.hide();
									});
								}
								
								// close the tooltip when the proxy gets a click (common behavior of native tooltips)
								if (self.options.hideOnClick) {
									
									self.$elProxy.on('click.'+ self.namespace + '-autoClose', function() {
										self.hide();
									});
								}
							}
							// here we'll set the same bindings for both clicks and touch on the body to hide the tooltip
							else if(self.options.trigger == 'click'){
								
								// use a timeout to prevent immediate closing if the method was called on a click event and if options.delay == 0 (because of bubbling)
								setTimeout(function() {
									$('body').on('click.'+ self.namespace +' touchstart.'+ self.namespace, function() {
										self.hide();
									});
								}, 0);
								
								// if interactive, we'll stop the events that were emitted from inside the tooltip to stop autoClosing
								if (self.options.interactive) {
									
									// note : the touch events will just not be used if the plugin is not enabled on touch devices
									self.$tooltip.on('click.'+ self.namespace +' touchstart.'+ self.namespace, function(event) {
										event.stopPropagation();
									});
								}
							}
						}
					}
					
					// if we have a timer set, let the countdown begin
					if (self.options.timer > 0) {
						
						self.timerHide = setTimeout(function() {
							self.timerHide = null;
							self.hide();
						}, self.options.timer + extraTime);
					}
				}
			});
		},
		
		_interval_set: function() {
			
			var self = this;
			
			self.checkInterval = setInterval(function() {
				
				// if the tooltip and/or its interval should be stopped
				if (
						// if the origin has been removed
						$('body').find(self.$el).length === 0
						// if the elProxy has been removed
					||	$('body').find(self.$elProxy).length === 0
						// if the tooltip has been closed
					||	self.Status == 'hidden'
						// if the tooltip has somehow been removed
					||	$('body').find(self.$tooltip).length === 0
				) {
					// remove the tooltip if it's still here
					if (self.Status == 'shown' || self.Status == 'appearing') self.hide();
					
					// clear this interval as it is no longer necessary
					self._interval_cancel();
				}
				// if everything is alright
				else {
					// compare the former and current positions of the elProxy to reposition the tooltip if need be
					if(self.options.positionTracker){
						
						var p = self._repositionInfo(self.$elProxy),
							identical = false;
						
						// compare size first (a change requires repositioning too)
						if(areEqual(p.dimension, self.elProxyPosition.dimension)){
							
							// for elements with a fixed position, we track the top and left properties (relative to window)
							if(self.$elProxy.css('position') === 'fixed'){
								if(areEqual(p.position, self.elProxyPosition.position)) identical = true;
							}
							// otherwise, track total offset (relative to document)
							else {
								if(areEqual(p.offset, self.elProxyPosition.offset)) identical = true;
							}
						}
						
						if(!identical){
							self.reposition();
							self.options.positionTrackerCallback.call(self, self.$el);
						}
					}
				}
			}, 200);
		},
		
		_interval_cancel: function() {
			clearInterval(this.checkInterval);
			// clean delete
			this.checkInterval = null;
		},
		
		_content_set: function(content) {
			// clone if asked. Cloning the object makes sure that each instance has its own version of the content (in case a same object were provided for several instances)
			// reminder : typeof null === object
			if (typeof content === 'object' && content !== null && this.options.contentCloning) {
				content = content.clone(true);
			}
			this.Content = content;
		},
		
		_content_insert: function() {
			
			var self = this,
				$d = this.$tooltip.find('.tooltipster-content');
			
			if (typeof self.Content === 'string' && !self.options.contentAsHTML) {
				$d.text(self.Content);
			}
			else {
				$d
					.empty()
					.append(self.Content);
			}
		},
		
		_update: function(content) {
			
			var self = this;
			
			// change the content
			self._content_set(content);
			
			if (self.Content !== null) {
				
				// update the tooltip if it is open
				if (self.Status !== 'hidden') {
					
					// reset the content in the tooltip
					self._content_insert();
					
					// reposition and resize the tooltip
					self.reposition();
					
					// if we want to play a little animation showing the content changed
					if (self.options.updateAnimation) {
						
						if (supportsTransitions()) {
							
							self.$tooltip.css({
								'width': '',
								'-webkit-transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms',
								'-moz-transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms',
								'-o-transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms',
								'-ms-transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms',
								'transition': 'all ' + self.options.speed + 'ms, width 0ms, height 0ms, left 0ms, top 0ms'
							}).addClass('tooltipster-content-changing');
							
							// reset the CSS transitions and finish the change animation
							setTimeout(function() {
								
								if(self.Status != 'hidden'){
									
									self.$tooltip.removeClass('tooltipster-content-changing');
									
									// after the changing animation has completed, reset the CSS transitions
									setTimeout(function() {
										
										if(self.Status !== 'hidden'){
											self.$tooltip.css({
												'-webkit-transition': self.options.speed + 'ms',
												'-moz-transition': self.options.speed + 'ms',
												'-o-transition': self.options.speed + 'ms',
												'-ms-transition': self.options.speed + 'ms',
												'transition': self.options.speed + 'ms'
											});
										}
									}, self.options.speed);
								}
							}, self.options.speed);
						}
						else {
							self.$tooltip.fadeTo(self.options.speed, 0.5, function() {
								if(self.Status != 'hidden'){
									self.$tooltip.fadeTo(self.options.speed, 1);
								}
							});
						}
					}
				}
			}
			else {
				self.hide();
			}
		},
		
		_repositionInfo: function($el) {
			return {
				dimension: {
					height: $el.outerHeight(false),
					width: $el.outerWidth(false)
				},
				offset: $el.offset(),
				position: {
					left: parseInt($el.css('left')),
					top: parseInt($el.css('top'))
				}
			};
		},
		
		hide: function(callback) {
			
			var self = this;
			
			// save the method custom callback and cancel any show method custom callbacks
			if (callback) self.callbacks.hide.push(callback);
			self.callbacks.show = [];
			
			// get rid of any appearance timeout
			clearTimeout(self.timerShow);
			self.timerShow = null;
			clearTimeout(self.timerHide);
			self.timerHide = null;
			
			var finishCallbacks = function() {
				// trigger any hide method custom callbacks and reset them
				$.each(self.callbacks.hide, function(i,c) { c.call(self.$el); });
				self.callbacks.hide = [];
			};
			
			// hide
			if (self.Status == 'shown' || self.Status == 'appearing') {
				
				self.Status = 'disappearing';
				
				var finish = function() {
					
					self.Status = 'hidden';
					
					// detach our content object first, so the next jQuery's remove() call does not unbind its event handlers
					if (typeof self.Content == 'object' && self.Content !== null) {
						self.Content.detach();
					}
					
					self.$tooltip.remove();
					self.$tooltip = null;
					
					// unbind orientationchange, scroll and resize listeners
					$(window).off('.'+ self.namespace);
					
					$('body')
						// unbind any auto-closing click/touch listeners
						.off('.'+ self.namespace)
						.css('overflow-x', self.bodyOverflowX);
					
					// unbind any auto-closing click/touch listeners
					$('body').off('.'+ self.namespace);
					
					// unbind any auto-closing hover listeners
					self.$elProxy.off('.'+ self.namespace + '-autoClose');
					
					// call our constructor custom callback function
					self.options.functionAfter.call(self.$el, self.$el);
					
					// call our method custom callbacks functions
					finishCallbacks();
				};
				
				if (supportsTransitions()) {
					
					self.$tooltip
						.clearQueue()
						.removeClass('tooltipster-' + self.options.animation + '-show')
						// for transitions only
						.addClass('tooltipster-dying');
					
					if(self.options.speed > 0) self.$tooltip.delay(self.options.speed);
					
					self.$tooltip.queue(finish);
				}
				else {
					self.$tooltip
						.stop()
						.fadeOut(self.options.speed, finish);
				}
			}
			// if the tooltip is already hidden, we still need to trigger the method custom callback
			else if(self.Status == 'hidden') {
				finishCallbacks();
			}
			
			return self;
		},
		
		// the public show() method is actually an alias for the private showNow() method
		show: function(callback) {
			this._showNow(callback);
			return this;
		},
		
		// 'update' is deprecated in favor of 'content' but is kept for backward compatibility
		update: function(c) {
			return this.content(c);
		},
		content: function(c) {
			// getter method
			if(typeof c === 'undefined'){
				return this.Content;
			}
			// setter method
			else {
				this._update(c);
				return this;
			}
		},
		
		reposition: function() {
			
			var self = this;
			
			// in case the tooltip has been removed from DOM manually
			if ($('body').find(self.$tooltip).length !== 0) {
				
				// reset width
				self.$tooltip.css('width', '');
				
				// find variables to determine placement
				self.elProxyPosition = self._repositionInfo(self.$elProxy);
				var arrowReposition = null,
					windowWidth = $(window).width(),
					// shorthand
					proxy = self.elProxyPosition,
					tooltipWidth = self.$tooltip.outerWidth(false),
					tooltipInnerWidth = self.$tooltip.innerWidth() + 1, // this +1 stops FireFox from sometimes forcing an additional text line
					tooltipHeight = self.$tooltip.outerHeight(false);
				
				// if this is an <area> tag inside a <map>, all hell breaks loose. Recalculate all the measurements based on coordinates
				if (self.$elProxy.is('area')) {
					var areaShape = self.$elProxy.attr('shape'),
						mapName = self.$elProxy.parent().attr('name'),
						map = $('img[usemap="#'+ mapName +'"]'),
						mapOffsetLeft = map.offset().left,
						mapOffsetTop = map.offset().top,
						areaMeasurements = self.$elProxy.attr('coords') !== undefined ? self.$elProxy.attr('coords').split(',') : undefined;
					
					if (areaShape == 'circle') {
						var areaLeft = parseInt(areaMeasurements[0]),
							areaTop = parseInt(areaMeasurements[1]),
							areaWidth = parseInt(areaMeasurements[2]);
						proxy.dimension.height = areaWidth * 2;
						proxy.dimension.width = areaWidth * 2;
						proxy.offset.top = mapOffsetTop + areaTop - areaWidth;
						proxy.offset.left = mapOffsetLeft + areaLeft - areaWidth;
					}
					else if (areaShape == 'rect') {
						var areaLeft = parseInt(areaMeasurements[0]),
							areaTop = parseInt(areaMeasurements[1]),
							areaRight = parseInt(areaMeasurements[2]),
							areaBottom = parseInt(areaMeasurements[3]);
						proxy.dimension.height = areaBottom - areaTop;
						proxy.dimension.width = areaRight - areaLeft;
						proxy.offset.top = mapOffsetTop + areaTop;
						proxy.offset.left = mapOffsetLeft + areaLeft;
					}
					else if (areaShape == 'poly') {
						var areaXs = [],
							areaYs = [],
							areaSmallestX = 0,
							areaSmallestY = 0,
							areaGreatestX = 0,
							areaGreatestY = 0,
							arrayAlternate = 'even';
						
						for (var i = 0; i < areaMeasurements.length; i++) {
							var areaNumber = parseInt(areaMeasurements[i]);
							
							if (arrayAlternate == 'even') {
								if (areaNumber > areaGreatestX) {
									areaGreatestX = areaNumber;
									if (i === 0) {
										areaSmallestX = areaGreatestX;
									}
								}
								
								if (areaNumber < areaSmallestX) {
									areaSmallestX = areaNumber;
								}
								
								arrayAlternate = 'odd';
							}
							else {
								if (areaNumber > areaGreatestY) {
									areaGreatestY = areaNumber;
									if (i == 1) {
										areaSmallestY = areaGreatestY;
									}
								}
								
								if (areaNumber < areaSmallestY) {
									areaSmallestY = areaNumber;
								}
								
								arrayAlternate = 'even';
							}
						}
					
						proxy.dimension.height = areaGreatestY - areaSmallestY;
						proxy.dimension.width = areaGreatestX - areaSmallestX;
						proxy.offset.top = mapOffsetTop + areaSmallestY;
						proxy.offset.left = mapOffsetLeft + areaSmallestX;
					}
					else {
						proxy.dimension.height = map.outerHeight(false);
						proxy.dimension.width = map.outerWidth(false);
						proxy.offset.top = mapOffsetTop;
						proxy.offset.left = mapOffsetLeft;
					}
				}
				
				// our function and global vars for positioning our tooltip
				var myLeft = 0,
					myLeftMirror = 0,
					myTop = 0,
					offsetY = parseInt(self.options.offsetY),
					offsetX = parseInt(self.options.offsetX),
					// this is the arrow position that will eventually be used. It may differ from the position option if the tooltip cannot be displayed in this position
					practicalPosition = self.options.position;
				
				// a function to detect if the tooltip is going off the screen horizontally. If so, reposition the crap out of it!
				function dontGoOffScreenX() {
				
					var windowLeft = $(window).scrollLeft();
					
					// if the tooltip goes off the left side of the screen, line it up with the left side of the window
					if((myLeft - windowLeft) < 0) {
						arrowReposition = myLeft - windowLeft;
						myLeft = windowLeft;
					}
					
					// if the tooltip goes off the right of the screen, line it up with the right side of the window
					if (((myLeft + tooltipWidth) - windowLeft) > windowWidth) {
						arrowReposition = myLeft - ((windowWidth + windowLeft) - tooltipWidth);
						myLeft = (windowWidth + windowLeft) - tooltipWidth;
					}
				}
				
				// a function to detect if the tooltip is going off the screen vertically. If so, switch to the opposite!
				function dontGoOffScreenY(switchTo, switchFrom) {
					// if it goes off the top off the page
					if(((proxy.offset.top - $(window).scrollTop() - tooltipHeight - offsetY - 12) < 0) && (switchFrom.indexOf('top') > -1)) {
						practicalPosition = switchTo;
					}
					
					// if it goes off the bottom of the page
					if (((proxy.offset.top + proxy.dimension.height + tooltipHeight + 12 + offsetY) > ($(window).scrollTop() + $(window).height())) && (switchFrom.indexOf('bottom') > -1)) {
						practicalPosition = switchTo;
						myTop = (proxy.offset.top - tooltipHeight) - offsetY - 12;
					}
				}
				
				if(practicalPosition == 'top') {
					var leftDifference = (proxy.offset.left + tooltipWidth) - (proxy.offset.left + proxy.dimension.width);
					myLeft = (proxy.offset.left + offsetX) - (leftDifference / 2);
					myTop = (proxy.offset.top - tooltipHeight) - offsetY - 12;
					dontGoOffScreenX();
					dontGoOffScreenY('bottom', 'top');
				}
				
				if(practicalPosition == 'top-left') {
					myLeft = proxy.offset.left + offsetX;
					myTop = (proxy.offset.top - tooltipHeight) - offsetY - 12;
					dontGoOffScreenX();
					dontGoOffScreenY('bottom-left', 'top-left');
				}
				
				if(practicalPosition == 'top-right') {
					myLeft = (proxy.offset.left + proxy.dimension.width + offsetX) - tooltipWidth;
					myTop = (proxy.offset.top - tooltipHeight) - offsetY - 12;
					dontGoOffScreenX();
					dontGoOffScreenY('bottom-right', 'top-right');
				}
				
				if(practicalPosition == 'bottom') {
					var leftDifference = (proxy.offset.left + tooltipWidth) - (proxy.offset.left + proxy.dimension.width);
					myLeft = proxy.offset.left - (leftDifference / 2) + offsetX;
					myTop = (proxy.offset.top + proxy.dimension.height) + offsetY + 12;
					dontGoOffScreenX();
					dontGoOffScreenY('top', 'bottom');
				}
				
				if(practicalPosition == 'bottom-left') {
					myLeft = proxy.offset.left + offsetX;
					myTop = (proxy.offset.top + proxy.dimension.height) + offsetY + 12;
					dontGoOffScreenX();
					dontGoOffScreenY('top-left', 'bottom-left');
				}
				
				if(practicalPosition == 'bottom-right') {
					myLeft = (proxy.offset.left + proxy.dimension.width + offsetX) - tooltipWidth;
					myTop = (proxy.offset.top + proxy.dimension.height) + offsetY + 12;
					dontGoOffScreenX();
					dontGoOffScreenY('top-right', 'bottom-right');
				}
				
				if(practicalPosition == 'left') {
					myLeft = proxy.offset.left - offsetX - tooltipWidth - 12;
					myLeftMirror = proxy.offset.left + offsetX + proxy.dimension.width + 12;
					var topDifference = (proxy.offset.top + tooltipHeight) - (proxy.offset.top + proxy.dimension.height);
					myTop = proxy.offset.top - (topDifference / 2) - offsetY;
					
					// if the tooltip goes off boths sides of the page
					if((myLeft < 0) && ((myLeftMirror + tooltipWidth) > windowWidth)) {
						var borderWidth = parseFloat(self.$tooltip.css('border-width')) * 2,
							newWidth = (tooltipWidth + myLeft) - borderWidth;
						self.$tooltip.css('width', newWidth + 'px');
						
						tooltipHeight = self.$tooltip.outerHeight(false);
						myLeft = proxy.offset.left - offsetX - newWidth - 12 - borderWidth;
						topDifference = (proxy.offset.top + tooltipHeight) - (proxy.offset.top + proxy.dimension.height);
						myTop = proxy.offset.top - (topDifference / 2) - offsetY;
					}
					
					// if it only goes off one side, flip it to the other side
					else if(myLeft < 0) {
						myLeft = proxy.offset.left + offsetX + proxy.dimension.width + 12;
						arrowReposition = 'left';
					}
				}
				
				if(practicalPosition == 'right') {
					myLeft = proxy.offset.left + offsetX + proxy.dimension.width + 12;
					myLeftMirror = proxy.offset.left - offsetX - tooltipWidth - 12;
					var topDifference = (proxy.offset.top + tooltipHeight) - (proxy.offset.top + proxy.dimension.height);
					myTop = proxy.offset.top - (topDifference / 2) - offsetY;
					
					// if the tooltip goes off boths sides of the page
					if(((myLeft + tooltipWidth) > windowWidth) && (myLeftMirror < 0)) {
						var borderWidth = parseFloat(self.$tooltip.css('border-width')) * 2,
							newWidth = (windowWidth - myLeft) - borderWidth;
						self.$tooltip.css('width', newWidth + 'px');
						
						tooltipHeight = self.$tooltip.outerHeight(false);
						topDifference = (proxy.offset.top + tooltipHeight) - (proxy.offset.top + proxy.dimension.height);
						myTop = proxy.offset.top - (topDifference / 2) - offsetY;
					}
						
					// if it only goes off one side, flip it to the other side
					else if((myLeft + tooltipWidth) > windowWidth) {
						myLeft = proxy.offset.left - offsetX - tooltipWidth - 12;
						arrowReposition = 'right';
					}
				}
				
				// if arrow is set true, style it and append it
				if (self.options.arrow) {
	
					var arrowClass = 'tooltipster-arrow-' + practicalPosition;
					
					// set color of the arrow
					if(self.options.arrowColor.length < 1) {
						var arrowColor = self.$tooltip.css('background-color');
					}
					else {
						var arrowColor = self.options.arrowColor;
					}
					
					// if the tooltip was going off the page and had to re-adjust, we need to update the arrow's position
					if (!arrowReposition) {
						arrowReposition = '';
					}
					else if (arrowReposition == 'left') {
						arrowClass = 'tooltipster-arrow-right';
						arrowReposition = '';
					}
					else if (arrowReposition == 'right') {
						arrowClass = 'tooltipster-arrow-left';
						arrowReposition = '';
					}
					else {
						arrowReposition = 'left:'+ Math.round(arrowReposition) +'px;';
					}
					
					// building the logic to create the border around the arrow of the tooltip
					if ((practicalPosition == 'top') || (practicalPosition == 'top-left') || (practicalPosition == 'top-right')) {
						var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-bottom-width')),
							tooltipBorderColor = self.$tooltip.css('border-bottom-color');
					}
					else if ((practicalPosition == 'bottom') || (practicalPosition == 'bottom-left') || (practicalPosition == 'bottom-right')) {
						var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-top-width')),
							tooltipBorderColor = self.$tooltip.css('border-top-color');
					}
					else if (practicalPosition == 'left') {
						var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-right-width')),
							tooltipBorderColor = self.$tooltip.css('border-right-color');
					}
					else if (practicalPosition == 'right') {
						var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-left-width')),
							tooltipBorderColor = self.$tooltip.css('border-left-color');
					}
					else {
						var tooltipBorderWidth = parseFloat(self.$tooltip.css('border-bottom-width')),
							tooltipBorderColor = self.$tooltip.css('border-bottom-color');
					}
					
					if (tooltipBorderWidth > 1) {
						tooltipBorderWidth++;
					}
					
					var arrowBorder = '';
					if (tooltipBorderWidth !== 0) {
						var arrowBorderSize = '',
							arrowBorderColor = 'border-color: '+ tooltipBorderColor +';';
						if (arrowClass.indexOf('bottom') !== -1) {
							arrowBorderSize = 'margin-top: -'+ Math.round(tooltipBorderWidth) +'px;';
						}
						else if (arrowClass.indexOf('top') !== -1) {
							arrowBorderSize = 'margin-bottom: -'+ Math.round(tooltipBorderWidth) +'px;';
						}
						else if (arrowClass.indexOf('left') !== -1) {
							arrowBorderSize = 'margin-right: -'+ Math.round(tooltipBorderWidth) +'px;';
						}
						else if (arrowClass.indexOf('right') !== -1) {
							arrowBorderSize = 'margin-left: -'+ Math.round(tooltipBorderWidth) +'px;';
						}
						arrowBorder = '<span class="tooltipster-arrow-border" style="'+ arrowBorderSize +' '+ arrowBorderColor +';"></span>';
					}
					
					// if the arrow already exists, remove and replace it
					self.$tooltip.find('.tooltipster-arrow').remove();
					
					// build out the arrow and append it		
					var arrowConstruct = '<div class="'+ arrowClass +' tooltipster-arrow" style="'+ arrowReposition +'">'+ arrowBorder +'<span style="border-color:'+ arrowColor +';"></span></div>';
					self.$tooltip.append(arrowConstruct);
				}
				
				// position the tooltip
				self.$tooltip.css({'top': Math.round(myTop) + 'px', 'left': Math.round(myLeft) + 'px'});
			}
			
			return self;
		},
		
		enable: function() {
			this.enabled = true;
			return this;
		},
		
		disable: function() {
			// hide first, in case the tooltip would not disappear on its own (autoClose false)
			this.hide();
			this.enabled = false;
			return this;
		},
		
		destroy: function() {
			
			var self = this;
			
			self.hide();
			
			// remove the icon, if any
			if (self.$el[0] !== self.$elProxy[0]) {
				self.$elProxy.remove();
			}
			
			self.$el
				.removeData(self.namespace)
				.off('.'+ self.namespace);
			
			var ns = self.$el.data('tooltipster-ns');
			
			// if there are no more tooltips on this element
			if(ns.length === 1){
				
				// optional restoration of a title attribute
				var title = null;
				if (self.options.restoration === 'previous'){
					title = self.$el.data('tooltipster-initialTitle');
				}
				else if(self.options.restoration === 'current'){
					
					// old school technique to stringify when outerHTML is not supported
					title =
						(typeof self.Content === 'string') ?
						self.Content :
						$('<div></div>').append(self.Content).html();
				}
				
				if (title) {
					self.$el.attr('title', title);
				}
				
				// final cleaning
				self.$el
					.removeClass('tooltipstered')
					.removeData('tooltipster-ns')
					.removeData('tooltipster-initialTitle');
			}
			else {
				// remove the instance namespace from the list of namespaces of tooltips present on the element
				ns = $.grep(ns, function(el, i){
					return el !== self.namespace;
				});
				self.$el.data('tooltipster-ns', ns);
			}
			
			return self;
		},
		
		elementIcon: function() {
			return (this.$el[0] !== this.$elProxy[0]) ? this.$elProxy[0] : undefined;
		},
		
		elementTooltip: function() {
			return this.$tooltip ? this.$tooltip[0] : undefined;
		},
		
		// public methods but for internal use only
		// getter if val is ommitted, setter otherwise
		option: function(o, val) {
			if (typeof val == 'undefined') return this.options[o];
			else {
				this.options[o] = val;
				return this;
			}
		},
		status: function() {
			return this.Status;
		}
	};
	
	$.fn[pluginName] = function () {
		
		// for using in closures
		var args = arguments;
		
		// if we are not in the context of jQuery wrapped HTML element(s) :
		// this happens when calling static methods in the form $.fn.tooltipster('methodName'), or when calling $(sel).tooltipster('methodName or options') where $(sel) does not match anything
		if (this.length === 0) {
			
			// if the first argument is a method name
			if (typeof args[0] === 'string') {
				
				var methodIsStatic = true;
				
				// list static methods here (usable by calling $.fn.tooltipster('methodName');)
				switch (args[0]) {
					
					case 'setDefaults':
						// change default options for all future instances
						$.extend(defaults, args[1]);
						break;
					
					default:
						methodIsStatic = false;
						break;
				}
				
				// $.fn.tooltipster('methodName') calls will return true
				if (methodIsStatic) return true;
				// $(sel).tooltipster('methodName') calls will return the list of objects event though it's empty because chaining should work on empty lists
				else return this;
			}
			// the first argument is undefined or an object of options : we are initalizing but there is no element matched by selector
			else {
				// still chainable : same as above
				return this;
			}
		}
		// this happens when calling $(sel).tooltipster('methodName or options') where $(sel) matches one or more elements
		else {
			
			// method calls
			if (typeof args[0] === 'string') {
				
				var v = '#*$~&';
				
				this.each(function() {
					
					// retrieve the namepaces of the tooltip(s) that exist on that element. We will interact with the first tooltip only.
					var ns = $(this).data('tooltipster-ns'),
						// self represents the instance of the first tooltipster plugin associated to the current HTML object of the loop
						self = ns ? $(this).data(ns[0]) : null;
					
					// if the current element holds a tooltipster instance
					if (self) {
						
						if (typeof self[args[0]] === 'function') {
							// note : args[1] and args[2] may not be defined
							var resp = self[args[0]](args[1], args[2]);
						}
						else {
							throw new Error('Unknown method .tooltipster("' + args[0] + '")');
						}
						
						// if the function returned anything other than the instance itself (which implies chaining)
						if (resp !== self){
							v = resp;
							// return false to stop .each iteration on the first element matched by the selector
							return false;
						}
					}
					else {
						throw new Error('You called Tooltipster\'s "' + args[0] + '" method on an uninitialized element');
					}
				});
				
				return (v !== '#*$~&') ? v : this;
			}
			// first argument is undefined or an object : the tooltip is initializing
			else {
				
				var instances = [],
					// is there a defined value for the multiple option in the options object ?
					multipleIsSet = args[0] && typeof args[0].multiple !== 'undefined',
					// if the multiple option is set to true, or if it's not defined but set to true in the defaults
					multiple = (multipleIsSet && args[0].multiple) || (!multipleIsSet && defaults.multiple),
					// same for debug
					debugIsSet = args[0] && typeof args[0].debug !== 'undefined',
					debug = (debugIsSet && args[0].debug) || (!debugIsSet && defaults.debug);
				
				// initialize a tooltipster instance for each element if it doesn't already have one or if the multiple option is set, and attach the object to it
				this.each(function () {
					
					var go = false,
						ns = $(this).data('tooltipster-ns'),
						instance = null;
					
					if (!ns) {
						go = true;
					}
					else if (multiple) {
						go = true;
					}
					else if (debug) {
						console.log('Tooltipster: one or more tooltips are already attached to this element: ignoring. Use the "multiple" option to attach more tooltips.');
					}
					
					if (go) {
						instance = new Plugin(this, args[0]);
						
						// save the reference of the new instance
						if (!ns) ns = [];
						ns.push(instance.namespace);
						$(this).data('tooltipster-ns', ns)
						
						// save the instance itself
						$(this).data(instance.namespace, instance);
					}
					
					instances.push(instance);
				});
				
				if (multiple) return instances;
				else return this;
			}
		}
	};
	
	// quick & dirty compare function (not bijective nor multidimensional)
	function areEqual(a,b) {
		var same = true;
		$.each(a, function(i, el){
			if(typeof b[i] === 'undefined' || a[i] !== b[i]){
				same = false;
				return false;
			}
		});
		return same;
	}
	
	// detect if this device can trigger touch events
	var deviceHasTouchCapability = !!('ontouchstart' in window);
	
	// we'll assume the device has no mouse until we detect any mouse movement
	var deviceHasMouse = false;
	$('body').one('mousemove', function() {
		deviceHasMouse = true;
	});
	
	function deviceIsPureTouch() {
		return (!deviceHasMouse && deviceHasTouchCapability);
	}
	
	// detecting support for CSS transitions
	function supportsTransitions() {
		var b = document.body || document.documentElement,
			s = b.style,
			p = 'transition';
		
		if(typeof s[p] == 'string') {return true; }

		v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'],
		p = p.charAt(0).toUpperCase() + p.substr(1);
		for(var i=0; i<v.length; i++) {
			if(typeof s[v[i] + p] == 'string') { return true; }
		}
		return false;
	}
})( jQuery, window, document );
;
/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

(function($) {
    // Setup editable widgets
    $('div.editable, span.editable, h1.editable')
        .find('.viewer')
        .append('<a class="edit_btn btn"><b class="fa fa-edit"></b></a>')
        .end()
        .click(function(e){
            var editable = $(this).closest('.editable');
            var editor = editable.find('.editor');
            var viewer = editable.find('.viewer');
            if(editor.hasClass('overlap')){
                editor.width(viewer.width());
            }
            editable.addClass('editing')
                    .removeClass('viewing');
            // autoresize textareas will be the wrong size the first time due to being hidden, so nudge them
            editor.find('textarea').change();
            e.stopPropagation();
        })
        .find('a').click(function(event){
            if(!$(this).hasClass('edit_btn')){
                event.stopPropagation();
            }
        })
        .end()
        .end()
        .find('.editor')
        .find('input, select, textarea').each(function(i){
            var $this = $(this);
            var editor = $this.closest('.editor');
            if ($this.attr('type') === 'checkbox') {
                $this.attr('original_val', this.checked);
            } else {
                $this.attr('original_val', this.value);
            }
            if(!$('a.cancel_btn', editor).length){
                var save_btns = $('<div class="save_holder"><input type="submit" value="Save"/><a href="#" class="cancel_btn">Cancel</a></div>');
                if(editor.hasClass('multiline')){
                    var save_holder = editor.find('.save_holder');
                    if(save_holder.length){
                        save_holder.append(save_btns);
                    }
                    else{
                        editor.append(save_btns);
                    }
                }
                else{
                    editor.append($('<table class="holder_table"><tr/></table>')
                                .append($('<td/>').append($this))
                                .append($('<td class="save_controls"/>').append($(save_btns)))
                    );
                }
            }
        })
        .end()
        .find('.cancel_btn').click(function(e){
            var $editable = $(this).closest('.editable');
            $editable.addClass('viewing').removeClass('editing');
            $editable.find('input:text, select, textarea').each(function(){
                $(this).val($(this).attr('original_val'));
            });
            $editable.find('input[type=checkbox]').each(function(){
                this.checked = ($(this).attr('original_val') === 'true');
            });
            return false;
        });
})(jQuery);

$(function(){
    $('.defaultText').
        focus(function(){
            var $this = $(this);
            if ( $this.val() == $this[0].title ){
                $this.removeClass('defaultTextActive').val('');
            }
        }).
        blur(function(){
            var $this = $(this);
            if ( !$this.val() ){
                $this.addClass('defaultTextActive').val($this[0].title);
            }
        }).
        blur();
    $('.selectText').focus(function(){
        var field = $(this);
        // running select() directly doesn't work for Chrome
        // http://stackoverflow.com/questions/3150275/jquery-input-select-all-on-focus/3150369#3150369
        window.setTimeout(function() {
            field.select();
        }, 10);
    });
});

function auto_close( o, timeout ){
    var $o = $(o);
    setTimeout(function(){
        $o.fadeOut('slow');
    }, timeout);
    return $o;
}

function flash( html, kind, timeout ){
    var status = kind || 'info';
    var title = 'Notice:';
    if(status == 'error'){
        title = 'Error:';
    }
    $('#messages').notify(html, {
        title: title,
        status: status
    });
}

function attach_form_retry( form ){
    $(form).submit(function(){
        $form = $(this);
        $messages = $('#messages')

        $messages.notify('Saving...', {
            title: 'Form save in progress',
            status: 'info'
        });
        setTimeout(function(){
            // After 7 seconds, express our concern.
            $messages.notify('The server is taking too long to respond.<br/>Retrying in 30 seconds.', {
                title: 'Form save in progress',
                status: 'error'
            });
            setTimeout(function(){
                // After 30 seconds total, give up and try again.
                $messages.notify('Retrying...', {
                    title: 'Form save in progress',
                    status: 'warning'
                });
                $form.submit();
            }, 23000)
        }, 7000);
    });
}

function addCommas(num) {
    // http://stackoverflow.com/questions/1990512/add-comma-to-numbers-every-three-digits-using-jquery/1990590#1990590
    return String(num).replace(new RegExp('(\\d)(?=(\\d\\d\\d)+(?!\\d))', 'g'), "$1,");
}

function get_cm($elem) {
    return $('.CodeMirror', $elem)[0].CodeMirror;
}

function escape_html(str) {
    return $('<i></i>').text(str).html();
}

$(function(){
    $('html').removeClass('no-js').addClass('js');

    // Add notifications for form submission.
    attach_form_retry('form.can-retry');

    $('#messages').notifier();
    // Process Flash messages
    $('#flash > div').
        each(function(){
            var status = this.className || 'info';
            var title = 'Notice:';
            if(status == 'error'){
                title = 'Error:';
            }
            $('#messages').notify(this.innerHTML, {
                title: title,
                status: status
            });
        });

    // Make life a little better for Chrome users by setting tab-order on inputs.
    // This won't stop Chrome from tabbing over links, but should stop links from
    // coming "in between" fields.
    var i = 0;
    $('input,textarea,select,button').each(function(){
        $(this).attr('tabindex', ++i);
    });

    // Provide prompt text for otherwise empty viewers
    var ws = /^\s*$/;
    $('[data-prompt]').each(function(){
        var $this = $(this);
        if ( ws.test($this.text()) ) {
            $this.css('color', 'gray').text($this.attr('data-prompt'))
        }
    });

    $('#site-notification .btn-close').click(function(e) {
        var $note = $(this).parents('section:first');
        $note.hide();
        var note_id = $note.attr('data-notification-id');
        var cookie = $.cookie('site-notification');
        // change e.g. "5dc2f69f07ae3175c7c21972-5-False" to "5dc2f69f07ae3175c7c21972-5-True" to mark as closed
        // cookie may have multiple id-num-bool sets in it
        cookie = cookie.replace(new RegExp(note_id + '-([0-9]+)-False'), note_id + '-$1-True');
        $.cookie('site-notification', cookie, {
            expires: 365,
            path: '/',
            secure: top.location.protocol==='https:' ? true : false
        });
        e.preventDefault();
        return false;
    });

    $('.lightbox').click(function(e) {
        var image_source = $(this).data("src") || $(this).attr('href');
        if ($('#lightbox').length === 0) {
            $('body').append('<div id="lightbox" style="display:none; height: 90%"><img style="display: block; max-height: 100%; max-width: 100%; margin-left: auto; margin-right: auto;"></div>');
        }
        var image = $('#lightbox').find('img:first');
        image.attr("src", image_source);

        $('#lightbox').lightbox_me({
            centered: true
        });

        e.preventDefault();
    });
    // backwards compatibility for old anchors.  If there's an intended target, but not an active one, try again with TOC prefix
    if (window.location.hash && !document.querySelector(':target')) {
        var new_hash = window.location.hash.replace('#', '#h-');
        try {
            if (document.querySelector(new_hash)) {
                window.location.hash = new_hash;
            } else {
                new_hash = window.location.hash.replace('#', '#user-content-');
                if (document.querySelector(new_hash)) {
                    window.location.hash = new_hash;
                }
            }
        } catch (e) {
            // e.g. invalid selector syntax
        }
    }
});

// Interactive checkboxes
$(function(){
    $('.active-md').each(function() {
        var $active_md = $(this);
        new Checklists($active_md, function(checkbox, callback) {
            var uri = $active_md.data('markdownlink');
            $.get(uri + 'get_markdown', callback);
        }, function(markdown, checkbox, callback) {
            var uri = $active_md.data('markdownlink');
            $.ajax({
                type: 'post',
                url: uri + 'update_markdown',
                data: {
                    'text' : markdown,
                    '_csrf_token' : $.cookie('_csrf_token')
                },
                success: callback
            });
        });
    });
});

// User card for mentions

var umProfileStore = {}; // caching profile data

var displayUserCard = function(instance, data) {
    $(instance).tooltipster('content', data);
}

$(function(){
    $(".user-mention").tooltipster({
        animation: 'fade',
        delay: 200,
        theme: 'tooltipster-default',
        trigger: 'hover',
        position: 'top',
        iconCloning: false,
        maxWidth: 400,
        contentAsHTML: true,
        interactive: true,
        content: 'Loading...',
        functionReady: function (instance, helper) {
            var userUrl = $(this).attr('href');
            if($(this).data('user-url')){
                userUrl = $(this).data('user-url');
            }
            
            if(umProfileStore.hasOwnProperty(userUrl)){
                displayUserCard(instance, umProfileStore[userUrl]);
                // load from cache
            }
            else {
                $.get(userUrl + 'user_card', function(data) {
                    displayUserCard(instance, data);
                    umProfileStore[userUrl] = data;
                });
            }
        }
    });
});
;
/*jslint white: true, vars: true */
/*global Checklists, jQuery */

var Checklists = (function($) {

    "use strict";
    
    // makes Markdown checklists interactive
    // `container` is either a DOM element, jQuery collection or selector containing
    // the Markdown content
    // `retriever` is a function being passed the respective checkbox and a
    // callback - the latter is epxected to be called with the container's raw
    // Markdown source
    // `storer` is a function being passed the updated Markdown content, the
    // respective checkbox and a callback
    // both functions' are invoked with the respective `Checklists` instance as
    // execution context (i.e. `this`)
    function Checklists(container, retriever, storer) {
        this.container = container.jquery ? container : $(container);
        this.retriever = retriever;
        this.storer = storer;
    
        var checklists = $(".checklist", container);
        checklists.find(this.checkboxSelector).prop("disabled", false);
        var self = this;
        checklists.on("change", this.checkboxSelector, function() {
            var args = Array.prototype.slice.call(arguments);
            args.push(self);
            self.onChange.apply(this, args);
        });
    }
    Checklists.prototype.checkboxSelector = "> li > input:checkbox";
    Checklists.prototype.onChange = function(ev, self) {
        var checkbox = $(this).prop("disabled", true);
        var index = $("ul" + self.checkboxSelector, self.container).index(this);
        var reactivate = function() { checkbox.prop("disabled", false); };
        self.retriever(checkbox, function(markdown) {
            markdown = self.toggleCheckbox(index, markdown);
            self.storer(markdown, checkbox, reactivate);
        });
    };
    Checklists.prototype.toggleCheckbox = function(index, markdown) {
        var pattern = /^([*-]) \[([ Xx])\]/mg; // XXX: duplicates server-side logic!?
        var count = 0;
        return markdown.replace(pattern, function(match, prefix, marker) {
            if(count === index) {
                marker = marker === " " ? "x" : " ";
            }
            count++;
            return prefix + " [" + marker + "]";
        });
    };
    
    return Checklists;
    
    }(jQuery));;
/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

// This logic is the same as the inline JS from the Lightbox widget
function startLightbox($lightbox) {
    $lightbox.lightbox_me();
    $lightbox.on('click', '.close', function (e) {
        e.preventDefault();
        $lightbox.trigger('close');
    });
    return $lightbox;
}

$(function() {
    $('body').on('click', 'a.admin_modal', function(e) {
        e.preventDefault();

        $('#lightbox_admin_modal').remove();
        $('body').append('<div id="lightbox_admin_modal" class="modal" style="display:none">  \
            <a class="icon close" href="#" title="Close"><i class="fa fa-close"></i></a>  \
            <h1 id="admin_modal_title"></h1><div id="admin_modal_contents">Loading...</div>  \
        </div>');

        startLightbox($('#lightbox_admin_modal'));

        var link = this;
        $.get(link.href, function(data) {
            var $popup_title = $('#admin_modal_title');
            var $popup_contents = $('#admin_modal_contents');
            $popup_title.html($(link).html());
            $popup_contents.html(data);
            var csrf_exists = $popup_contents.find('form > input[name="_csrf_token"]').length;
            if (!csrf_exists) {
                var cval = $.cookie('_csrf_token');
                var csrf_input = $('<input name="_csrf_token" type="hidden" value="'+cval+'">');
                $popup_contents.find('form').append(csrf_input);
            }
        });
    });
});
;
/*
* $ lightbox_me
* By: Buck Wilson
* Version : 2.4
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


(function($) {

    $.fn.lightbox_me = function(options) {

        return this.each(function() {

            var
                opts = $.extend({}, $.fn.lightbox_me.defaults, options),
                $overlay = $(),
                $self = $(this),
                $iframe = $('<iframe id="foo" style="z-index: ' + (opts.zIndex + 1) + ';border: none; margin: 0; padding: 0; position: absolute; width: 100%; height: 100%; top: 0; left: 0; filter: mask();"/>');

            if (opts.showOverlay) {
                //check if there's an existing overlay, if so, make subequent ones clear
               var $currentOverlays = $(".js_lb_overlay:visible");
                if ($currentOverlays.length > 0){
                    $overlay = $('<div class="lb_overlay_clear js_lb_overlay"/>');
                } else {
                    $overlay = $('<div class="' + opts.classPrefix + '_overlay js_lb_overlay"/>');
                }
            }

            /*----------------------------------------------------
               DOM Building
            ---------------------------------------------------- */
            $('body').append($self.hide()).append($overlay);


            /*----------------------------------------------------
               Overlay CSS stuffs
            ---------------------------------------------------- */

            // set css of the overlay
            if (opts.showOverlay) {
                setOverlayHeight(); // pulled this into a function because it is called on window resize.
                $overlay.css({ position: 'absolute', width: '100%', top: 0, left: 0, right: 0, bottom: 0, zIndex: (opts.zIndex + 2), display: 'none' });
				if (!$overlay.hasClass('lb_overlay_clear')){
                	$overlay.css(opts.overlayCSS);
                }
            }

            /*----------------------------------------------------
               Animate it in.
            ---------------------------------------------------- */
               //
            if (opts.showOverlay) {
                $overlay.fadeIn(opts.overlaySpeed, function() {
                    setSelfPosition();
                    $self[opts.appearEffect](opts.lightboxSpeed, function() { setOverlayHeight(); setSelfPosition(); opts.onLoad()});
                });
            } else {
                setSelfPosition();
                $self[opts.appearEffect](opts.lightboxSpeed, function() { opts.onLoad()});
            }

            /*----------------------------------------------------
               Hide parent if parent specified (parentLightbox should be jquery reference to any parent lightbox)
            ---------------------------------------------------- */
            if (opts.parentLightbox) {
                opts.parentLightbox.fadeOut(200);
            }


            /*----------------------------------------------------
               Bind Events
            ---------------------------------------------------- */

            $(window).resize(setOverlayHeight)
                     .resize(setSelfPosition)
                     .scroll(setSelfPosition);

            $(window).bind('keyup.lightbox_me', observeKeyPress);

            if (opts.closeClick) {
                $overlay.click(function(e) { closeLightbox(); e.preventDefault; });
            }
            $self.delegate(opts.closeSelector, "click", function(e) {
                closeLightbox(); e.preventDefault();
            });
            $self.bind('close', closeLightbox);
            $self.bind('reposition', setSelfPosition);



            /*--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
              -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */


            /*----------------------------------------------------
               Private Functions
            ---------------------------------------------------- */

            /* Remove or hide all elements */
            function closeLightbox() {
                var s = $self[0].style;
                if (opts.destroyOnClose) {
                    $self.add($overlay).remove();
                } else {
                    $self.add($overlay).hide();
                }

                //show the hidden parent lightbox
                if (opts.parentLightbox) {
                    opts.parentLightbox.fadeIn(200);
                }
                if (opts.preventScroll) {
                    $('body').css('overflow', '');
                }
                $iframe.remove();

				        // clean up events.
                $self.undelegate(opts.closeSelector, "click");
                $self.unbind('close', closeLightbox);
                $self.unbind('repositon', setSelfPosition);

                $(window).unbind('resize', setOverlayHeight);
                $(window).unbind('resize', setSelfPosition);
                $(window).unbind('scroll', setSelfPosition);
                $(window).unbind('keyup.lightbox_me');
                opts.onClose();
            }


            /* Function to bind to the window to observe the escape/enter key press */
            function observeKeyPress(e) {
                if((e.keyCode == 27 || (e.DOM_VK_ESCAPE == 27 && e.which==0)) && opts.closeEsc) closeLightbox();
            }


            /* Set the height of the overlay
                    : if the document height is taller than the window, then set the overlay height to the document height.
                    : otherwise, just set overlay height: 100%
            */
            function setOverlayHeight() {
                if ($(window).height() < $(document).height()) {
                    $overlay.css({height: $(document).height() + 'px'});
                     $iframe.css({height: $(document).height() + 'px'});
                } else {
                    $overlay.css({height: '100%'});
                }
            }


            /* Set the position of the modal'd window ($self)
                    : if $self is taller than the window, then make it absolutely positioned
                    : otherwise fixed
            */
            function setSelfPosition() {
                var s = $self[0].style;

                // reset CSS so width is re-calculated for margin-left CSS
                $self.css({left: '50%', marginLeft: ($self.outerWidth() / 2) * -1,  zIndex: (opts.zIndex + 3) });


                /* we have to get a little fancy when dealing with height, because lightbox_me
                    is just so fancy.
                 */

                // if the height of $self is bigger than the window and self isn't already position absolute
                if (($self.height() + 80  >= $(window).height()) && ($self.css('position') != 'absolute')) {

                    // we are going to make it positioned where the user can see it, but they can still scroll
                    // so the top offset is based on the user's scroll position.
                    var topOffset = $(document).scrollTop() + 40;
                    $self.css({position: 'absolute', top: topOffset + 'px', marginTop: 0})
                } else if ($self.height()+ 80  < $(window).height()) {
                    //if the height is less than the window height, then we're gonna make this thing position: fixed.
                    if (opts.centered) {
                        $self.css({ position: 'fixed', top: '50%', marginTop: ($self.outerHeight() / 2) * -1})
                    } else {
                        $self.css({ position: 'fixed'}).css(opts.modalCSS);
                    }
                    if (opts.preventScroll) {
                        $('body').css('overflow', 'hidden');
                    }
                }
            }

        });



    };

    $.fn.lightbox_me.defaults = {

        // animation
        appearEffect: "fadeIn",
        appearEase: "",
        overlaySpeed: 250,
        lightboxSpeed: 300,

        // close
        closeSelector: ".close",
        closeClick: true,
        closeEsc: true,

        // behavior
        destroyOnClose: false,
        showOverlay: true,
        parentLightbox: false,
        preventScroll: false,

        // callbacks
        onLoad: function() {},
        onClose: function() {},

        // style
        classPrefix: 'lb',
        zIndex: 999,
        centered: false,
        modalCSS: {top: '40px'},
        overlayCSS: {background: 'black', opacity: .3}
    }
})(jQuery);
;
/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

/*global $, console, jQuery, localStorage */
window.Memorable = {};

/**
 * Class that describes the management of a memorable input - identifying, watching, saving, and restoring
 */
Memorable.InputManager = (function(){

    var defaults = {
        // regex to determine if an input's name can't reliably identify it, as many inputs have randomized
        // names for antispam purposes.
        invalidInputName: /([A-Za-z0-9\-_]{28})/,
        // selectors of buttons that represent a user cancellation, and will clear remembered inputs in the form
        cancelSelectors: '.cancel_edit_post, .cancel_form, input[value=Cancel]'
    };

    /**
     * @param inputObj - the InputBasic or InputMDE object representing the input to be tracked
     * @constructor
     */
    function InputManager(inputObj, options){
        this.options = $.extend({}, defaults, options);
        this.inputObj = inputObj;
        this.$form = this.inputObj.getForm();

        //watch the Input object for change
        this.inputObj.watchObj.on(this.inputObj.watchEvent, this.handleSave.bind(this));

        //watch "cancel"-style links, to forget immediately
        $(this.options.cancelSelectors, this.$form).on('click', this.handleCancel.bind(this));

        //watch for hidden inputs that might be revealed
        this.$form.on('replyRevealed', this.inputObj.refresh.bind(this.inputObj));

        //restore from localStorage
        this.restore();
    }

    /**
     * Builds a unique key to use when persisting the input's value
     * @returns {string}
     */
    InputManager.prototype.getStorageKey = function(){
        var self = this;
        function isUsableName($el){
            var name = $el.attr('name');
            if (name && !name.match(self.options.invalidInputName)){
                return true;
            }
        }
        function getRelativeAction($f){
            var action = $f[0].action;
            var list = action.split('/');
            var relativeAction = "/" + list.slice(3).join('/');
            return relativeAction;
        }

        var key = '';
        var $f = this.$form;
        var keySeparator = '__';
        if ($f.attr('action')){
            var relativeAction = getRelativeAction($f);
            key += relativeAction;
        }
        if (isUsableName(this.inputObj.$el)) {
            key += keySeparator + this.inputObj.$el.attr('name');
        } else if (this.inputObj.$el.attr('class')) {
            // id can't be relied upon, because of EW.  We can key off class, if it's the only one in the form.
            var klass = this.inputObj.$el.attr('class');
            if ($('.' + klass, $f).length == 1) {
                key += keySeparator + klass;
            } else {
                throw "Element isn't memorable, it has no unique class";
            }
        } else {
            throw "Element isn't memorable, it has no identifiable traits";
        }
        return key;
    };

    /**
     * Gets the value of the tracked input field
     */
    InputManager.prototype.getValue = function(){
        return this.inputObj.getValue();
    };

    /**
     * Saves the input's value to local storage, and registers it as part of the form for later removal
     */
    InputManager.prototype.save = function(){
        localStorage[this.getStorageKey()] = this.getValue();
    };

    /**
     * Event handler for invoking the save
     * @param e
     * @returns {boolean}
     */
    InputManager.prototype.handleSave = function(e){
        if (e.preventDefault){
            e.preventDefault();
        }
        this.save();
        return false;
    };

    /**
     * Event handler for clicking "cancel"
     * @param e
     * @returns {boolean}
     */
    InputManager.prototype.handleCancel = function(e){
        Memorable.forget(this.getStorageKey());
        return true;
    };
    /**
     * Fetches the tracked input's persisted value from storage
     * @returns {string}
     */
    InputManager.prototype.storedValue = function(){
        return localStorage[this.getStorageKey()];
    };

    /**
     * Fetches the input's remembered value and restores it to the target field
     */
    InputManager.prototype.restore = function(){
        if (!this.storedValue()){
            return;
        }
        this.inputObj.setValue(this.storedValue());
    };

    return InputManager;
})();


/**
 * Class describing a simple input field, as identified by a selector or DOM element, with specific methods for
 * getting & setting the value, and finding it's parent form
 *
 * @property obj: the raw object representing the field to be tracked; a standard jquery object
 * @property watchEvent: the name of the event to watch to detect when changes have been made
 * @property watchObj: the object instance to watch for events on. same as this.obj
 * @property $el: the jquery object representing the actual input field on the page. same as this.obj
 */
Memorable.InputBasic = (function() {
    /**
     * @param obj: a selector or DOM Element identifying the basic input field to be remembered
     * @constructor
     */
    function InputBasic(obj) {
        this.obj = $(obj);
        this.watchEvent = 'change';
        this.watchObj = this.obj;
        this.$el = this.obj;
    }
    InputBasic.prototype.getValue = function () {
        return this.obj.val();
    };
    InputBasic.prototype.setValue = function (val) {
        this.$el.val(val);
    };
    InputBasic.prototype.getForm = function () {
        return this.$el.parents('form').eq(0);
    };
    InputBasic.prototype.refresh = function(){
        return null;  // noop
    };
    return InputBasic;
})();


/**
 * Class describing a field backed by EasyMDE, as identified by the passed instance of `EasyMDE` provided, with specific methods for
 * getting & setting the value, and finding it's parent form
 *
 * @property obj: the EasyMDE object describing the field to be tracked
 * @property watchEvent: the name of the event to watch to detect when changes have been made
 * @property watchObj: the object instance to watch for events on; editor.codemirror per their docs
 * @property $el: the jquery object representing the actual input field on the page
 */
Memorable.InputMDE = (function() {
    /**
     * @param obj: A EasyMDE object representing the input field
     * @constructor
     */
    function InputMDE(obj) {
        this.obj = obj;
        this.watchEvent = 'change';
        this.watchObj = this.obj.codemirror;
        this.$el= $(this.obj.element);
    }
    InputMDE.prototype.getValue = function () {
        return this.obj.value();
    };
    InputMDE.prototype.setValue = function (val) {
        this.obj.value(val);
    };
    InputMDE.prototype.getForm = function () {
        return this.$el.parents('form').eq(0);
    };
    InputMDE.prototype.refresh = function(){
        this.watchObj.refresh();
    };
    return InputMDE;
})();


/**
 * Takes an arbitrary object, and determines the best Input class to represent it
 */
Memorable.inputFactory = function(obj) {
    if (obj.codemirror){
        return Memorable.InputMDE;
    } else {
        return Memorable.InputBasic;
    }
};


/**
 * Convenience method to find any classes decorated with `.memorable` and create a related Input object for it
 * @param selector - use to override the selector used to find all fields to be remembered
 */
Memorable.initialize = function(selector){
    var s = selector || '.memorable';
    $(s).each(function(){
        Memorable.add(this);
    });
};


/**
 * Forgets any successfully processed inputs from user
 */
Memorable.forget = function(key_prefix){
    key_prefix = key_prefix || $.cookie('memorable_forget');
    if (key_prefix) {
        for (var i = localStorage.length -1; i >=0; i--) {
            if(localStorage.key(i).indexOf(key_prefix) == 0){
                localStorage.removeItem(localStorage.key(i));
            }
        }
        $.removeCookie('memorable_forget', { path: '/', secure: top.location.protocol==='https:' ? true : false });
    }
};



/**
 * Creates a new Input object to remember changes to an individual field
 * @param obj - the raw object representing the field to be tracked
 */
Memorable.add = function(obj){
    var cls = Memorable.inputFactory(obj);
    Memorable.items.push(new Memorable.InputManager(new cls(obj)));
};


// Initialize.  Some items must be immediately, not wait until domready, because other Memorable.add usage could happen before our dom-ready initialize fires
Memorable.items = [];
Memorable.forget();
$(function(){Memorable.initialize();});
;
/*global SF, jQuery, $, Dropzone, Dragster, bizxPrebid, grecaptcha, isPassiveEventListenerSupported, CSV, bizx */
if (!window.SF) {
    window.SF = {};
}
SF.Widgets = SF.Widgets || {};


SF.SDChromePopover = function($popover) {
    /* This is only for sandiego_chrome pages, and can be removed when those are gone
        Full-sandiego pages use Foundation for the dropdown behavior
    */

    // Mimic the dropdown menu behaviors from FDN.
    $popover.addClass('is-dropdown-submenu-parent opens-right');
    var trigger = $popover.find('a').first();
    var submenu = trigger.siblings('ul').first();
    submenu.addClass('submenu is-dropdown-submenu first-sub vertical');
    submenu.parent().addClass('is-dropdown-submenu-parent opens-right');
    trigger.on("mouseenter", function() {
        $popover.addClass('is-active');
        submenu.addClass('js-dropdown-active');
    });
    trigger.on("mouseleave",function() {
        trigger.parent().on("mouseleave", function() {
            $popover.removeClass('is-active');
            submenu.removeClass('js-dropdown-active');
        });
    });
};

jQuery(function($) {
    // Setup the updater popover
    var $updater = $('#updater-tooltip-sd').length ? $('#updater-tooltip-sd') : $('#updater-tooltip');
    if ($updater.length) {
        if ($updater.hasClass('fetch')) {
            $.ajax({
                url: '/user/updates/find' + location.search,
                global: false,
                success: function(data) {
                    if (data.length) {
                        $updater.hide()
                                .html(data)
                                .show();
                        if (SF.sandiego_chrome) {
                            SF.SDChromePopover($updater);
                        }
                    }
                }
            });
        }
        else if (SF.sandiego_chrome) {
            SF.SDChromePopover($updater);
        }
    }
    // Setup the account popover
    var $account_tip = $('#account-tooltip');
    if ($account_tip.length) {
        if (SF.sandiego_chrome) {
            SF.SDChromePopover($account_tip);
        }
    }

    $(window).on('load', function(){
        SF.floatingNewsletter = new SF.FloatingNewsletterSubscribe();
    });


    //wire up newsletter subscribe widgets ("NSW")
    $('.newsletter-subscribe-form').each(SF.wire_up_subscribe_form);

    SF.blockThis = new SF.BlockThis({positionSticky: true});

    SF.myProjects = new SF.MyProjects();

});


SF.FloatingNewsletterSubscribe = (function($){
    var _defaults = {
        element:'#newsletter-floating',
        delay:5,
        cookieName: 'suppressNewsletter',
        basementEl: 'footer .l-nav-bottom',
        transition: 'bottom 1s'
    };

    function FloatingNewsletterSubscribe(options) {
        var _self = this;
        this.settings = $.extend(this.settings, _defaults, options);
        setTimeout(this.init.bind(this), this.settings.delay * 1000);  // doing the delay right away also gives time for Allura ajax to run
    }

    FloatingNewsletterSubscribe.prototype.init = function(){
        //init values
        this.$el = $(this.settings.element);
        if (!this.$el.length) {
            return;
        }
        this.height = this.$el.outerHeight();
        this.$el.css('bottom', this.height*(-1));
        this.suppressCookie = $.cookie(this.settings.cookieName);
        this.isHidden = true;

        this.$basementEl = $(this.settings.basementEl);
        this.basementHeight = this.$basementEl.height();    //this doesn't change via MQ's, so can grab it once
        this.boundScrollDelegate = this.scrollRelocate.bind(this);

        if (this.$el && !this.suppressCookie) {
            // isPassiveEventListenerSupported available via sticky.js
            window.addEventListener('scroll', this.boundScrollDelegate, isPassiveEventListenerSupported() ? {passive: true} : false);

            this.show();

            //wire close click
            $('.btn-closer', this.$el).on("click", this.hide.bind(this));
        }
    };

    FloatingNewsletterSubscribe.prototype.scrollRelocate = function() {
        if(!this.isHidden) {
            this.$el.css('transition', 'none');
            this.$el.css('bottom', this.calcBottom());
        }

    };

    FloatingNewsletterSubscribe.prototype.calcBottom = function() {
      var windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;

        var windowScrollTop = $(window).scrollTop();
        var scrollBottomLocation = windowHeight + windowScrollTop;
        var basement = this.$basementEl.offset().top;

        if (scrollBottomLocation < basement) {
            return 0;
        } else {
            return scrollBottomLocation - basement;
        }
    };


    FloatingNewsletterSubscribe.prototype.show = function(){
        this.$el.css('transition', this.settings.transition);
        this.$el.css('bottom', this.calcBottom());
        this.isHidden = false;
    };

    FloatingNewsletterSubscribe.prototype.hide = function(){
        this.$el.css('transition', this.settings.transition);
        this.$el.css('bottom', this.height*(-1));
        this.suppress();
        this.isHidden = true;
    };

    FloatingNewsletterSubscribe.prototype.suppress = function(){
        $.cookie(this.settings.cookieName, true,  { expires: 3, path: '/', secure: true });
        return true;
    };

    return FloatingNewsletterSubscribe;
})(jQuery);


//------------------------------------
//Widget for BlockThis
//------------------------------------

function getIndicesOf(searchStr, str, caseSensitive) {
    var startIndex = 0, searchStrLen = searchStr.length;
    var index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + searchStrLen;
    }
    return indices;
}

SF.BlockThis = (function($){
    var _defaults = {
        element:'#overlay-blockthis-wrapper',
        btnActivateSelector:'.btn-blockthis',
        btnCloseSelector:'#btn-blockthis-close',
        inputGptInfoSelector:'#gpt-info',
        positionSticky: false
    };

    function BlockThis(options){
        var _self = this;
        this.settings = $.extend(this.settings, _defaults, options);

        function handleActivate(e){
            var $t = $(e.target),
                $p = $t.parents('.draper'),
                ad_unit = $p.attr('id').replace('_wrapped',''),
                ad_id = $p.attr('data-id');
            _self.$element.show();
            _self.dropzone = enableDropzone();
            if (! _self.settings.positionSticky) {
                repositionOverlay();
                $(window).resize(repositionOverlay);
            }
            _self.capture(ad_unit, ad_id);
            return false;
        }
        function handleSubmit(e){
            return _self.submit();
        }
        function handleClose(e){
            _self.close();
            return false;
        }
        function enableDropzone(){
            if (_self.dropzone) {
                _self.dropzone.enable();
                return _self.dropzone;
            }
             var myDropzone = new Dropzone('#blockthisForm', {
                paramName: 'screenshot', // this is not antispam encoded, but it is still let through ok since the name is correct
                autoProcessQueue: false,
                maxFiles: 1,
                maxFilesize: 2, // MB
                clickable: '#upload-it',
                thumbnailWidth: null,
                thumbnailHeight: 35,
                acceptedFiles: 'image/*,.png,.jpg,.jpeg,.gif',
                addRemoveLinks: true,
                renameFilename: function (name) {
                    var parts = name.split('.'),
                        ext = parts[parts.length - 1];
                    return 'screenshot.' + ext;
                },
                previewsContainer: $('.dropzone-previews')[0],
                previewTemplate: document.getElementById('dropzone-preview-template').innerHTML,
                dictMaxFilesExceeded: 'You may only upload 1 screenshot.',
                dictFallbackText: 'Screenshot (required):',
                init: function () {
                    this.on('success', function () {
                        $('#messages').notify({message: 'Report submitted successfully.  Thanks!', status: 'success'});
                        $('#btn-blockthis-close').trigger('click');
                    });
                    this.on('error', function (file, errorMessage, xhr) {
                        // this can receive XHR submission errors, or internal errors (like too many files)
                        var message = errorMessage.error || errorMessage;
                        $('#messages').notify({message: message, status: 'error'});
                        this.removeAllFiles(true);
                        // re-enable button in case of submission error, so they can try again
                        $('#btn-blockthis-submit').attr('disabled', false).attr('value', 'Submit Report');
                    });
                    this.on("addedfile", function (file) {
                        $('#upload-it').hide();
                        $('.dropzone-previews').show();
                        // dragster:leave doesn't fire on its own, when ending, so we must fire it
                        // otherwise if you remove the file and add another it'll be in the wrong state
                        _self.$form.trigger('dragster:leave');
                    });
                    this.on("removedfile", function (file) {
                        $('#upload-it').show();
                        $('.dropzone-previews').hide();
                    });
                },
            });
            // https://github.com/enyo/dropzone/issues/438
            var dragster = new Dragster(_self.$form[0]);
            _self.$form.on('dragster:enter', function () {
                _self.$form.addClass('dragging-active');
            });
            _self.$form.on('dragster:leave', function () {
                _self.$form.removeClass('dragging-active');
            });
            return myDropzone;
        }

        function repositionOverlay(e){
            var footerHeight = _self.$element.outerHeight();
            var footerTop = ($(window).height()-footerHeight)+"px";
            _self.$element.css({
                top: footerTop
            });
        }

        (function init() {
            this.$element = $(this.settings.element);
            if (!this.$element.length){
                // widget isn't on page, bail.
                return false;
            }


            this.$btnClose = $(this.settings.btnCloseSelector);
            this.$gptInfo = $(this.settings.inputGptInfoSelector);
            this.$form = $('form', this.$element);

            //wire events
            $('body').on('click', this.settings.btnActivateSelector, handleActivate);
            this.$form.on("submit", handleSubmit);
            this.$btnClose.on("click", handleClose);
        }).apply(this);
    }

    BlockThis.prototype.getSanitizeAdInfo = function(ad_unit, ad_id) {
        var ad = null,
            ad_info = {};
        for (var x=0; x < SF.Ads.renderedAds.length; x++) {
            ad = SF.Ads.renderedAds[x];
            if (ad.slot.getAdUnitPath().indexOf(ad_unit) !== -1) {
                break;
            }
        }
        if (!ad) {
            return null;
        }

        ad_info.contentUrl = ad.slot.getContentUrl();
        ad_info.position = ad_unit;
        ad_info.size = ad.size;
        ad_info.targeting = ad.slot.getTargetingMap();
        // these are undocumented methods so might not work forever
        try {
            ad_info.clickUrl = ad.slot.getClickUrl();
        } catch (e) {}
        try {
            ad_info.html = ad.slot.getHtml();
        } catch (e) {}
        ad_info.response_info = ad.slot.getResponseInformation();
        for (var key in SF.Ads.Advertisers) {
            if (SF.Ads.Advertisers[key] === ad_info.response_info.advertiserId) {
                ad_info.ad_network = key;
                break;
            }
        }
        var prebid_winner = window.bizxPrebid && bizxPrebid.Ads.prebidWinners && bizxPrebid.Ads.prebidWinners[ad_id];
        if (prebid_winner) {
            ad_info.ad_network = prebid_winner.bidder;
            if (prebid_winner.ad) {
                ad_info.html = prebid_winner.ad;
            }
            ad_info.prebid = bizxPrebid.pbjs.getBidResponsesForAdUnitCode(ad_id);
        }
        if (window.console && window.console.log) {
            window.console.log('Ad info is:', ad_info);
        }
        return ad_info;
    };

    // --------------------------------------------------------------------
    // stores serialized json of captured ad info
    // --------------------------------------------------------------------
    BlockThis.prototype.persistCapturedInfo = function() {
        this.$gptInfo.val(JSON.stringify(this.capturedAdInfo));
    };

    // --------------------------------------------------------------------
    // main entry point to capture ad info
    // --------------------------------------------------------------------
    BlockThis.prototype.capture = function(ad_unit, ad_id) {
        if (!SF.Ads.renderedAds) {
            throw "Attempted to capture ad info, but feature is not enabled";
        }
        this.capturedAdInfo = this.getSanitizeAdInfo(ad_unit, ad_id);
        this.persistCapturedInfo();
        return this.capturedAdInfo;
    };

    // --------------------------------------------------------------------
    // pushes user submission to SF API endpoint.
    // --------------------------------------------------------------------
    BlockThis.prototype.submit = function() {
        var form = this.$form[0];
        if (form && form.checkValidity && !form.checkValidity()) {
            // built in validation exists and fails, so let it run
            return true;
        }
        if (this.dropzone.getQueuedFiles && !this.dropzone.getQueuedFiles().length) {
            $('#messages').notify({message: 'You must provide a screenshot file.', status: 'error'});
            return false;
        }
        $('input[type=submit]', this.$form).attr('disabled', true).attr('value', 'Submitting...');
        if (this.dropzone.processQueue) {
            this.dropzone.processQueue();
            return false;
        } else {
            // fallback, no dropzone, do regular submit
            return true;
        }
    };

    // --------------------------------------------------------------------
    // Closes the widget and cleans it up for next time
    // --------------------------------------------------------------------
    BlockThis.prototype.close = function() {
        this.$element.hide();
        this.dropzone.removeAllFiles(true);
        this.dropzone.disable();
        $('#btn-blockthis-submit').attr('disabled', false).attr('value', 'Submit Report');
        // reset all fields except the special ones
        this.$form.find('input').each(function(i, elem) {
            if (elem.name !== "_visit_cookie" &&
                elem.name !== "timestamp" &&
                elem.name !== "spinner" &&
                elem.name !== "" ) {
                $(elem).val('');
            }
        });
        return false;
    };

    return BlockThis;
}(window.jQuery));


SF.MyProjects = (function($) {
    function MyProjects() {
        this.init();
    }

    MyProjects.prototype.init = function() {
        if (!$('#account-tooltip').length) {
            return;
        }
        this.loaded = false;
        this.$logout_li = $('.tooltip-container .account b[title="Log Out"]').parents('li:first');
        this.pending();
        $(window).on('load', this.load.bind(this)); // ok to be pretty late, often isn't even needed
        $('#account-tooltip').on("click", this.load.bind(this));  // make sure we load immediately if they click on us
    };

    MyProjects.prototype.pending = function() {
        this.$logout_li.before('<li class="projects-loading">loading your projects...</li>');
    };

    MyProjects.prototype.load = function() {
        if (this.loaded) {
            return;
        }
        this.loaded = true;
        var user_profile_url = $('div#account-tooltip').length ? $('#account-tooltip > a').attr('href') : $('#account-tooltip > li > a').attr('href');
        var rest_api_url = '/rest' + user_profile_url;
        $.ajax({
            url: rest_api_url,
            context: this,
            global: false,
            success: function(data) {
                $('.projects-loading').remove();
                var my_projects_html = [];
                for (var i = 0; i < data.projects.length; i++) {
                    var proj = data.projects[i];
                    var escaped_proj_name = $('<i></i>').text(proj.name).html();
                    my_projects_html.push('<li><a href="' + proj.url + '">' + escaped_proj_name + '</a></li>');
                }
                this.$logout_li.before(my_projects_html.join(''));
            },
            error: function() {
                this.loaded = false;
            }
        });
    };

    return MyProjects;
})(jQuery);


/*
 Set up reCaptcha bindings.  The automatic setup doesn't work with multiple captcha forms on a page.

 https://developers.google.com/recaptcha/docs/invisible#js_api
 */
SF.captchaSuccessCallbacks = {};
SF.doRecaptcha = function(event, $recap_elem, success_callback) {
    /* DOCS: https://bizxinfo.atlassian.net/wiki/spaces/engr/pages/593166337/Captcha+Configuration */
    if ($recap_elem.length === 0) {
        if (window.console && window.console.log) {
            window.console.log('No recaptcha element found');
        }
        success_callback();
        return;
    }
    var gcaptcha_id = $recap_elem.data('sf-recaptcha-id');
    if (gcaptcha_id === undefined) {
        window.alert('reCAPTCHA did not get loaded.');
    } else {
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();  // this prevents other form.submit handlers from running
        grecaptcha.reset(gcaptcha_id);
        SF.captchaSuccessCallbacks[gcaptcha_id] = success_callback;
        // show the captcha modal (if necessary)
        grecaptcha.execute(gcaptcha_id);
    }
};


// called explicitly by some forms (e.g. when a modal form is triggered)
// for other forms that are on page, this is triggered by form input
function recaptchaLoad() {
    if (!SF.recaptchaInUse) {
        return;
    }
    if (!window.grecaptcha) {
        bizx.cmp.embedScript('https://www.recaptcha.net/recaptcha/api.js?onload=recaptchaConfigure&render=explicit');
    } else {
        recaptchaConfigure();
    }
}

function recaptchaConfigure() {
    /* DOCS: https://bizxinfo.atlassian.net/wiki/spaces/engr/pages/593166337/Captcha+Configuration */
    if (!window.grecaptcha) {
        return;
    }
    $('.g-recaptcha').each(function() {
        var $recap_elem = $(this);
        if (!$recap_elem.parent().is(':visible')) {
            // don't run if the form isn't visible.  Avoids stupid recaptcha alert()s which sometimes happen
            return;
        }
        if ($recap_elem.data('sf-recaptcha-id') !== undefined) {
            // already set up
            return;
        }
        // set up the captcha.  We're invisible so "render" is a bit misleading
        var gcaptcha_id = grecaptcha.render(
            this,
            {
                'callback': function (token) {
                    gcaptcha_id = $recap_elem.data('sf-recaptcha-id');
                    SF.captchaSuccessCallbacks[gcaptcha_id]();
                },
            },
            true /* inherit (use data- attrs) */
        );
        $recap_elem.data('sf-recaptcha-id', gcaptcha_id);

        if ($recap_elem.data('run-automatically') !== undefined) {
            var $form = $recap_elem.parents('form');
            $form.on('submit.checkCaptcha', function(e) {
                SF.doRecaptcha(e, $recap_elem, function() {
                    $form.off('submit.checkCaptcha');
                    $form.submit();
                });
            });
        }
    });
}

$(function() {
    // when a form that has a captcha is interacted with, then load+config the recaptcha
    $('.g-recaptcha').each(function() {
        var $form = $(this).parents('form');
        $form.one('click mouseover', recaptchaLoad);
        $form.find(':input').one('focus', recaptchaLoad);  // handle keyboard navigation too
    });
});


// this snippet from https://github.com/mholt/PapaParse/issues/175#issuecomment-395978144
// could use a more robust library like FileSaver.js but this seems sufficient
// and FileSaver.js has a weird issue: https://github.com/eligrey/FileSaver.js/issues/500
function openSaveFileDialog(data, filename, mimetype) {

  if (!data) {
      return;
  }

  var blob = data.constructor !== Blob ? new Blob([data], {type: mimetype || 'application/octet-stream'}) : data;

  if (navigator.msSaveBlob) {
    navigator.msSaveBlob(blob, filename);
    return;
  }

  var lnk = document.createElement('a'),
      url = window.URL,
      objectURL;

  if (mimetype) {
    lnk.type = mimetype;
  }

  lnk.download = filename || 'untitled';
  lnk.href = objectURL = url.createObjectURL(blob);
  lnk.dispatchEvent(new MouseEvent('click'));
  setTimeout(url.revokeObjectURL.bind(url, objectURL));

}

function saveCSV(data, name) {
    data[0].push('Downloaded ' + (new Date()).toLocaleString() + ' from https://sourceforge.net');
    var csv = CSV.arrayToCsv(data);
    var csv_win = csv.replace(/\n/g, '\r\n');
    openSaveFileDialog(csv_win, name + ".csv", "text/csv");
}
;
/*global SF, _, log, console, $ */

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill
/*jshint ignore:start*/
if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

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

    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fNOP.prototype = this.prototype;
    }
    fBound.prototype = new fNOP();

    return fBound;
  };
}
/*jshint ignore:end*/

// taken from https://github.com/AurelioDeRosa/audero-sticky/blob/master/src/audero-sticky.js
function isPassiveEventListenerSupported() {
    var isSupported = false;
    try {
        var options = Object.defineProperty({}, "passive", {
            get: function() {
                isSupported=true;
            }
        });
        window.addEventListener("", null, options);
    } catch(ex) {
    }
    return isSupported;
}


/* basic sticky features, but using CSS position:sticky instead of doing things manually */
SF.FancyStickify = (function(){
    var defaults = {};

    function FancyStickify($els, options){
        /*
         $el can be multiple elements if there are multiple sticky things on the page.
         But this also does special handling for top leaderboard
         */
        if (! $els || $els.length === 0 || !$('body.sandiego, body.sandiego_chrome').length ) {
            // abandon if there isn't an element to make sticky, or if we're not on full sandiego pages
            return;
        }
        this.o = $.extend({}, defaults, options);
        this.$els = $els;

        this.$header = this.$els.filter('.l-header-nav');
        this.$viewabilityRequirementAd = $('.draper', this.$header);
        this.viewabilityReached = false;
    }

    FancyStickify.prototype.init = function() {
        if (!this.$els) {
            return;
        }

        /* Check for sticky things being stuck or unstuck */
        this.$window = $(window);
        this.sticky_$elems_limits = [];
        var self = this;
        this.$els.each(function () {
            self.recordStickyElem($(this));
        });

        if (this.o.waitForGoneEls) {
            this.waitForGoneEls = $(this.o.waitForGoneEls);
            this.paidSticky = $('.l-header-nav-paid-sticky, .l-header-nav-unpaid-sticky');
            this.paidStickyOn = false;

            if ($('.m-popular-projects').length) {
                this.$unpaidCards = $('.project-masthead .m-popular-projects');
                this.$unpaidCardStuckContainer = $('.l-row-cards');
                this.$unpaidCardsUnstuckContainer = $('.projects-inner');

                this.$unpaidCards.clone().appendTo(this.$unpaidCardStuckContainer);

            }
        }

        var boundHandler = this.checkSticky.bind(this);
        window.addEventListener('load', boundHandler);
        window.addEventListener('scroll', boundHandler, isPassiveEventListenerSupported() ? {passive: true} : false);
        window.addEventListener('resize', boundHandler);
        this.checkSticky();

        this._scrollCount = 0;
        this._scrollWatcherBound = this.scrollWatcherForHeader.bind(this);
        window.addEventListener('scroll', this._scrollWatcherBound, isPassiveEventListenerSupported() ? {passive: true} : false);

        this.checkViewabilityReached();  // viewability could've been reached already (before we got created)!

    };

    FancyStickify.prototype.recordStickyElem = function($elem) {
        var top_limit = parseInt($elem.css('top'), 10);
        this.sticky_$elems_limits.push([$elem, top_limit]);
    };

    FancyStickify.prototype.triggerPaidSticky = function() {
        /*
        Governs when the sticky paid buttons row in the header nav appears.
        Runs on every scroll action so must be performant
        */
        if (!this.paidSticky.length) {
            return;
        }
        // the static buttons have margin not reported by DOM height; get that so we know its bottom position
        var el = this.waitForGoneEls.get(0);
        var n = window.getComputedStyle(el).marginBottom;
        n = Number(n.replace('px', ''));

        // get the height of the paid sticky bar so we can compensate for it
        var stickyHeight = this.paidSticky.get(0).clientHeight;
        var manualAdjust = 10;  // not sure where this gap is coming from :/

        // do math to detect when we've scrolled enough so the static buttons aren't visible.
        var staticButtonsPosition = el.offsetTop + el.clientHeight + stickyHeight + n;
        var windowScroll = window.scrollY + stickyHeight + manualAdjust;
        var doShow = windowScroll > staticButtonsPosition;


        if (!this.paidStickyOn && doShow) {
            this.paidSticky.show();
            this.paidStickyOn = true;
        } else if (this.paidStickyOn && !doShow) {
            this.paidSticky.hide();
            this.paidStickyOn = false;
        }
    };

    FancyStickify.prototype.checkSticky = function() {
        var scrollTop = this.$window.scrollTop();
        for (var i = 0; i < this.sticky_$elems_limits.length; i++) {
            var $elem = this.sticky_$elems_limits[i][0];
            var top_limit = this.sticky_$elems_limits[i][1];
            // TODO this means something already at the top will always be stuck
            if (Math.round($elem.offset().top - scrollTop) <= top_limit) {
                if (!$elem.hasClass('stuck')) {
                    $elem.addClass('stuck');
                }
            } else {
                $elem.removeClass('stuck');

                // special handling for header
                if ($elem.is(this.$header) && this.viewabilityReached) {
                    this.unstickLeaderAd();
                }
            }
        }

        this.triggerPaidSticky();
    };

    FancyStickify.prototype.checkViewabilityReached = function() {
        // events (from other code) will set these classes.  If we're viewable or it was a blank ad, then stop sticking
        if (this.$viewabilityRequirementAd.hasClass('viewableImpression') || this.$viewabilityRequirementAd.hasClass('blank')) {
            this.reachedViewability(this.$viewabilityRequirementAd);
        }
    };

    FancyStickify.prototype.reachedViewability = function($ad) {
        if ($ad.is(this.$viewabilityRequirementAd)) {
            this.viewabilityReached = true;
            if (!this.$header.hasClass('stuck')) {
                this.unstickLeaderAd();
            }
        }
    };

    FancyStickify.prototype.scrollWatcherForHeader = function(e) {
        this._scrollCount++;
        if (this.viewabilityReached && this._scrollCount > 2) { // FF has non-user-initiated scroll events near the onload event, we want to ignore the first one (real scrolls will generate many events anyway)
            this.unstickLeaderAd();
        }
    };

    FancyStickify.prototype.unstickLeaderAd = function() {
        if (!this.unstuckLeaderAlready) {
            // can't move the ad around in the DOM (e.g. out of the sticky div) or it'll break
            // so instead desticky the whole sticky div, and re-stick the top nav only

            // unstick header
            var $headNav = $('.l-header-nav');
            $headNav.css('position', 'static');
            $headNav.removeClass('sticky');  // in case we run before main polyfill is set up, don't want polyfill to activate it again

            // re-stick the header bar we want to keep
            var $headNavRowKeep = $('.l-header-nav-bottom:visible, .l-header-nav-top.hide-for-large:visible');  // small/large screens have different header bars kept sticky, pick the right one here
            $headNavRowKeep.insertBefore(this.$header);  // position: sticky doesn't work when trapped within the wrapper div, so move it up before
            $headNavRowKeep.addClass('sticky');

            if (SF.Ads.scrollFixable) {
                SF.Ads.scrollFixable.scrollRelocate();
            }

            // redo "stuck" listeners
            $headNav.removeClass('stuck');
            for (var i = 0; i < this.sticky_$elems_limits.length; i++) {
                var $elem = this.sticky_$elems_limits[i][0];
                if ($elem.is($headNav)) {
                    this.sticky_$elems_limits.splice(i, 1);  // delete this element
                    break;
                }
            }
            this.recordStickyElem($headNavRowKeep);

            window.removeEventListener('scroll', this._scrollWatcherBound, isPassiveEventListenerSupported() ? {passive: true} : false);

            this.unstuckLeaderAlready = true;
        }
    };

    return FancyStickify;
})();

/* component for adding "scroll fixable" behavior to the right rail
* where the rail will follow you downward, until viewability on the first unit
* is met; after which it will gracefully follow you back up, while allowing the
* bottom parts of the rail to be reachable*/
SF.ScrollFixable = (function(){
    var defaults = {
        avoidElement: '#banner-sterling .sticky',
        adjustHorizontal: true,
        maintainParentWidth: true,
        watchAvoidStickiness: true,
        enforceFloor: true,
    };

    /* ctor */
    function ScrollFixable($el, options){
        if (! $el || $el.length === 0) {
            // abandon if there isn't an element to make sticky.
            return;
        }
        this.o = $.extend({}, defaults, options);
        this.$el = $el;
        this.$parent = $el.parent();
        this.$avoid = $(this.o.avoidElement);
        this.leftPositionContext = window.innerWidth;

        // Y position of the right rail in it's unpinned place
        this.originalTop = null; // wait til last possible moment to calc this
        this.enabled = true;
        this.freezePoint = null;
        this.is_pinned = false;

        //the files page has trouble with jumping heights.
        //correct with hard-coded handicap value for now.
        this.floorCompensate = this.$el.attr('data-floor-compensate') || 0;

        //cache a bound instance of this function for reliable $.on() and $.off(),
        //as the method expects its context to be the current instance (rather than the default jQ event)
        //(and we can't just recklessly call window.scroll.off)
        this.boundScrollDelegate = this.scrollRelocate.bind(this);

        this.init();

        this.scrollRelocate();
    }

    ScrollFixable.prototype.avoidHeight = function() {
        var outerHeight = 0;
        this.$avoid.filter(':visible').each(function() {
          outerHeight += $(this).outerHeight();
        });
        return outerHeight;
    };

    ScrollFixable.prototype.stuckHeight = function() {
        var outerHeight = 0;
        $('.stuck').each(function() {
          outerHeight += $(this).outerHeight();
        });
        return outerHeight;
    };
    /*calculates the uppermost point at which we need to "let go" of the stickiness */
    ScrollFixable.prototype.baseTop = function() {
        var result = 0;
        var watchAvoidStickiness = this.o.watchAvoidStickiness;
        this.$avoid.filter(':visible').each(function() {
            var $t = $(this);
            if (watchAvoidStickiness && !$t.hasClass('stick') && !$t.hasClass('stuck')) {
                //if it's not sticky, we don't want to avoid it.
                return result;
            }
            result += $t.outerHeight();
        });
        return result;
    };

    /* stateful check to see if we are in the process of gracefully unwinding the stickiness */
    ScrollFixable.prototype.disabling = function() {
        return this.freezePoint !== null;
    };

    ScrollFixable.prototype.parentHeight = function() {
        this._nav = this._nav || this.$el.siblings('nav');
        function calc() {
            var result = this.$parent.height();
            if (this._nav){
                result += (this._nav.outerHeight(true) * 2);
            }
            return result;

        }
        return calc.apply(this);
    };


    ScrollFixable.prototype.enforceFloor = function(baseTop) {
        if (this.enabled && this.o.enforceFloor){
            var limitHeight;
            // calculate the position of the bottom edge of the body content container. then, backout the position of the stuck rail
            limitHeight = this.parentHeight() + this.$el.parent().offset().top - this.$el.offset().top;
            this.$el.height(limitHeight + parseInt(this.floorCompensate));
        }
    };

    /* main scroll handler */
    ScrollFixable.prototype.scrollRelocate = function() {
        if (!this.enabled) {
            return;
        }
        this.recalculateTop();
        var windowScrollTop = $(window).scrollTop();
        var baseTop = this.baseTop();
        if (this.disabling()){
            //we are gracefully winding down.

            //going up or down?
            if (windowScrollTop > this.freezePoint) {
                // going down
                var newTop = windowScrollTop - this.freezePoint ;
                var adjustedNewTop = -newTop + baseTop;
                this.$el.css('top', adjustedNewTop);
            }
            else {
                // going up...
                if (windowScrollTop <= this.originalTop - baseTop) {
                    // at the top yet?
                    this.disable();
                } else {
                    this.$el.css('top', baseTop);
                    //make sure this.freezePoint is updated to latest top point
                    //as we continue upward
                    this.freezePoint = windowScrollTop;
                }
            }
            this.enforceFloor(baseTop);
            return;
        }

        this.checkViewabilityRequirement();
        this.nativeTop = this.$el.offset().top;
        this.scrollPositionY = windowScrollTop;
        if(this.pinnable(baseTop)){
            //before taking this action, must ensure that the widget is still
            //enabled, and a race condition hasn't occurred where it should now
            //be disabled
            if (!this.is_pinned && this.enabled) {

                if(this.o.adjustHorizontal) {
                    // calc before we are about to go fixed
                    this.leftPosition = this.$el.offset().left;
                    this.horizontalRelocate();
                }

                this.$el.addClass('scroll-fixable-enabled');
                this.$el.css('top', baseTop);
            }
            this.is_pinned = true;
        } else {
            this.$el.removeClass('scroll-fixable-enabled');
            this.is_pinned = false;
        }

        if (this.is_pinned) {
            this.enforceFloor(baseTop);
            this.$el.css('top', baseTop);
        }
    };

    /* calculate if we have scrolled far enough down to where we must start sticking the right rail */
    ScrollFixable.prototype.pinnable = function(baseTop) {
        if (this.scrollPositionY  >= this.nativeTop - baseTop && this.scrollPositionY >= this.originalTop - baseTop) {
            return true;
        } else {
            return false;
        }
    };

    /* recalculate the position of the right rail when it is in its natural, static position.
     * This can change as the height of content above it (like ads) changes/renders */
    ScrollFixable.prototype.recalculateTop = function() {
        this.originalTop = this.$parent.offset().top;
    };

    /* moves the fixed positioned element left or right, to maintain the correct appearance if the
     * viewport widens/narrows.  Only used on bluesteel pages */
    ScrollFixable.prototype.horizontalRelocate = function(newLeft) {
        if(this.o.maintainParentWidth) {
            var parentInnerWidth = this.$el.parent().innerWidth();
            this.$el.css('left', this.$el.parent().offset().left + this.horizontalMarginOffset);
            this.$el.width(parentInnerWidth - this.horizontalOffset - 40);
        } else {
            if(this.o.adjustHorizontal) {
                this.$el.css('left', newLeft || this.leftPosition );
            }
        }
    };

    /* calculate the proper X position of the stuck thing.  Only used on bluesteel */
    ScrollFixable.prototype.calculateHorizontalPosition = function() {
        var delta = this.leftPositionContext - window.innerWidth;
        this.leftPosition = this.leftPosition - (delta / 2);
        this.leftPositionContext = window.innerWidth;
        this.horizontalRelocate();
    };

    /* begin the process of disabling the stickiness gracefully */
    ScrollFixable.prototype.disableGracefully = function($el) {
        this.freezePoint = $(window).scrollTop();
        this.scrollRelocate();
    };

    /* disable any further stickiness */
    ScrollFixable.prototype.disable = function() {
        this.enabled = false;
        this.$el.removeClass('scroll-fixable-enabled');
        this.is_pinned = false;
        $(window).off('scroll', this.boundScrollDelegate);
        $('body').off('widthChanged');
        this.$el.removeAttr('style');
    };

    /* checks the viewability status of the first ad in the right rail, and if it has been met,
    * begin unwinding the stickiness */
    ScrollFixable.prototype.checkViewabilityRequirement = function() {
        if (this.enabled && !this.disabling() && (
                this.viewabilityRequirementAd.hasClass('viewableImpression') || this.viewabilityRequirementAd.hasClass('blank')
            )
        ) {
            this.disableGracefully();
        }
    };

    /* initialization */
    ScrollFixable.prototype.init = function($el) {

        SF.Breakpoints = SF.Breakpoints || {
            small: 0,
            medium: 640,
            leaderboard: 743,
            billboard: 985,
            large: 1053,
            xlarge: 1295,
            xxlarge: 1366
          };

        window.addEventListener('scroll', this.boundScrollDelegate, isPassiveEventListenerSupported() ? {passive: true} : false);

        if(this.o.adjustHorizontal) {
            $('body').on('widthChanged', this.calculateHorizontalPosition.bind(this));
        }

        //assuming the first ad in the scrollfixable container is what we care about for stickiness lifetime
        this.viewabilityRequirementAd = $('.draper', this.$el).eq(0);

        //one time standup
        if (!SF.viewportWidth) {
            SF.viewportWidth = window.innerWidth;
            var self = this;
            window.addEventListener('resize', function(event){
                if (SF.viewportWidth === event.target.innerWidth){
                    return;
                }else{
                    SF.viewportWidth = event.target.innerWidth;
                    if (SF.viewportWidth < SF.Breakpoints.large) {
                        self.disable();
                    }
                    $('body').trigger('widthChanged');
                }
            });
        }

        if(this.o.maintainParentWidth) {
            // cache original margins because this class will strip them upon going sticky
            this.horizontalPaddingOffset = Number(this.$el.css('padding-left').replace('px', ''));
            this.horizontalMarginOffset = Number(this.$el.css('margin-left').replace('px', ''));
            this.horizontalBorderOffset = Number(this.$el.css('border-left-width').replace('px', ''));
            this.horizontalOffset = this.horizontalPaddingOffset + this.horizontalMarginOffset + this.horizontalBorderOffset;
        }
    };

    return ScrollFixable;
})();
;
// https://github.com/bensmithett/dragster

// Generated by CoffeeScript 1.8.0
(function() {
  var Dragster,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  Dragster = (function() {
    function Dragster(el) {
      this.el = el;
      this.dragleave = __bind(this.dragleave, this);
      this.dragenter = __bind(this.dragenter, this);
      if (this.supportsEventConstructors()) {
        this.first = false;
        this.second = false;
        this.el.addEventListener("dragenter", this.dragenter, false);
        this.el.addEventListener("dragleave", this.dragleave, false);
      }
    }

    Dragster.prototype.dragenter = function(event) {
      if (this.first) {
        return this.second = true;
      } else {
        this.first = true;
        return this.el.dispatchEvent(new CustomEvent("dragster:enter", {
          bubbles: true,
          cancelable: true,
          detail: {
            dataTransfer: event.dataTransfer
          }
        }));
      }
    };

    Dragster.prototype.dragleave = function(event) {
      if (this.second) {
        this.second = false;
      } else if (this.first) {
        this.first = false;
      }
      if (!this.first && !this.second) {
        return this.el.dispatchEvent(new CustomEvent("dragster:leave", {
          bubbles: true,
          cancelable: true,
          detail: {
            dataTransfer: event.dataTransfer
          }
        }));
      }
    };

    Dragster.prototype.removeListeners = function() {
      this.el.removeEventListener("dragenter", this.dragenter, false);
      return this.el.removeEventListener("dragleave", this.dragleave, false);
    };

    Dragster.prototype.supportsEventConstructors = function() {
      try {
        new CustomEvent("z");
      } catch (_error) {
        return false;
      }
      return true;
    };

    Dragster.prototype.reset = function() {
      this.first = false;
      return this.second = false;
    };

    return Dragster;

  })();

  if (typeof module === 'undefined') {
    window.Dragster = Dragster;
  } else {
    module.exports = Dragster;
  }

}).call(this);;
/*global $, SF, bizx */

function initFancyStickify() {
    $(function () {
        SF.Ads.fancyStickify = new SF.FancyStickify($('.sticky'), {waitForGoneEls: '.project-masthead .buttons, .popular-cards .projects-inner '});
        SF.Ads.fancyStickify.init();
        if (SF.Ads.acceptable_ads_active || SF.Ads.skipStickyAds){
            SF.Ads.fancyStickify.unstickLeaderAd();
        }
    });
}
bizx.cmp.ifConsent({ purposes: 'all', vendors: ['google-ads']}, function () {
    initFancyStickify();
});


/* Touchscreen fix for iphone menu active state. */
document.addEventListener("touchstart", function() {}, false);


/* Collapsed header search toggle. */
$('.search-toggle').on("click", function () {
    $('.search').toggleClass('sticky-search-open');
    $('.search-toggle-when-stuck').toggleClass('sticky-search-open');
    $('.search input').trigger("focus");
});


$('select.use-placeholder-color').on('change', function() {
    $(this).toggleClass('first-option-selected', this.value === '');
}).trigger('change');


function escape_html(str) {
    return $('<i></i>').text(str).html();
}

$(function() {
    var fixed_suggestions_endpoint = 'directory_fixed_suggestions' + (SF.variant === 'sd' ? '_slash' : (SF.variant === 'tbs' ? '_tbs' : ''));
    var categories_url = SF.cdn + '/app/' + fixed_suggestions_endpoint + '/?v2&' + (new Date()).toISOString().slice(0, 10);
    var business_software_caption = SF.variant === 'tbs' ? 'Products' : 'Business Software & Services';
    var $typeaheads = $('.typeahead__container input[name=q]');
    if (!$typeaheads.length) {
        return;
    }
    // avoid a bad empty cache with 0 items that can happens sometimes for unknown reason
    var cached_bus_cats = localStorage.getItem("TYPEAHEAD_input:Business Categories");
    if (cached_bus_cats) {
        var bad_cache = false;
        try {
            if (JSON.parse(cached_bus_cats).data.length < 10) {
                bad_cache = true;
            }
        } catch (e) {
            // e.g. JSON.parse fails
            bad_cache = true;
        }
        if (bad_cache) {
            localStorage.removeItem("TYPEAHEAD_input:Business Categories");
            localStorage.removeItem("TYPEAHEAD_input:Open Source Categories");
        }
    }

    function addFullSearchLink($resultHtmlList, group, query, search_url, text) {
        // modifies $resultHtmlList for the given 'group' to add or update a result entry for doing a full search

        var $last_result = $('.typeahead__group-' + group + ':last', $resultHtmlList);
        // build with jQ instead of constructing ourselves, to avoid XSS injection
        var link = search_url + query;
        var $html = $('<li>', {'class': "typeahead__item full-search-row"}).append(
            $('<a>', {href: link}).append(
                $('<span>', {'class': 'typeahead__display'}).text(text)
            )
        ).append(
            $('<a>', {href: link}).append(
                '<svg data-name="search" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1216 832q0-185-131.5-316.5t-316.5-131.5-316.5 131.5-131.5 316.5 131.5 316.5 316.5 131.5 316.5-131.5 131.5-316.5zm512 832q0 52-38 90t-90 38q-54 0-90-38l-343-342q-179 124-399 124-143 0-273.5-55.5t-225-150-150-225-55.5-273.5 55.5-273.5 150-225 225-150 273.5-55.5 273.5 55.5 225 150 150 225 55.5 273.5q0 220-124 399l343 343q37 37 37 90z"></path></svg></label>'
            )


        );
        if ($last_result.text().indexOf('full-search-placeholder')>=0 ) {  // this is a hardcoded result (see "data" config)
            $last_result.replaceWith($html);
        } else {
            $last_result.after($html);
        }
    }

    function forceInResults(q, r, $resultHtmlList) {
        var cont = true;
        var idx = 0;
        var forcedMatches = {
            'captcha': {
                slug: 'MTCaptcha',
                name: 'MTCaptcha',
                icon_url: 'https://a.fsdn.com/allura/s/mtcaptcha/icon?6a65976aae81e674c6386f85c67bee68ca4ca5c72de8e367529f437149b33d80?&w=180'
            },
            'dmarc': {
                slug: 'EasyDMARC',
                name: 'EasyDMARC',
                icon_url: 'https://a.fsdn.com/allura/s/easydmarc/icon?d8cdea5566b3224406d2fd22c2184173772b5d90fe04572ec3932a1ae328844a?&w=90'
            },
        };

        var match = forcedMatches[q.toLowerCase()];
        if (!match) {
            return;
        }

        var lis = $resultHtmlList.find('li');
        while(cont){
            var group = lis.eq(idx).text();
            if (idx >= lis.length || (group && group.indexOf('Business Software') === 0)) {
                cont = false;
            }
            idx ++;
        }

        var welded = templateWithIcon.replace('{{icon_url}}', match.icon_url).replace('{{name}}', match.name);
        var fullLink = $('<li>', {'class':'typeahead__item typeahead__group-business-software-services'})
                            .append($('<a>', {href:'/software/product/' + match.slug})
                            .append(welded));
        $resultHtmlList.find("li:nth-child(" + (idx) + ")").after(fullLink);
    }

    //pre-define these templates so that the template string doesn't have to be constructed for every result item
    var templateProject = '<div class="summary-tile"><div class="autocomplete-sf-icon"></div>{{name}}<br> <div class="m-stars"></div></div>';
    var templateWithIcon = '<div class="summary-tile"><img src="{{icon_url}}">{{name}}<br> <div class="m-stars"></div></div>';
    var templateBuilderFn = function(item, item_data){
        return item_data.icon_url ? templateWithIcon : templateProject;
    };

    $typeaheads.each(function() {
        var $typeahead = $(this);
        $typeahead.on('input', function(ev) {
            $typeahead.data('q', ev.target.value);
        });
        var config = {
            ttl: 24 * 60 * 60 * 1000,
            group: true,
            maxItem: 0,
            mustSelectItem: $typeahead.data('prevent-submit') ? true : false,
            maxItemPerGroup: 4,
            cancelButton: false,
            emptyTemplate: "<p><p>No quick results found.<p>Press ENTER to do a full search.",
            href: "{{url}}",
            callback: {
                onLayoutBuiltBefore: function (node, query, result, $resultHtmlList) {
                    addFullSearchLink($resultHtmlList, 'open-source-projects', query, '/directory/?q=', 'Search Open Source for "' + query + '" ...');
                    addFullSearchLink($resultHtmlList, 'business-software-services', query, '/software/?q=', 'Search ' + business_software_caption + ' for "' + query + '" ...');
                    forceInResults(query, result, $resultHtmlList);
                    return $resultHtmlList;
                },
                onPopulateSource: function (node, data, group, path) {
                    // escape potential HTML from solr results
                    if (path === 'response.docs') {
                        for (var i = 0; i < data.length; i++) {
                            data[i].name = escape_html(data[i].name);
                        }
                    }
                    return data;
                },
                onClickBefore: function($typeahead, a, item, event){
                    var q = $typeahead.data('q');
                    $typeahead.trigger('typeahead-item-clicked', [$typeahead, q, item]);
                },
                onHideLayout: function($typeahead, a, item, event){
                    $('.search-results-backdrop').removeClass('active');
                },
                onShowLayout: function($typeahead, a, item, event){
                    if ($typeahead.data('scroll-to')) {
                        var top = $typeahead.offset().top;
                        if($('.sandiego.sticky').length) { // accomodate sticky header when present
                            top -= $('.sandiego.sticky').outerHeight();
                        }
                        $('html').scrollTop(top);
                    }

                    $('.search-results-backdrop').addClass('active');

                    if ($('.typeahead-arrow-hint').length) {
                        $('.typeahead-arrow-hint').remove();
                    }

                    var html = '<svg class="svgico typeahead-arrow-hint"><use xlink:href="#download"></use></svg>';
                    // arrows
                    $('.typeahead__item.full-search-row').each(function(){
                        var $arrow = $(html);
                        $(this).prepend($arrow);

                    });
                }
            },
        };
        var $container = $typeahead.closest('.typeahead__container');
        var data_bis = [];
        if (SF.variant !== 'tbs'){
            data_bis = [
                {name: 'full-search-placeholder'}
            ];
        }
        var sources_groups = {
            'Open Source Categories': {
                dynamic: false,
                cache: true,
                ajax: {
                    url: categories_url,
                    path: "opensource_categories",
                },
            },
            'Open Source Projects': {
                dynamic: true,
                cache: false,
                filter: false,
                ajax: {
                    url: '/proxy-api/search/suggest-project?q={{query}}',
                    path: "response.docs",
                },
                data: [  // placeholder to force this group to always show up
                    {name: 'full-search-placeholder'}
                ],
                href: "{{project_url}}",
                display: ['name'],
                template: templateBuilderFn
            },
            'Business Categories': {
                dynamic: false,
                cache: true,
                ajax: {
                    url: categories_url,
                    path: "commercial_categories",
                },
                filter: function(item, displayKey){
                    if((new RegExp(this.rawQuery, 'i')).test(displayKey)) {
                        return true;
                    } else if (this.rawQuery.indexOf(' ') > 0 && new RegExp(this.rawQuery.replace(' ', '-'), 'i').test(displayKey)) {
                        return true;
                    }
                }
            },
            [business_software_caption]: {
                dynamic: true,
                cache: false,
                filter: false,
                ajax: {
                    url: '/proxy-api/search/suggest-commercial?q={{query}}' + ($container.data('commercial-hidden') ? '&hidden=true' : ''),
                    path: "response.docs",
                },
                data: data_bis,
                href: function(res){
                    // handle different variant routes for the billboard page
                    if (res.slug) {
                        return SF.billboard_route.replace("$slug", res.slug);
                    }
                },

                display: ['name'],
                template: templateBuilderFn
            },
        };

        // these are all categories, and their order
        var sources_groups_keys = Object.keys(sources_groups);
        $typeahead.data('groups', sources_groups_keys);
        if ($('body').hasClass('v-sd') || $('body').hasClass('v-tbs') || $container.data('commercial-only')) {
            delete sources_groups['Open Source Categories'];
            delete sources_groups['Open Source Projects'];
        } else if ($container.data('oss-only')) {
            delete sources_groups['Business Categories'];
            delete sources_groups[business_software_caption];
        }
        config.source = sources_groups;
        if ($container.data('commercial-only')) {
            config.groupOrder = ['Business Categories', business_software_caption];
        } else if ($container.data('oss-only')) {
            config.groupOrder = ['Open Source Categories', 'Open Source Projects'];
        } else if ($container.data('commercial-default')) {
            config.groupOrder = ['Business Categories', business_software_caption, 'Open Source Categories', 'Open Source Projects'];
        } else {
            config.groupOrder = ['Open Source Categories', 'Open Source Projects', 'Business Categories', business_software_caption];
        }
        $typeahead.typeahead(config);

    });
});



/*
Fix anchor targets being hidden by the sticky header

from https://stackoverflow.com/a/13067009/ jquery version http://jsfiddle.net/ianclark001/rkocah23/
We have customized getFixedOffset() and use scrollTop() directly instead of animate()

caveat: if the page height changes after dom-ready (e.g. images loading) and the target is near the end of the page
the browser may not let scrollTop be set to what we want since it thinks the page isn't that tall yet
*/

/*
The browser can fire a scroll event for moving to the intended hash target (which isn't quite the right location).
So we need to listen for the first scroll event and force scrolling to the right spot.
In Chrome currently, when reloading a page, the browser tries to put you back to the same scroll position as you were
at earlier, so it fires another event (after the our own scrolling event), so this cause the page to jump around :(
 */
var $stickyHeader = $('.l-header-nav.sticky');
if ($stickyHeader.length) {
    SF._scroll_listener_for_hash = function (e) {
        document.removeEventListener('scroll', SF._scroll_listener_for_hash);
        if (SF.anchorOffsetActive) {
            $(window).trigger('hashchange'); // force it to run again
        }
    };
    document.addEventListener('scroll', SF._scroll_listener_for_hash);

    (function (document, history, location) {
        var HISTORY_SUPPORT = !!(history && history.pushState);

        var anchorScrolls = {
            ANCHOR_REGEX: /^#(?!md_)[^ ]+$/, // special exlucion for md_, which are markdown formatting help links within a modal

            /**
             * Establish events, and fix initial scroll position if a hash is provided.
             */
            init: function () {
                this.scrollToCurrent();
                $(window).on('hashchange', $.proxy(this, 'scrollToCurrent'));
                $('body').on('click', 'a', $.proxy(this, 'delegateAnchors'));
            },

            /**
             * Return the offset amount to deduct from the normal scroll position.
             * Modify as appropriate to allow for dynamic calculations
             */
            getFixedOffset: function () {
                // sticky leaderboard can cause some oddities if ads are present, but this seems to generally work ok
                return $stickyHeader.height();
            },

            /**
             * If the provided href is an anchor which resolves to an element on the
             * page, scroll to it.
             * @param  {String} href
             * @return {Boolean} - Was the href an anchor.
             */
            scrollIfAnchor: function (href, pushToHistory) {
                var match, anchorOffset;

                if (!this.ANCHOR_REGEX.test(href)) {
                    return false;
                }

                var target = href.slice(1);
                match = document.getElementById(target) || document.getElementsByName(target)[0];

                if (match) {
                    anchorOffset = $(match).offset().top - this.getFixedOffset();
                    SF.anchorOffsetActive = true;
                    $('html, body').scrollTop(anchorOffset);

                    // Add the state to history as-per normal anchor links
                    if (HISTORY_SUPPORT && pushToHistory) {
                        history.pushState({}, document.title, location.pathname + href);
                    }
                }

                return !!match;
            },

            /**
             * Attempt to scroll to the current location's hash.
             */
            scrollToCurrent: function (e) {
                if (this.scrollIfAnchor(window.location.hash) && e) {
                    e.preventDefault();
                }
            },

            /**
             * If the click event's target was an anchor, fix the scroll position.
             */
            delegateAnchors: function (e) {
                var elem = e.target;

                if (this.scrollIfAnchor(elem.getAttribute('href'), true)) {
                    e.preventDefault();
                }
            }
        };

        $(document).ready($.proxy(anchorScrolls, 'init'));
    })(window.document, window.history, window.location);
}


// wire up obfuscated links
$('[data-href], [data-dest]').each(function (i, el) {
    var $el = $(el);
    let href = el.getAttribute('data-href') || el.getAttribute('data-dest');
    if ($el.prop('tagName') === 'A') {
        el.setAttribute('href', href);
    } else {
        $(el).on('click', function(){
            if ($(this).data('target') && $(this).data('newtab')) {
                Object.assign(document.createElement('a'), {
                target: $(this).data('target'),
                href: href,
                }).click();
            }else{
                top.location = href;
            }
        });
    }
});

if($('.js-required').length) {
    $('.js-required').hide();
}

// main nav ad unit button link in nav menu
// keep in sync with maxnav.js
$('#main-nav-badge-link').off('click').on('click', function(e){
    var label = $(this).data('label') || 'MaxNav';
    window._paq.push(['trackEvent', 'Nav Menu', label]);
});

$('#privacy-choices').on('click', function(e){
    e.preventDefault();
    bizx.cmp.promptConsent();
});
;
/* global $, SF, recaptchaLoad */

$(function(){
    /* Social Sharing */
    $('#share-project-button').on("click", function (e) {
        // expose buttons and remove the toggle button.
        e.preventDefault();
        $(this).remove();
        $('.social-sharing-buttons').removeClass('hide');
        $('.social-sharing-buttons').removeClass('invisible');
    });

    $('.social-sharing-buttons a').on('click', function (e) {
        e.preventDefault();
        var url = this.href;
        // Google has different dimensions for their widget, so they're special here.
        var height = this.className === 'google' ? 520 : 444,
            width = this.className === 'google' ? 390: 680;
        window.open(url, 'sourceforge_social_share', 'resizeable, height=' + height + ',width=' + width);
    });

    // Modify External Links
    var modLink = function() {
        $(this).attr('target', '_blank');
        $(this).addClass('ext-link');
        $(this).append('<span class="sf-linkout-icon">' + SF.linkout_icon + '</span>');
    };

    // Mark external links: explitly tagged, navbar, and PSP elements
    $('a[data-external], #top_nav a[rel*=nofollow], .features a, a#homepage, .description a')
        .not('[href^="/"]').not('[href^="#"]').not('[href^="."]').not('[href*="sourceforge.net"]').not('[href*=".sourceforge.io"]').not('[href*="sb.sf.net"]')
        .not('[href*="xb.sf.net"]').not('[href*="slashdot.org"]')
        .each(modLink);

    $('.get-updates.button').on("click", function (e) {
        e.preventDefault();
    });
    
    var getUrlHash = function() {
        var el_id = '#' + window.location.hash.replace(/[^\w-]/g, "");
        var location_hash;
        try {
            location_hash = $(window.document).find(el_id);
        } catch(error) {
            location_hash = $();
        }
        return location_hash;
    };

    // reveal any modals or collapsed sections, indicated by URL hash fragment -- but skip if Ember/Svelte is on the page.
    if (!$('.ember-application').length && !$('[id*="svelte-"]').length) {
        var target;
        target = getUrlHash();

        if (target.length > 0 && typeof target.attr('data-reveal') !== typeof undefined && target.attr('data-reveal') !== false) {
            target.foundation('open');
        }
        var uncollapse_section = function() {
            target = getUrlHash();
            target.filter('.psp-section').addClass('is-active');
        };
        uncollapse_section();
        $(window).on('hashchange', uncollapse_section);
    }

    // focus any autofocus inputs within modals
    $(document).on('open.zf.reveal', '[data-reveal]', function () {
        var modal = $(this);
        modal.find('[autofocus]').focus();
    });

    //modal listener for get_updates_button_helper
    if ($('#psp-newsletter-modal').length) {
        $(document).on('open.zf.reveal', "#psp-newsletter-modal", function (e) {
            var $modal = $(this);
            var ajax_url = $modal.data("ajax-url");
            if (ajax_url) {
                var params;
                if (document.location.search) {
                    if (ajax_url.indexOf('?') > -1) {
                        params = document.location.search.replace('?', '&');
                    } else {
                        params = document.location.search;
                    }
                } else {
                    params = '';
                }
                $.ajax(ajax_url + params).done(function (response) {
                    $modal.html(response);
                    // redoing things that happen at dom-ready
                    // TODO: refactor this
                    if ($('.js-required').length) {
                        $('.js-required').hide();
                    }
                    $('.newsletter-subscribe-form').each(SF.wire_up_subscribe_form);
                    recaptchaLoad();
                });
            }
        });
    }
});


// wire up collapsible sidebar; don't wait for domready; only on FC/allura
if ($('body#forge').length && ! $('body.legacy_chrome').length) {
    var $sidebarActivate = $('#sidebar-activate');
    var toolName = $('#top_nav_admin li.selected').text().trim();

    $('.btn-label', $sidebarActivate).text(toolName + ' Menu');
    $('.btn-arrow-up').toggle();

    $sidebarActivate.on('click', function () {
        $('#sidebar').toggle(500, function() {
            var $sb = $('#sidebar');
            if (!$sb.is(':visible')) {
                // when it is not visible, remove the style=display:none
                // since it's not needed and can cause precendence issues elsewhere (e.g. commercial leads page)
                $sb.removeAttr('style');
            }
        });
        $('.btn-arrow-down', $sidebarActivate).toggle();
        $('.btn-arrow-up', $sidebarActivate).toggle();
        return false;
    });
}

// use this on tablesorter tables, to update our SVG sort icons
SF.tablesorter_svg_update = function() {
    $('th.usersortable div use').each(function(idx) {
        var $use = $(this);
        var $th = $use.closest('th.usersortable');
        if ($th.hasClass('tablesorter-headerDesc')) {
            $use.attr("xlink:href", "#sort_down");
        } else if ($th.hasClass('tablesorter-headerAsc')) {
            $use.attr("xlink:href", "#sort_up");
        } else {
            $use.attr("xlink:href", "#sort");
        }
    });
};

SF.LogJS = function() {
    function log(level, message, extra_details){
        var domain = window.location.hostname;
        if (domain.indexOf('.xb.sf.net') !== -1) {
            domain = domain.replace('slash-', 'sf-').replace('tbs-', 'sf-');
        } else if (domain !== 'sourceforge.net') {
            domain = 'sourceforge.net';
        }
        domain = 'https://' + domain;
        var querystring = '';
        if (extra_details) {
            querystring = '?' + $.param(extra_details);
        }
        $.ajax({
            url: domain + '/logjs' + querystring,
            type: 'put',
            data: { level: level, message: message },
            global: false
        });
    }

    function debug(message, extra_details) {
        log('debug', message, extra_details);
    }

    function info(message, extra_details) {
        log('info', message, extra_details);
    }

    function warning(message, extra_details) {
        log('warning', message, extra_details);
    }

    function error(message, extra_details) {
        log('error', message, extra_details);
    }

    function critical(message) {
        log('critical', message);
    }

    return {
        log: log,
        debug: debug,
        info: info,
        warning: warning,
        error: error,
        critical: critical
    };
};

SF.logjs = SF.LogJS();
;
!function(t){function n(i){if(e[i])return e[i].exports;var r=e[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}var e={};n.m=t,n.c=e,n.i=function(t){return t},n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:i})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},n.p="",n(n.s=6)}([function(t,n){t.exports=jQuery},function(t,n,e){"use strict";function i(){return"rtl"===u()("html").attr("dir")}function r(t,n){return t=t||6,Math.round(Math.pow(36,t+1)-Math.random()*Math.pow(36,t)).toString(36).slice(1)+(n?"-"+n:"")}function o(t){var n,e={transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend"},i=document.createElement("div");for(var r in e)void 0!==i.style[r]&&(n=e[r]);return n||(n=setTimeout(function(){t.triggerHandler("transitionend",[t])},1),"transitionend")}e.d(n,"a",function(){return i}),e.d(n,"b",function(){return r}),e.d(n,"c",function(){return o});var a=e(0),u=e.n(a)},function(t,n,e){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var i=e(0),r=e.n(i),o=e(3),a=e(1),u=e(4);o.a.addToJquery(r.a),o.a.rtl=a.a,o.a.GetYoDigits=a.b,o.a.transitionend=a.c,o.a.Plugin=u.a,window.Foundation=o.a},function(t,n,e){"use strict";function i(t){if(void 0===Function.prototype.name){var n=/function\s([^(]{1,})\(/,e=n.exec(t.toString());return e&&e.length>1?e[1].trim():""}return void 0===t.prototype?t.constructor.name:t.prototype.constructor.name}function r(t){return"true"===t||"false"!==t&&(isNaN(1*t)?t:parseFloat(t))}function o(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}e.d(n,"a",function(){return l});var a=e(0),u=e.n(a),s=e(1),c=e(5),l={version:"6.4.3",_plugins:{},_uuids:[],plugin:function(t,n){var e=n||i(t),r=o(e);this._plugins[r]=this[e]=t},registerPlugin:function(t,n){var r=n?o(n):i(t.constructor).toLowerCase();t.uuid=e.i(s.b)(6,r),t.$element.attr("data-"+r)||t.$element.attr("data-"+r,t.uuid),t.$element.data("zfPlugin")||t.$element.data("zfPlugin",t),t.$element.trigger("init.zf."+r),this._uuids.push(t.uuid)},unregisterPlugin:function(t){var n=o(i(t.$element.data("zfPlugin").constructor));this._uuids.splice(this._uuids.indexOf(t.uuid),1),t.$element.removeAttr("data-"+n).removeData("zfPlugin").trigger("destroyed.zf."+n);for(var e in t)t[e]=null},reInit:function(t){var n=t instanceof u.a;try{if(n)t.each(function(){u()(this).data("zfPlugin")._init()});else{var e=typeof t,i=this;({object:function(t){t.forEach(function(t){t=o(t),u()("[data-"+t+"]").foundation("_init")})},string:function(){t=o(t),u()("[data-"+t+"]").foundation("_init")},undefined:function(){this.object(Object.keys(i._plugins))}})[e](t)}}catch(t){console.error(t)}finally{return t}},reflow:function(t,n){void 0===n?n=Object.keys(this._plugins):"string"==typeof n&&(n=[n]);var e=this;u.a.each(n,function(n,i){var o=e._plugins[i];u()(t).find("[data-"+i+"]").addBack("[data-"+i+"]").each(function(){var t=u()(this),n={};if(t.data("zfPlugin"))return void console.warn("Tried to initialize "+i+" on an element that already has a Foundation plugin.");t.attr("data-options")&&t.attr("data-options").split(";").forEach(function(t,e){var i=t.split(":").map(function(t){return t.trim()});i[0]&&(n[i[0]]=r(i[1]))});try{t.data("zfPlugin",new o(u()(this),n))}catch(t){console.error(t)}finally{return}})})},getFnName:i,addToJquery:function(t){var n=function(n){var e=typeof n,r=t(".no-js");if(r.length&&r.removeClass("no-js"),"undefined"===e)c.a._init(),l.reflow(this);else{if("string"!==e)throw new TypeError("We're sorry, "+e+" is not a valid parameter. You must use a string representing the method you wish to invoke.");var o=Array.prototype.slice.call(arguments,1),a=this.data("zfPlugin");if(void 0===a||void 0===a[n])throw new ReferenceError("We're sorry, '"+n+"' is not an available method for "+(a?i(a):"this element")+".");1===this.length?a[n].apply(a,o):this.each(function(e,i){a[n].apply(t(i).data("zfPlugin"),o)})}return this};return t.fn.foundation=n,t}};l.util={throttle:function(t,n){var e=null;return function(){var i=this,r=arguments;null===e&&(e=setTimeout(function(){t.apply(i,r),e=null},n))}}},window.Foundation=l,function(){Date.now&&window.Date.now||(window.Date.now=Date.now=function(){return(new Date).getTime()});for(var t=["webkit","moz"],n=0;n<t.length&&!window.requestAnimationFrame;++n){var e=t[n];window.requestAnimationFrame=window[e+"RequestAnimationFrame"],window.cancelAnimationFrame=window[e+"CancelAnimationFrame"]||window[e+"CancelRequestAnimationFrame"]}if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){var i=0;window.requestAnimationFrame=function(t){var n=Date.now(),e=Math.max(i+16,n);return setTimeout(function(){t(i=e)},e-n)},window.cancelAnimationFrame=clearTimeout}window.performance&&window.performance.now||(window.performance={start:Date.now(),now:function(){return Date.now()-this.start}})}(),Function.prototype.bind||(Function.prototype.bind=function(t){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var n=Array.prototype.slice.call(arguments,1),e=this,i=function(){},r=function(){return e.apply(this instanceof i?this:t,n.concat(Array.prototype.slice.call(arguments)))};return this.prototype&&(i.prototype=this.prototype),r.prototype=new i,r})},function(t,n,e){"use strict";function i(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function r(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function o(t){return r(void 0!==t.constructor.name?t.constructor.name:t.className)}e.d(n,"a",function(){return c});var a=e(0),u=(e.n(a),e(1)),s=function(){function t(t,n){for(var e=0;e<n.length;e++){var i=n[e];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(n,e,i){return e&&t(n.prototype,e),i&&t(n,i),n}}(),c=function(){function t(n,r){i(this,t),this._setup(n,r);var a=o(this);this.uuid=e.i(u.b)(6,a),this.$element.attr("data-"+a)||this.$element.attr("data-"+a,this.uuid),this.$element.data("zfPlugin")||this.$element.data("zfPlugin",this),this.$element.trigger("init.zf."+a)}return s(t,[{key:"destroy",value:function(){this._destroy();var t=o(this);this.$element.removeAttr("data-"+t).removeData("zfPlugin").trigger("destroyed.zf."+t);for(var n in this)this[n]=null}}]),t}()},function(t,n,e){"use strict";function i(t){var n={};return"string"!=typeof t?n:(t=t.trim().slice(1,-1))?n=t.split("&").reduce(function(t,n){var e=n.replace(/\+/g," ").split("="),i=e[0],r=e[1];return i=decodeURIComponent(i),r=void 0===r?null:decodeURIComponent(r),t.hasOwnProperty(i)?Array.isArray(t[i])?t[i].push(r):t[i]=[t[i],r]:t[i]=r,t},{}):n}e.d(n,"a",function(){return u});var r=e(0),o=e.n(r),a=window.matchMedia||function(){var t=window.styleMedia||window.media;if(!t){var n=document.createElement("style"),e=document.getElementsByTagName("script")[0],i=null;n.type="text/css",n.id="matchmediajs-test",e&&e.parentNode&&e.parentNode.insertBefore(n,e),i="getComputedStyle"in window&&window.getComputedStyle(n,null)||n.currentStyle,t={matchMedium:function(t){var e="@media "+t+"{ #matchmediajs-test { width: 1px; } }";return n.styleSheet?n.styleSheet.cssText=e:n.textContent=e,"1px"===i.width}}}return function(n){return{matches:t.matchMedium(n||"all"),media:n||"all"}}}(),u={queries:[],current:"",_init:function(){var t=this;o()("meta.foundation-mq").length||o()('<meta class="foundation-mq">').appendTo(document.head);var n,e=o()(".foundation-mq").css("font-family");n=i(e);for(var r in n)n.hasOwnProperty(r)&&t.queries.push({name:r,value:"only screen and (min-width: "+n[r]+")"});this.current=this._getCurrentSize(),this._watcher()},atLeast:function(t){var n=this.get(t);return!!n&&a(n).matches},is:function(t){return t=t.trim().split(" "),t.length>1&&"only"===t[1]?t[0]===this._getCurrentSize():this.atLeast(t[0])},get:function(t){for(var n in this.queries)if(this.queries.hasOwnProperty(n)){var e=this.queries[n];if(t===e.name)return e.value}return null},_getCurrentSize:function(){for(var t,n=0;n<this.queries.length;n++){var e=this.queries[n];a(e.value).matches&&(t=e)}return"object"==typeof t?t.name:t},_watcher:function(){var t=this;o()(window).off("resize.zf.mediaquery").on("resize.zf.mediaquery",function(){var n=t._getCurrentSize(),e=t.current;n!==e&&(t.current=n,o()(window).trigger("changed.zf.mediaquery",[n,e]))})}}},function(t,n,e){t.exports=e(2)}]);;
!function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=103)}({0:function(e,t){e.exports=jQuery},1:function(e,t){e.exports={Foundation:window.Foundation}},103:function(e,t,n){e.exports=n(37)},37:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=(n.n(r),n(67));r.Foundation.MediaQuery=i.a,r.Foundation.MediaQuery._init()},67:function(e,t,n){"use strict";function r(e){var t={};return"string"!=typeof e?t:(e=e.trim().slice(1,-1))?t=e.split("&").reduce(function(e,t){var n=t.replace(/\+/g," ").split("="),r=n[0],i=n[1];return r=decodeURIComponent(r),i=void 0===i?null:decodeURIComponent(i),e.hasOwnProperty(r)?Array.isArray(e[r])?e[r].push(i):e[r]=[e[r],i]:e[r]=i,e},{}):t}n.d(t,"a",function(){return a});var i=n(0),u=n.n(i),o=window.matchMedia||function(){var e=window.styleMedia||window.media;if(!e){var t=document.createElement("style"),n=document.getElementsByTagName("script")[0],r=null;t.type="text/css",t.id="matchmediajs-test",n&&n.parentNode&&n.parentNode.insertBefore(t,n),r="getComputedStyle"in window&&window.getComputedStyle(t,null)||t.currentStyle,e={matchMedium:function(e){var n="@media "+e+"{ #matchmediajs-test { width: 1px; } }";return t.styleSheet?t.styleSheet.cssText=n:t.textContent=n,"1px"===r.width}}}return function(t){return{matches:e.matchMedium(t||"all"),media:t||"all"}}}(),a={queries:[],current:"",_init:function(){var e=this;u()("meta.foundation-mq").length||u()('<meta class="foundation-mq">').appendTo(document.head);var t,n=u()(".foundation-mq").css("font-family");t=r(n);for(var i in t)t.hasOwnProperty(i)&&e.queries.push({name:i,value:"only screen and (min-width: "+t[i]+")"});this.current=this._getCurrentSize(),this._watcher()},atLeast:function(e){var t=this.get(e);return!!t&&o(t).matches},is:function(e){return e=e.trim().split(" "),e.length>1&&"only"===e[1]?e[0]===this._getCurrentSize():this.atLeast(e[0])},get:function(e){for(var t in this.queries)if(this.queries.hasOwnProperty(t)){var n=this.queries[t];if(e===n.name)return n.value}return null},_getCurrentSize:function(){for(var e,t=0;t<this.queries.length;t++){var n=this.queries[t];o(n.value).matches&&(e=n)}return"object"==typeof e?e.name:e},_watcher:function(){var e=this;u()(window).off("resize.zf.mediaquery").on("resize.zf.mediaquery",function(){var t=e._getCurrentSize(),n=e.current;t!==n&&(e.current=t,u()(window).trigger("changed.zf.mediaquery",[t,n]))})}}}});;
!function(n){function t(o){if(e[o])return e[o].exports;var r=e[o]={i:o,l:!1,exports:{}};return n[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var e={};t.m=n,t.c=e,t.i=function(n){return n},t.d=function(n,e,o){t.o(n,e)||Object.defineProperty(n,e,{configurable:!1,enumerable:!0,get:o})},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},t.p="",t(t.s=102)}({0:function(n,t){n.exports=jQuery},1:function(n,t){n.exports={Foundation:window.Foundation}},102:function(n,t,e){n.exports=e(36)},3:function(n,t){n.exports={rtl:window.Foundation.rtl,GetYoDigits:window.Foundation.GetYoDigits,transitionend:window.Foundation.transitionend}},36:function(n,t,e){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=e(1),r=(e.n(o),e(66));o.Foundation.Keyboard=r.a},66:function(n,t,e){"use strict";function o(n){return!!n&&n.find("a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]").filter(function(){return!(!a()(this).is(":visible")||a()(this).attr("tabindex")<0)})}function r(n){var t=d[n.which||n.keyCode]||String.fromCharCode(n.which).toUpperCase();return t=t.replace(/\W+/,""),n.shiftKey&&(t="SHIFT_"+t),n.ctrlKey&&(t="CTRL_"+t),n.altKey&&(t="ALT_"+t),t=t.replace(/_$/,"")}e.d(t,"a",function(){return c});var i=e(0),a=e.n(i),u=e(3),d=(e.n(u),{9:"TAB",13:"ENTER",27:"ESCAPE",32:"SPACE",35:"END",36:"HOME",37:"ARROW_LEFT",38:"ARROW_UP",39:"ARROW_RIGHT",40:"ARROW_DOWN"}),f={},c={keys:function(n){var t={};for(var e in n)t[n[e]]=n[e];return t}(d),parseKey:r,handleKey:function(n,t,o){var r,i,d,c=f[t],s=this.parseKey(n);if(!c)return console.warn("Component not defined!");if(r=void 0===c.ltr?c:e.i(u.rtl)()?a.a.extend({},c.ltr,c.rtl):a.a.extend({},c.rtl,c.ltr),i=r[s],(d=o[i])&&"function"==typeof d){var l=d.apply();(o.handled||"function"==typeof o.handled)&&o.handled(l)}else(o.unhandled||"function"==typeof o.unhandled)&&o.unhandled()},findFocusable:o,register:function(n,t){f[n]=t},trapFocus:function(n){var t=o(n),e=t.eq(0),i=t.eq(-1);n.on("keydown.zf.trapfocus",function(n){n.target===i[0]&&"TAB"===r(n)?(n.preventDefault(),e.focus()):n.target===e[0]&&"SHIFT_TAB"===r(n)&&(n.preventDefault(),i.focus())})},releaseFocus:function(n){n.off("keydown.zf.trapfocus")}}}});;
!function(t){function e(i){if(o[i])return o[i].exports;var n=o[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var o={};e.m=t,e.c=o,e.i=function(t){return t},e.d=function(t,o,i){e.o(t,o)||Object.defineProperty(t,o,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var o=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(o,"a",o),o},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=100)}({1:function(t,e){t.exports={Foundation:window.Foundation}},100:function(t,e,o){t.exports=o(34)},3:function(t,e){t.exports={rtl:window.Foundation.rtl,GetYoDigits:window.Foundation.GetYoDigits,transitionend:window.Foundation.transitionend}},34:function(t,e,o){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=o(1),n=(o.n(i),o(64));i.Foundation.Box=n.a},64:function(t,e,o){"use strict";function i(t,e,o,i,f){return 0===n(t,e,o,i,f)}function n(t,e,o,i,n){var s,r,h,a,c=f(t);if(e){var l=f(e);r=l.height+l.offset.top-(c.offset.top+c.height),s=c.offset.top-l.offset.top,h=c.offset.left-l.offset.left,a=l.width+l.offset.left-(c.offset.left+c.width)}else r=c.windowDims.height+c.windowDims.offset.top-(c.offset.top+c.height),s=c.offset.top-c.windowDims.offset.top,h=c.offset.left-c.windowDims.offset.left,a=c.windowDims.width-(c.offset.left+c.width);return r=n?0:Math.min(r,0),s=Math.min(s,0),h=Math.min(h,0),a=Math.min(a,0),o?h+a:i?s+r:Math.sqrt(s*s+r*r+h*h+a*a)}function f(t){if((t=t.length?t[0]:t)===window||t===document)throw new Error("I'm sorry, Dave. I'm afraid I can't do that.");var e=t.getBoundingClientRect(),o=t.parentNode.getBoundingClientRect(),i=document.body.getBoundingClientRect(),n=window.pageYOffset,f=window.pageXOffset;return{width:e.width,height:e.height,offset:{top:e.top+n,left:e.left+f},parentDims:{width:o.width,height:o.height,offset:{top:o.top+n,left:o.left+f}},windowDims:{width:i.width,height:i.height,offset:{top:n,left:f}}}}function s(t,e,i,n,f,s){switch(console.log("NOTE: GetOffsets is deprecated in favor of GetExplicitOffsets and will be removed in 6.5"),i){case"top":return o.i(h.rtl)()?r(t,e,"top","left",n,f,s):r(t,e,"top","right",n,f,s);case"bottom":return o.i(h.rtl)()?r(t,e,"bottom","left",n,f,s):r(t,e,"bottom","right",n,f,s);case"center top":return r(t,e,"top","center",n,f,s);case"center bottom":return r(t,e,"bottom","center",n,f,s);case"center left":return r(t,e,"left","center",n,f,s);case"center right":return r(t,e,"right","center",n,f,s);case"left bottom":return r(t,e,"bottom","left",n,f,s);case"right bottom":return r(t,e,"bottom","right",n,f,s);case"center":return{left:$eleDims.windowDims.offset.left+$eleDims.windowDims.width/2-$eleDims.width/2+f,top:$eleDims.windowDims.offset.top+$eleDims.windowDims.height/2-($eleDims.height/2+n)};case"reveal":return{left:($eleDims.windowDims.width-$eleDims.width)/2+f,top:$eleDims.windowDims.offset.top+n};case"reveal full":return{left:$eleDims.windowDims.offset.left,top:$eleDims.windowDims.offset.top};default:return{left:o.i(h.rtl)()?$anchorDims.offset.left-$eleDims.width+$anchorDims.width-f:$anchorDims.offset.left+f,top:$anchorDims.offset.top+$anchorDims.height+n}}}function r(t,e,o,i,n,s,r){var h,a,c=f(t),l=e?f(e):null;switch(o){case"top":h=l.offset.top-(c.height+n);break;case"bottom":h=l.offset.top+l.height+n;break;case"left":a=l.offset.left-(c.width+s);break;case"right":a=l.offset.left+l.width+s}switch(o){case"top":case"bottom":switch(i){case"left":a=l.offset.left+s;break;case"right":a=l.offset.left-c.width+l.width-s;break;case"center":a=r?s:l.offset.left+l.width/2-c.width/2+s}break;case"right":case"left":switch(i){case"bottom":h=l.offset.top-n+l.height-c.height;break;case"top":h=l.offset.top+n;break;case"center":h=l.offset.top+n+l.height/2-c.height/2}}return{top:h,left:a}}o.d(e,"a",function(){return a});var h=o(3),a=(o.n(h),{ImNotTouchingYou:i,OverlapArea:n,GetDimensions:f,GetOffsets:s,GetExplicitOffsets:r})}});;
!function(n){function e(r){if(t[r])return t[r].exports;var u=t[r]={i:r,l:!1,exports:{}};return n[r].call(u.exports,u,u.exports,e),u.l=!0,u.exports}var t={};e.m=n,e.c=t,e.i=function(n){return n},e.d=function(n,t,r){e.o(n,t)||Object.defineProperty(n,t,{configurable:!1,enumerable:!0,get:r})},e.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return e.d(t,"a",t),t},e.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},e.p="",e(e.s=105)}({0:function(n,e){n.exports=jQuery},1:function(n,e){n.exports={Foundation:window.Foundation}},105:function(n,e,t){n.exports=t(39)},39:function(n,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=t(1),u=(t.n(r),t(69));r.Foundation.Nest=u.a},69:function(n,e,t){"use strict";t.d(e,"a",function(){return a});var r=t(0),u=t.n(r),a={Feather:function(n){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"zf";n.attr("role","menubar");var t=n.find("li").attr({role:"menuitem"}),r="is-"+e+"-submenu",a=r+"-item",i="is-"+e+"-submenu-parent",o="accordion"!==e;t.each(function(){var n=u()(this),t=n.children("ul");t.length&&(n.addClass(i),t.addClass("submenu "+r).attr({"data-submenu":""}),o&&(n.attr({"aria-haspopup":!0,"aria-label":n.children("a:first").text()}),"drilldown"===e&&n.attr({"aria-expanded":!1})),t.addClass("submenu "+r).attr({"data-submenu":"",role:"menu"}),"drilldown"===e&&t.attr({"aria-hidden":!0})),n.parent("[data-submenu]").length&&n.addClass("is-submenu-item "+a)})},Burn:function(n,e){var t="is-"+e+"-submenu",r=t+"-item",u="is-"+e+"-submenu-parent";n.find(">li, .menu, .menu > li").removeClass(t+" "+r+" "+u+" is-submenu-item submenu is-active").removeAttr("data-submenu").css("display","")}}}});;
!function(e){function n(o){if(t[o])return t[o].exports;var i=t[o]={i:o,l:!1,exports:{}};return e[o].call(i.exports,i,i.exports,n),i.l=!0,i.exports}var t={};n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,o){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:o})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},n.p="",n(n.s=84)}({0:function(e,n){e.exports=jQuery},1:function(e,n){e.exports={Foundation:window.Foundation}},18:function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var o=t(1),i=(t.n(o),t(48));o.Foundation.plugin(i.a,"DropdownMenu")},2:function(e,n){e.exports={Plugin:window.Foundation.Plugin}},3:function(e,n){e.exports={rtl:window.Foundation.rtl,GetYoDigits:window.Foundation.GetYoDigits,transitionend:window.Foundation.transitionend}},48:function(e,n,t){"use strict";function o(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function i(e,n){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!n||"object"!=typeof n&&"function"!=typeof n?e:n}function s(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function, not "+typeof n);e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),n&&(Object.setPrototypeOf?Object.setPrototypeOf(e,n):e.__proto__=n)}t.d(n,"a",function(){return h});var r=t(0),a=t.n(r),u=t(5),d=(t.n(u),t(9)),l=(t.n(d),t(8)),p=(t.n(l),t(3)),c=(t.n(p),t(2)),f=(t.n(c),function(){function e(e,n){for(var t=0;t<n.length;t++){var o=n[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(n,t,o){return t&&e(n.prototype,t),o&&e(n,o),n}}()),h=function(e){function n(){return o(this,n),i(this,(n.__proto__||Object.getPrototypeOf(n)).apply(this,arguments))}return s(n,e),f(n,[{key:"_setup",value:function(e,t){this.$element=e,this.options=a.a.extend({},n.defaults,this.$element.data(),t),this.className="DropdownMenu",this._init(),u.Keyboard.register("DropdownMenu",{ENTER:"open",SPACE:"open",ARROW_RIGHT:"next",ARROW_UP:"up",ARROW_DOWN:"down",ARROW_LEFT:"previous",ESCAPE:"close"})}},{key:"_init",value:function(){d.Nest.Feather(this.$element,"dropdown");var e=this.$element.find("li.is-dropdown-submenu-parent");this.$element.children(".is-dropdown-submenu-parent").children(".is-dropdown-submenu").addClass("first-sub"),this.$menuItems=this.$element.find('[role="menuitem"]'),this.$tabs=this.$element.children('[role="menuitem"]'),this.$tabs.find("ul.is-dropdown-submenu").addClass(this.options.verticalClass),"auto"===this.options.alignment?this.$element.hasClass(this.options.rightClass)||t.i(p.rtl)()||this.$element.parents(".top-bar-right").is("*")?(this.options.alignment="right",e.addClass("opens-left")):(this.options.alignment="left",e.addClass("opens-right")):"right"===this.options.alignment?e.addClass("opens-left"):e.addClass("opens-right"),this.changed=!1,this._events()}},{key:"_isVertical",value:function(){return"block"===this.$tabs.css("display")||"column"===this.$element.css("flex-direction")}},{key:"_isRtl",value:function(){return this.$element.hasClass("align-right")||t.i(p.rtl)()&&!this.$element.hasClass("align-left")}},{key:"_events",value:function(){var e=this,n="ontouchstart"in window||void 0!==window.ontouchstart,t="is-dropdown-submenu-parent",o=function(o){var i=a()(o.target).parentsUntil("ul","."+t),s=i.hasClass(t),r="true"===i.attr("data-is-click"),u=i.children(".is-dropdown-submenu");if(s)if(r){if(!e.options.closeOnClick||!e.options.clickOpen&&!n||e.options.forceFollow&&n)return;o.stopImmediatePropagation(),o.preventDefault(),e._hide(i)}else o.preventDefault(),o.stopImmediatePropagation(),e._show(u),i.add(i.parentsUntil(e.$element,"."+t)).attr("data-is-click",!0)};(this.options.clickOpen||n)&&this.$menuItems.on("click.zf.dropdownmenu touchstart.zf.dropdownmenu",o),e.options.closeOnClickInside&&this.$menuItems.on("click.zf.dropdownmenu",function(n){a()(this).hasClass(t)||e._hide()}),this.options.disableHover||this.$menuItems.on("mouseenter.zf.dropdownmenu",function(n){var o=a()(this);o.hasClass(t)&&(clearTimeout(o.data("_delay")),o.data("_delay",setTimeout(function(){e._show(o.children(".is-dropdown-submenu"))},e.options.hoverDelay)))}).on("mouseleave.zf.dropdownmenu",function(n){var o=a()(this);if(o.hasClass(t)&&e.options.autoclose){if("true"===o.attr("data-is-click")&&e.options.clickOpen)return!1;clearTimeout(o.data("_delay")),o.data("_delay",setTimeout(function(){e._hide(o)},e.options.closingTime))}}),this.$menuItems.on("keydown.zf.dropdownmenu",function(n){var t,o,i=a()(n.target).parentsUntil("ul",'[role="menuitem"]'),s=e.$tabs.index(i)>-1,r=s?e.$tabs:i.siblings("li").add(i);r.each(function(e){if(a()(this).is(i))return t=r.eq(e-1),void(o=r.eq(e+1))});var d=function(){o.children("a:first").focus(),n.preventDefault()},l=function(){t.children("a:first").focus(),n.preventDefault()},p=function(){var t=i.children("ul.is-dropdown-submenu");t.length&&(e._show(t),i.find("li > a:first").focus(),n.preventDefault())},c=function(){var t=i.parent("ul").parent("li");t.children("a:first").focus(),e._hide(t),n.preventDefault()},f={open:p,close:function(){e._hide(e.$element),e.$menuItems.eq(0).children("a").focus(),n.preventDefault()},handled:function(){n.stopImmediatePropagation()}};s?e._isVertical()?e._isRtl()?a.a.extend(f,{down:d,up:l,next:c,previous:p}):a.a.extend(f,{down:d,up:l,next:p,previous:c}):e._isRtl()?a.a.extend(f,{next:l,previous:d,down:p,up:c}):a.a.extend(f,{next:d,previous:l,down:p,up:c}):e._isRtl()?a.a.extend(f,{next:c,previous:p,down:d,up:l}):a.a.extend(f,{next:p,previous:c,down:d,up:l}),u.Keyboard.handleKey(n,"DropdownMenu",f)})}},{key:"_addBodyHandler",value:function(){var e=a()(document.body),n=this;e.off("mouseup.zf.dropdownmenu touchend.zf.dropdownmenu").on("mouseup.zf.dropdownmenu touchend.zf.dropdownmenu",function(t){n.$element.find(t.target).length||(n._hide(),e.off("mouseup.zf.dropdownmenu touchend.zf.dropdownmenu"))})}},{key:"_show",value:function(e){var n=this.$tabs.index(this.$tabs.filter(function(n,t){return a()(t).find(e).length>0})),t=e.parent("li.is-dropdown-submenu-parent").siblings("li.is-dropdown-submenu-parent");this._hide(t,n),e.css("visibility","hidden").addClass("js-dropdown-active").parent("li.is-dropdown-submenu-parent").addClass("is-active");var o=l.Box.ImNotTouchingYou(e,null,!0);if(!o){var i="left"===this.options.alignment?"-right":"-left",s=e.parent(".is-dropdown-submenu-parent");s.removeClass("opens"+i).addClass("opens-"+this.options.alignment),o=l.Box.ImNotTouchingYou(e,null,!0),o||s.removeClass("opens-"+this.options.alignment).addClass("opens-inner"),this.changed=!0}e.css("visibility",""),this.options.closeOnClick&&this._addBodyHandler(),this.$element.trigger("show.zf.dropdownmenu",[e])}},{key:"_hide",value:function(e,n){var t;if(t=e&&e.length?e:void 0!==n?this.$tabs.not(function(e,t){return e===n}):this.$element,t.hasClass("is-active")||t.find(".is-active").length>0){if(t.find("li.is-active").add(t).attr({"data-is-click":!1}).removeClass("is-active"),t.find("ul.js-dropdown-active").removeClass("js-dropdown-active"),this.changed||t.find("opens-inner").length){var o="left"===this.options.alignment?"right":"left";t.find("li.is-dropdown-submenu-parent").add(t).removeClass("opens-inner opens-"+this.options.alignment).addClass("opens-"+o),this.changed=!1}this.$element.trigger("hide.zf.dropdownmenu",[t])}}},{key:"_destroy",value:function(){this.$menuItems.off(".zf.dropdownmenu").removeAttr("data-is-click").removeClass("is-right-arrow is-left-arrow is-down-arrow opens-right opens-left opens-inner"),a()(document.body).off(".zf.dropdownmenu"),d.Nest.Burn(this.$element,"dropdown")}}]),n}(c.Plugin);h.defaults={disableHover:!1,autoclose:!0,hoverDelay:50,clickOpen:!1,closingTime:500,alignment:"auto",closeOnClick:!0,closeOnClickInside:!0,verticalClass:"vertical",rightClass:"align-right",forceFollow:!0}},5:function(e,n){e.exports={Keyboard:window.Foundation.Keyboard}},8:function(e,n){e.exports={Box:window.Foundation.Box}},84:function(e,n,t){e.exports=t(18)},9:function(e,n){e.exports={Nest:window.Foundation.Nest}}});;
!function(t){function e(n){if(i[n])return i[n].exports;var s=i[n]={i:n,l:!1,exports:{}};return t[n].call(s.exports,s,s.exports,e),s.l=!0,s.exports}var i={};e.m=t,e.c=i,e.i=function(t){return t},e.d=function(t,i,n){e.o(t,i)||Object.defineProperty(t,i,{configurable:!1,enumerable:!0,get:n})},e.n=function(t){var i=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(i,"a",i),i},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=88)}({0:function(t,e){t.exports=jQuery},1:function(t,e){t.exports={Foundation:window.Foundation}},2:function(t,e){t.exports={Plugin:window.Foundation.Plugin}},22:function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),s=(i.n(n),i(52));n.Foundation.plugin(s.a,"OffCanvas")},3:function(t,e){t.exports={rtl:window.Foundation.rtl,GetYoDigits:window.Foundation.GetYoDigits,transitionend:window.Foundation.transitionend}},4:function(t,e){t.exports={Motion:window.Foundation.Motion,Move:window.Foundation.Move}},5:function(t,e){t.exports={Keyboard:window.Foundation.Keyboard}},52:function(t,e,i){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}i.d(e,"a",function(){return g});var a=i(0),r=i.n(a),l=i(5),c=(i.n(l),i(6)),d=(i.n(c),i(3)),f=(i.n(d),i(2)),u=(i.n(f),i(7)),h=function(){function t(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,i,n){return i&&t(e.prototype,i),n&&t(e,n),e}}(),g=function(t){function e(){return n(this,e),s(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return o(e,t),h(e,[{key:"_setup",value:function(t,i){var n=this;this.className="OffCanvas",this.$element=t,this.options=r.a.extend({},e.defaults,this.$element.data(),i),this.contentClasses={base:[],reveal:[]},this.$lastTrigger=r()(),this.$triggers=r()(),this.position="left",this.$content=r()(),this.nested=!!this.options.nested,r()(["push","overlap"]).each(function(t,e){n.contentClasses.base.push("has-transition-"+e)}),r()(["left","right","top","bottom"]).each(function(t,e){n.contentClasses.base.push("has-position-"+e),n.contentClasses.reveal.push("has-reveal-"+e)}),u.a.init(r.a),c.MediaQuery._init(),this._init(),this._events(),l.Keyboard.register("OffCanvas",{ESCAPE:"close"})}},{key:"_init",value:function(){var t=this.$element.attr("id");if(this.$element.attr("aria-hidden","true"),this.options.contentId?this.$content=r()("#"+this.options.contentId):this.$element.siblings("[data-off-canvas-content]").length?this.$content=this.$element.siblings("[data-off-canvas-content]").first():this.$content=this.$element.closest("[data-off-canvas-content]").first(),this.options.contentId?this.options.contentId&&null===this.options.nested&&console.warn("Remember to use the nested option if using the content ID option!"):this.nested=0===this.$element.siblings("[data-off-canvas-content]").length,!0===this.nested&&(this.options.transition="overlap",this.$element.removeClass("is-transition-push")),this.$element.addClass("is-transition-"+this.options.transition+" is-closed"),this.$triggers=r()(document).find('[data-open="'+t+'"], [data-close="'+t+'"], [data-toggle="'+t+'"]').attr("aria-expanded","false").attr("aria-controls",t),this.position=this.$element.is(".position-left, .position-top, .position-right, .position-bottom")?this.$element.attr("class").match(/position\-(left|top|right|bottom)/)[1]:this.position,!0===this.options.contentOverlay){var e=document.createElement("div"),i="fixed"===r()(this.$element).css("position")?"is-overlay-fixed":"is-overlay-absolute";e.setAttribute("class","js-off-canvas-overlay "+i),this.$overlay=r()(e),"is-overlay-fixed"===i?r()(this.$overlay).insertAfter(this.$element):this.$content.append(this.$overlay)}this.options.isRevealed=this.options.isRevealed||new RegExp(this.options.revealClass,"g").test(this.$element[0].className),!0===this.options.isRevealed&&(this.options.revealOn=this.options.revealOn||this.$element[0].className.match(/(reveal-for-medium|reveal-for-large)/g)[0].split("-")[2],this._setMQChecker()),this.options.transitionTime&&this.$element.css("transition-duration",this.options.transitionTime),this._removeContentClasses()}},{key:"_events",value:function(){if(this.$element.off(".zf.trigger .zf.offcanvas").on({"open.zf.trigger":this.open.bind(this),"close.zf.trigger":this.close.bind(this),"toggle.zf.trigger":this.toggle.bind(this),"keydown.zf.offcanvas":this._handleKeyboard.bind(this)}),!0===this.options.closeOnClick){(this.options.contentOverlay?this.$overlay:this.$content).on({"click.zf.offcanvas":this.close.bind(this)})}}},{key:"_setMQChecker",value:function(){var t=this;r()(window).on("changed.zf.mediaquery",function(){c.MediaQuery.atLeast(t.options.revealOn)?t.reveal(!0):t.reveal(!1)}).one("load.zf.offcanvas",function(){c.MediaQuery.atLeast(t.options.revealOn)&&t.reveal(!0)})}},{key:"_removeContentClasses",value:function(t){"boolean"!=typeof t?this.$content.removeClass(this.contentClasses.base.join(" ")):!1===t&&this.$content.removeClass("has-reveal-"+this.position)}},{key:"_addContentClasses",value:function(t){this._removeContentClasses(t),"boolean"!=typeof t?this.$content.addClass("has-transition-"+this.options.transition+" has-position-"+this.position):!0===t&&this.$content.addClass("has-reveal-"+this.position)}},{key:"reveal",value:function(t){t?(this.close(),this.isRevealed=!0,this.$element.attr("aria-hidden","false"),this.$element.off("open.zf.trigger toggle.zf.trigger"),this.$element.removeClass("is-closed")):(this.isRevealed=!1,this.$element.attr("aria-hidden","true"),this.$element.off("open.zf.trigger toggle.zf.trigger").on({"open.zf.trigger":this.open.bind(this),"toggle.zf.trigger":this.toggle.bind(this)}),this.$element.addClass("is-closed")),this._addContentClasses(t)}},{key:"_stopScrolling",value:function(t){return!1}},{key:"_recordScrollable",value:function(t){var e=this;e.scrollHeight!==e.clientHeight&&(0===e.scrollTop&&(e.scrollTop=1),e.scrollTop===e.scrollHeight-e.clientHeight&&(e.scrollTop=e.scrollHeight-e.clientHeight-1)),e.allowUp=e.scrollTop>0,e.allowDown=e.scrollTop<e.scrollHeight-e.clientHeight,e.lastY=t.originalEvent.pageY}},{key:"_stopScrollPropagation",value:function(t){var e=this,i=t.pageY<e.lastY,n=!i;e.lastY=t.pageY,i&&e.allowUp||n&&e.allowDown?t.stopPropagation():t.preventDefault()}},{key:"open",value:function(t,e){if(!this.$element.hasClass("is-open")&&!this.isRevealed){var n=this;e&&(this.$lastTrigger=e),"top"===this.options.forceTo?window.scrollTo(0,0):"bottom"===this.options.forceTo&&window.scrollTo(0,document.body.scrollHeight),this.options.transitionTime&&"overlap"!==this.options.transition?this.$element.siblings("[data-off-canvas-content]").css("transition-duration",this.options.transitionTime):this.$element.siblings("[data-off-canvas-content]").css("transition-duration",""),this.$element.addClass("is-open").removeClass("is-closed"),this.$triggers.attr("aria-expanded","true"),this.$element.attr("aria-hidden","false").trigger("opened.zf.offcanvas"),this.$content.addClass("is-open-"+this.position),!1===this.options.contentScroll&&(r()("body").addClass("is-off-canvas-open").on("touchmove",this._stopScrolling),this.$element.on("touchstart",this._recordScrollable),this.$element.on("touchmove",this._stopScrollPropagation)),!0===this.options.contentOverlay&&this.$overlay.addClass("is-visible"),!0===this.options.closeOnClick&&!0===this.options.contentOverlay&&this.$overlay.addClass("is-closable"),!0===this.options.autoFocus&&this.$element.one(i.i(d.transitionend)(this.$element),function(){if(n.$element.hasClass("is-open")){var t=n.$element.find("[data-autofocus]");t.length?t.eq(0).focus():n.$element.find("a, button").eq(0).focus()}}),!0===this.options.trapFocus&&(this.$content.attr("tabindex","-1"),l.Keyboard.trapFocus(this.$element)),this._addContentClasses()}}},{key:"close",value:function(t){if(this.$element.hasClass("is-open")&&!this.isRevealed){var e=this;this.$element.removeClass("is-open"),this.$element.attr("aria-hidden","true").trigger("closed.zf.offcanvas"),this.$content.removeClass("is-open-left is-open-top is-open-right is-open-bottom"),!1===this.options.contentScroll&&(r()("body").removeClass("is-off-canvas-open").off("touchmove",this._stopScrolling),this.$element.off("touchstart",this._recordScrollable),this.$element.off("touchmove",this._stopScrollPropagation)),!0===this.options.contentOverlay&&this.$overlay.removeClass("is-visible"),!0===this.options.closeOnClick&&!0===this.options.contentOverlay&&this.$overlay.removeClass("is-closable"),this.$triggers.attr("aria-expanded","false"),!0===this.options.trapFocus&&(this.$content.removeAttr("tabindex"),l.Keyboard.releaseFocus(this.$element)),this.$element.one(i.i(d.transitionend)(this.$element),function(t){e.$element.addClass("is-closed"),e._removeContentClasses()})}}},{key:"toggle",value:function(t,e){this.$element.hasClass("is-open")?this.close(t,e):this.open(t,e)}},{key:"_handleKeyboard",value:function(t){var e=this;l.Keyboard.handleKey(t,"OffCanvas",{close:function(){return e.close(),e.$lastTrigger.focus(),!0},handled:function(){t.stopPropagation(),t.preventDefault()}})}},{key:"_destroy",value:function(){this.close(),this.$element.off(".zf.trigger .zf.offcanvas"),this.$overlay.off(".zf.offcanvas")}}]),e}(f.Plugin);g.defaults={closeOnClick:!0,contentOverlay:!0,contentId:null,nested:null,contentScroll:!0,transitionTime:null,transition:"push",forceTo:null,isRevealed:!1,revealOn:null,autoFocus:!0,revealClass:"reveal-for-",trapFocus:!1}},6:function(t,e){t.exports={MediaQuery:window.Foundation.MediaQuery}},7:function(t,e,i){"use strict";function n(t,e,i){var n=void 0,s=Array.prototype.slice.call(arguments,3);o()(window).off(e).on(e,function(e){n&&clearTimeout(n),n=setTimeout(function(){i.apply(null,s)},t||10)})}i.d(e,"a",function(){return c});var s=i(0),o=i.n(s),a=i(4),r=(i.n(a),function(){for(var t=["WebKit","Moz","O","Ms",""],e=0;e<t.length;e++)if(t[e]+"MutationObserver"in window)return window[t[e]+"MutationObserver"];return!1}()),l=function(t,e){t.data(e).split(" ").forEach(function(i){o()("#"+i)["close"===e?"trigger":"triggerHandler"](e+".zf.trigger",[t])})},c={Listeners:{Basic:{},Global:{}},Initializers:{}};c.Listeners.Basic={openListener:function(){l(o()(this),"open")},closeListener:function(){o()(this).data("close")?l(o()(this),"close"):o()(this).trigger("close.zf.trigger")},toggleListener:function(){o()(this).data("toggle")?l(o()(this),"toggle"):o()(this).trigger("toggle.zf.trigger")},closeableListener:function(t){t.stopPropagation();var e=o()(this).data("closable");""!==e?a.Motion.animateOut(o()(this),e,function(){o()(this).trigger("closed.zf")}):o()(this).fadeOut().trigger("closed.zf")},toggleFocusListener:function(){var t=o()(this).data("toggle-focus");o()("#"+t).triggerHandler("toggle.zf.trigger",[o()(this)])}},c.Initializers.addOpenListener=function(t){t.off("click.zf.trigger",c.Listeners.Basic.openListener),t.on("click.zf.trigger","[data-open]",c.Listeners.Basic.openListener)},c.Initializers.addCloseListener=function(t){t.off("click.zf.trigger",c.Listeners.Basic.closeListener),t.on("click.zf.trigger","[data-close]",c.Listeners.Basic.closeListener)},c.Initializers.addToggleListener=function(t){t.off("click.zf.trigger",c.Listeners.Basic.toggleListener),t.on("click.zf.trigger","[data-toggle]",c.Listeners.Basic.toggleListener)},c.Initializers.addCloseableListener=function(t){t.off("close.zf.trigger",c.Listeners.Basic.closeableListener),t.on("close.zf.trigger","[data-closeable], [data-closable]",c.Listeners.Basic.closeableListener)},c.Initializers.addToggleFocusListener=function(t){t.off("focus.zf.trigger blur.zf.trigger",c.Listeners.Basic.toggleFocusListener),t.on("focus.zf.trigger blur.zf.trigger","[data-toggle-focus]",c.Listeners.Basic.toggleFocusListener)},c.Listeners.Global={resizeListener:function(t){r||t.each(function(){o()(this).triggerHandler("resizeme.zf.trigger")}),t.attr("data-events","resize")},scrollListener:function(t){r||t.each(function(){o()(this).triggerHandler("scrollme.zf.trigger")}),t.attr("data-events","scroll")},closeMeListener:function(t,e){var i=t.namespace.split(".")[0];o()("[data-"+i+"]").not('[data-yeti-box="'+e+'"]').each(function(){var t=o()(this);t.triggerHandler("close.zf.trigger",[t])})}},c.Initializers.addClosemeListener=function(t){var e=o()("[data-yeti-box]"),i=["dropdown","tooltip","reveal"];if(t&&("string"==typeof t?i.push(t):"object"==typeof t&&"string"==typeof t[0]?i.concat(t):console.error("Plugin names must be strings")),e.length){var n=i.map(function(t){return"closeme.zf."+t}).join(" ");o()(window).off(n).on(n,c.Listeners.Global.closeMeListener)}},c.Initializers.addResizeListener=function(t){var e=o()("[data-resize]");e.length&&n(t,"resize.zf.trigger",c.Listeners.Global.resizeListener,e)},c.Initializers.addScrollListener=function(t){var e=o()("[data-scroll]");e.length&&n(t,"scroll.zf.trigger",c.Listeners.Global.scrollListener,e)},c.Initializers.addMutationEventsListener=function(t){if(!r)return!1;var e=t.find("[data-resize], [data-scroll], [data-mutate]"),i=function(t){var e=o()(t[0].target);switch(t[0].type){case"attributes":"scroll"===e.attr("data-events")&&"data-events"===t[0].attributeName&&e.triggerHandler("scrollme.zf.trigger",[e,window.pageYOffset]),"resize"===e.attr("data-events")&&"data-events"===t[0].attributeName&&e.triggerHandler("resizeme.zf.trigger",[e]),"style"===t[0].attributeName&&(e.closest("[data-mutate]").attr("data-events","mutate"),e.closest("[data-mutate]").triggerHandler("mutateme.zf.trigger",[e.closest("[data-mutate]")]));break;case"childList":e.closest("[data-mutate]").attr("data-events","mutate"),e.closest("[data-mutate]").triggerHandler("mutateme.zf.trigger",[e.closest("[data-mutate]")]);break;default:return!1}};if(e.length)for(var n=0;n<=e.length-1;n++){var s=new r(i);s.observe(e[n],{attributes:!0,childList:!0,characterData:!1,subtree:!0,attributeFilter:["data-events","style"]})}},c.Initializers.addSimpleListeners=function(){var t=o()(document);c.Initializers.addOpenListener(t),c.Initializers.addCloseListener(t),c.Initializers.addToggleListener(t),c.Initializers.addCloseableListener(t),c.Initializers.addToggleFocusListener(t)},c.Initializers.addGlobalListeners=function(){var t=o()(document);c.Initializers.addMutationEventsListener(t),c.Initializers.addResizeListener(),c.Initializers.addScrollListener(),c.Initializers.addClosemeListener()},c.init=function(t,e){if(void 0===t.triggersInitialized){t(document);"complete"===document.readyState?(c.Initializers.addSimpleListeners(),c.Initializers.addGlobalListeners()):t(window).on("load",function(){c.Initializers.addSimpleListeners(),c.Initializers.addGlobalListeners()}),t.triggersInitialized=!0}e&&(e.Triggers=c,e.IHearYou=c.Initializers.addGlobalListeners)}},88:function(t,e,i){t.exports=i(22)}});;
!function(e){function t(n){if(i[n])return i[n].exports;var r=i[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var i={};t.m=e,t.c=i,t.i=function(e){return e},t.d=function(e,i,n){t.o(e,i)||Object.defineProperty(e,i,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var i=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(i,"a",i),i},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=98)}({0:function(e,t){e.exports=jQuery},1:function(e,t){e.exports={Foundation:window.Foundation}},2:function(e,t){e.exports={Plugin:window.Foundation.Plugin}},32:function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=i(1),r=(i.n(n),i(62));n.Foundation.plugin(r.a,"Toggler")},4:function(e,t){e.exports={Motion:window.Foundation.Motion,Move:window.Foundation.Move}},62:function(e,t,i){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}i.d(t,"a",function(){return f});var s=i(0),o=i.n(s),l=i(4),c=(i.n(l),i(2)),g=(i.n(c),i(7)),u=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}(),f=function(e){function t(){return n(this,t),r(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),u(t,[{key:"_setup",value:function(e,i){this.$element=e,this.options=o.a.extend({},t.defaults,e.data(),i),this.className="",this.className="Toggler",g.a.init(o.a),this._init(),this._events()}},{key:"_init",value:function(){var e;this.options.animate?(e=this.options.animate.split(" "),this.animationIn=e[0],this.animationOut=e[1]||null):(e=this.$element.data("toggler"),this.className="."===e[0]?e.slice(1):e);var t=this.$element[0].id;o()('[data-open="'+t+'"], [data-close="'+t+'"], [data-toggle="'+t+'"]').attr("aria-controls",t),this.$element.attr("aria-expanded",!this.$element.is(":hidden"))}},{key:"_events",value:function(){this.$element.off("toggle.zf.trigger").on("toggle.zf.trigger",this.toggle.bind(this))}},{key:"toggle",value:function(){this[this.options.animate?"_toggleAnimate":"_toggleClass"]()}},{key:"_toggleClass",value:function(){this.$element.toggleClass(this.className);var e=this.$element.hasClass(this.className);e?this.$element.trigger("on.zf.toggler"):this.$element.trigger("off.zf.toggler"),this._updateARIA(e),this.$element.find("[data-mutate]").trigger("mutateme.zf.trigger")}},{key:"_toggleAnimate",value:function(){var e=this;this.$element.is(":hidden")?l.Motion.animateIn(this.$element,this.animationIn,function(){e._updateARIA(!0),this.trigger("on.zf.toggler"),this.find("[data-mutate]").trigger("mutateme.zf.trigger")}):l.Motion.animateOut(this.$element,this.animationOut,function(){e._updateARIA(!1),this.trigger("off.zf.toggler"),this.find("[data-mutate]").trigger("mutateme.zf.trigger")})}},{key:"_updateARIA",value:function(e){this.$element.attr("aria-expanded",!!e)}},{key:"_destroy",value:function(){this.$element.off(".zf.toggler")}}]),t}(c.Plugin);f.defaults={animate:!1}},7:function(e,t,i){"use strict";function n(e,t,i){var n=void 0,r=Array.prototype.slice.call(arguments,3);a()(window).off(t).on(t,function(t){n&&clearTimeout(n),n=setTimeout(function(){i.apply(null,r)},e||10)})}i.d(t,"a",function(){return c});var r=i(0),a=i.n(r),s=i(4),o=(i.n(s),function(){for(var e=["WebKit","Moz","O","Ms",""],t=0;t<e.length;t++)if(e[t]+"MutationObserver"in window)return window[e[t]+"MutationObserver"];return!1}()),l=function(e,t){e.data(t).split(" ").forEach(function(i){a()("#"+i)["close"===t?"trigger":"triggerHandler"](t+".zf.trigger",[e])})},c={Listeners:{Basic:{},Global:{}},Initializers:{}};c.Listeners.Basic={openListener:function(){l(a()(this),"open")},closeListener:function(){a()(this).data("close")?l(a()(this),"close"):a()(this).trigger("close.zf.trigger")},toggleListener:function(){a()(this).data("toggle")?l(a()(this),"toggle"):a()(this).trigger("toggle.zf.trigger")},closeableListener:function(e){e.stopPropagation();var t=a()(this).data("closable");""!==t?s.Motion.animateOut(a()(this),t,function(){a()(this).trigger("closed.zf")}):a()(this).fadeOut().trigger("closed.zf")},toggleFocusListener:function(){var e=a()(this).data("toggle-focus");a()("#"+e).triggerHandler("toggle.zf.trigger",[a()(this)])}},c.Initializers.addOpenListener=function(e){e.off("click.zf.trigger",c.Listeners.Basic.openListener),e.on("click.zf.trigger","[data-open]",c.Listeners.Basic.openListener)},c.Initializers.addCloseListener=function(e){e.off("click.zf.trigger",c.Listeners.Basic.closeListener),e.on("click.zf.trigger","[data-close]",c.Listeners.Basic.closeListener)},c.Initializers.addToggleListener=function(e){e.off("click.zf.trigger",c.Listeners.Basic.toggleListener),e.on("click.zf.trigger","[data-toggle]",c.Listeners.Basic.toggleListener)},c.Initializers.addCloseableListener=function(e){e.off("close.zf.trigger",c.Listeners.Basic.closeableListener),e.on("close.zf.trigger","[data-closeable], [data-closable]",c.Listeners.Basic.closeableListener)},c.Initializers.addToggleFocusListener=function(e){e.off("focus.zf.trigger blur.zf.trigger",c.Listeners.Basic.toggleFocusListener),e.on("focus.zf.trigger blur.zf.trigger","[data-toggle-focus]",c.Listeners.Basic.toggleFocusListener)},c.Listeners.Global={resizeListener:function(e){o||e.each(function(){a()(this).triggerHandler("resizeme.zf.trigger")}),e.attr("data-events","resize")},scrollListener:function(e){o||e.each(function(){a()(this).triggerHandler("scrollme.zf.trigger")}),e.attr("data-events","scroll")},closeMeListener:function(e,t){var i=e.namespace.split(".")[0];a()("[data-"+i+"]").not('[data-yeti-box="'+t+'"]').each(function(){var e=a()(this);e.triggerHandler("close.zf.trigger",[e])})}},c.Initializers.addClosemeListener=function(e){var t=a()("[data-yeti-box]"),i=["dropdown","tooltip","reveal"];if(e&&("string"==typeof e?i.push(e):"object"==typeof e&&"string"==typeof e[0]?i.concat(e):console.error("Plugin names must be strings")),t.length){var n=i.map(function(e){return"closeme.zf."+e}).join(" ");a()(window).off(n).on(n,c.Listeners.Global.closeMeListener)}},c.Initializers.addResizeListener=function(e){var t=a()("[data-resize]");t.length&&n(e,"resize.zf.trigger",c.Listeners.Global.resizeListener,t)},c.Initializers.addScrollListener=function(e){var t=a()("[data-scroll]");t.length&&n(e,"scroll.zf.trigger",c.Listeners.Global.scrollListener,t)},c.Initializers.addMutationEventsListener=function(e){if(!o)return!1;var t=e.find("[data-resize], [data-scroll], [data-mutate]"),i=function(e){var t=a()(e[0].target);switch(e[0].type){case"attributes":"scroll"===t.attr("data-events")&&"data-events"===e[0].attributeName&&t.triggerHandler("scrollme.zf.trigger",[t,window.pageYOffset]),"resize"===t.attr("data-events")&&"data-events"===e[0].attributeName&&t.triggerHandler("resizeme.zf.trigger",[t]),"style"===e[0].attributeName&&(t.closest("[data-mutate]").attr("data-events","mutate"),t.closest("[data-mutate]").triggerHandler("mutateme.zf.trigger",[t.closest("[data-mutate]")]));break;case"childList":t.closest("[data-mutate]").attr("data-events","mutate"),t.closest("[data-mutate]").triggerHandler("mutateme.zf.trigger",[t.closest("[data-mutate]")]);break;default:return!1}};if(t.length)for(var n=0;n<=t.length-1;n++){var r=new o(i);r.observe(t[n],{attributes:!0,childList:!0,characterData:!1,subtree:!0,attributeFilter:["data-events","style"]})}},c.Initializers.addSimpleListeners=function(){var e=a()(document);c.Initializers.addOpenListener(e),c.Initializers.addCloseListener(e),c.Initializers.addToggleListener(e),c.Initializers.addCloseableListener(e),c.Initializers.addToggleFocusListener(e)},c.Initializers.addGlobalListeners=function(){var e=a()(document);c.Initializers.addMutationEventsListener(e),c.Initializers.addResizeListener(),c.Initializers.addScrollListener(),c.Initializers.addClosemeListener()},c.init=function(e,t){if(void 0===e.triggersInitialized){e(document);"complete"===document.readyState?(c.Initializers.addSimpleListeners(),c.Initializers.addGlobalListeners()):e(window).on("load",function(){c.Initializers.addSimpleListeners(),c.Initializers.addGlobalListeners()}),e.triggersInitialized=!0}t&&(t.Triggers=c,t.IHearYou=c.Initializers.addGlobalListeners)}},98:function(e,t,i){e.exports=i(32)}});;
/* global $, SF, Foundation, fitty, truncateDescrWithExpandLink, bizx, isOverflown, */

function truncateUserReviews(){
    if ($('.review-txt').length) {
        truncateDescrWithExpandLink('.review-txt-outer', 'Read More &#187;');
    }
}

(function reviewsEnabledToggle(){
    //wire event for reviews enabled admin toggle
    $('#chk-reviews-enabled').on("change", function(){
        var $form = $(this).parents('form');
        $('input[name=disabled]', $form).val( $(this).get(0).checked ? "0" : "1");
        $form.trigger("submit");
    });
})();


function displayVideo() {
    // defer setting of src attr for YT video, to prevent its date from potentially being applied to the page itself
    // within Google's index.
    var selector = '.m-screenshots-display-full iframe, .featherlight-content iframe';
    var vid = $(selector);
    if (vid.length) {
        if (vid.data('src')) {
            vid.attr('src', vid.data('src'));
        }
    }
}

// project rating control
if ($('form.rate-this-project').length > 0) {
    var $rate_form = $('form.rate-this-project');
    $rate_form.find('.star-rating').on("click", function() {
        $(this).parents('form').trigger("submit");
    });
    $rate_form.find('input.star').on("change", function() {
        $(this).parents('form').trigger("submit");
    });
}

// setup ellipsis for regular reviews
truncateUserReviews();



$('.psp-section').on('click', function(e) {
    if (Foundation.MediaQuery.current === 'small') {
        var $section = $(this);
        if ($section.is('.is-active')) {
            var clicked_h3 = $('h3:first', $section).is(e.target);
            var clicked_section_itself = $section.is(e.target);  // best attempt at knowing if they clicked the pseudo element
            if (clicked_h3 || clicked_section_itself) {
                $(this).toggleClass('is-active');
            }
        } else {
            $(this).toggleClass('is-active');
        }
    }
});

$( document ).ready(function() {
    // init screenshots carousel
    if ($().owlCarousel) {
        $(".owl-carousel").owlCarousel({
            nav: true,
            margin: 11,
            navText: ['', ''],
            responsive: {
                0: {
                    items: 2
                },
                // screenshot width is 245, so use breakpoints at factors of that, so we never get images wider than that
                490: {
                    items: 3
                },
                735: {
                    items: 4
                },
            }
        });
    }


    // init lightbox
    if ($().featherlightGallery) {
        $('.m-screenshots, .thumbnail-single').each(function () {
            $('.gallery', this).featherlightGallery({
                nextIcon: '',
                previousIcon: '',
                loading: '<div class="loading">loading...</div>',
                afterContent: function (event) {
                    var caption = this.$currentTarget.attr('title');
                    $('.featherlight-content .caption').remove();
                    var alt = this.$currentTarget.attr('data-alt');
                    $('.featherlight-content > img').attr('alt', alt);
                    if (caption) {
                        var captionContainer = $('<div class="caption"></div>').text(caption);
                        $('.featherlight-content').append(captionContainer);
                    }
                    displayVideo();
                }
            });
        });

        $('.btn-nearest-gallery').on("click", function (e) {
            e.preventDefault();
            $(this).siblings(".gallery").eq(0).click();
            return false;
        });
    }

    // fix scrolldown on SD masthead menu
    $('body.v-sd #top_nav a').on('click', function(event) {
        var href = this.getAttribute('href');
        if (href.includes('#')) {
            const targetId = href.split("#")[1];
            const targetElement = document.getElementById(targetId);
            // check if element exists and is visible
            if (targetElement && targetElement.offsetParent !== null) {
                event.preventDefault();
                const offset = -70;
                const newTop = targetElement.getBoundingClientRect().top + offset;
                window.scrollTo({
                    top: newTop,
                    behavior: 'smooth'
                });
            }
        }
    });
});

// screenshot thumbnails for inline mode
$('.thumbnail', '.m-screenshots[data-mode="inline"]').on("click", function(e){
    var $full = $('.m-screenshots-display-full');
    $full.text('loading...');
    var $t = $(e.currentTarget);
    if($t.hasClass('video-screenshot')){
        $full.html($t.data('featherlight'));
        displayVideo();
    } else {
        var img = new Image();
        if ($t.attr('title')) {
            img.setAttribute('alt',$t.attr('title'));
        }else{
            img.setAttribute('alt',$t.data('alt'));
        }
        img.onload = function(){
            var markup = '<img src="' + img.src + '" alt="' + img.alt + '">';
            var caption = '';
            if ($t.attr('title')){
                caption = $('<div/>').text($t.attr('title')).html(); // encode
                markup += '<p class="screenshot-caption">' + caption + '</p>';
            }
            $full.html(markup);
            handleOverflownCaptions($full);
        };
        img.src = $t.attr('href');
    }
    return false;
});


displayVideo();


function handleOverflownCaptions($el){
    if (!$el) {
        $el = $('.m-screenshots-display-full');
    }
    var caption = $('p', $el);
    if (caption.length && isOverflown(caption.get(0))) {
        var tooltip = new Foundation.Tooltip(caption, {'tipText': caption.text(), triggerClass:'', maxWidth: '20rem',
                                             clickOpen:true, templateClasses:'tooltip-billboard'});
    }
}


handleOverflownCaptions();

$(function() {
    var trusted = $('.download-container .tip.trusted-file');
    if (trusted.length) {
        var tooltip = new Foundation.Tooltip(
            trusted,
            { 'tipText': 'This download has been scanned for malware. All downloads on SourceForge are scanned for malware.' }
        );
    }
});


function reflowProjectMenu() {
    function getOverflowedItems() {
        if (Foundation.MediaQuery.current === 'small') {
            // return "no items", so "..." isn't created (or is cleaned up)
            return [];
        }
        return $('#top_nav_admin ul.dropdown > li').map(function() {
            if ($(this).position().top !== 0) {
                return this;
            }
        }).get();
    }
    var overflowedMenuItems = getOverflowedItems();
    var $menu = $('#top_nav_admin ul.dropdown');
    var menu_margins = $menu.outerWidth(true) - $menu.outerWidth();
    if (overflowedMenuItems.length) {
        // create #ddd if needed
        if (!$('#top_nav_admin ul.dropdown #ddd').length) {
            $menu.append("<li id='ddd'><a>\u2022\u2022\u2022</a><ul></ul></li>"); // \u2022 == dot
        }
        var ddd_width = $('#ddd').outerWidth(true);
        // force Add Tool to stay on main row
        $('#add-tool-container').css({
            'position': 'absolute',
            'right': ddd_width + menu_margins,
            'top': 0,
        });
        // set smaller width of the main menu
        var new_width = $menu.parent().width() - menu_margins - ddd_width - ($('#add-tool-container').outerWidth(true) || 0);
        $menu.width(new_width);
        // move overflowed items into the "..." dropdown
        overflowedMenuItems = getOverflowedItems();  // get again since we moved #add-tool and resized the parent
        var ddd_contents = overflowedMenuItems.map(function(elem, i) {
            var react_attr = /data-reactid=".*?"/g;
            return elem.outerHTML.replace(/\u25BE/g, '').replace(react_attr, ''); // \u25BE == down triangle
        }).join('');
        $('#top_nav_admin ul.dropdown #ddd ul').html(ddd_contents);
    } else {
        // nothing overflowed, reset "...", "Add" and menu changes
        $('#top_nav_admin ul.dropdown #ddd').remove();
        $menu.width("auto");
        $('#add-tool-container').css({
            'position': 'relative',
            'right': 0,
        });

    }
}

if ($('#top_nav_admin').length) {

    // when touch events are used, don't let a click on a dropdown link actual go to that "parent" page, prevent it
    // so that the dropdown menu is shown.   Touchstart events run first.
    var $dropdowns = $('.dropdown > li ul').parent().find('> a');
    var usingTouch = false;
    $dropdowns.on('touchstart', function() {
        usingTouch = true;
    });
    $dropdowns.on('click', function(e) {
        if (usingTouch) {
            e.preventDefault();
        }
    });

    if (window.MutationObserver) {
        // watch for React to kick in during admin mode, and subsequent lock/unlock changes
        // this is carefully set up so we don't get DOM changes from reflowProjectMenu
        new MutationObserver(function () {
            if (!$('ul.dropdown').length) {  // initial menu is gone, replaced with React admin menu in unlocked mode
                var top_of_react_dom = $('#top_nav_admin > div').get(0);
                new MutationObserver(reflowProjectMenu).observe(top_of_react_dom, {childList: true});
            }
        }).observe(document.getElementById('top_nav_admin'), {childList: true});
    }
    // watch resize
    window.addEventListener('resize', reflowProjectMenu);
    if (!SF.initial_breakpoints_visible || SF.initial_breakpoints_visible.medium) {
        // DOM ready
        $(reflowProjectMenu);
    }
}


// wire up fitty for dynamic masthead h1 font sizes
$(function(){
    if (window.fitty) {
        var selector = '.v-sf h1.long-title';  // OSS & Commercial.  Not Slashdot, it does wrapping instead
        fitty(selector, {
            minSize: 24,
            maxSize: 48,
            observeMutations: {
                subtree: true,
                childList: true,
                characterData: true
            }
        });
    }
});

if ($('#demo-tour-modal').length) {
    $(document).on('open.zf.reveal', "#demo-tour-modal", function (e) {
        var $modal = $(this);
        var ajax_url = $modal.data("ajax-url");
        if (ajax_url) {
            $.ajax(ajax_url + document.location.search).done(function (response) {
                $modal.find('#demo-tour-frame').remove();
                $modal.append(response);
            });
        }
    });
}

function linkVideoExternally(videoURL, placeholderSelectors){
    var blankImg = '<a id="blank-screenshot" href="'+ (videoURL.includes('https') ? '' : 'https://') + videoURL +'" target="_blank" style="margin:0 auto;"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgYAAAAAMAASsJTYQAAAAASUVORK5CYII=" alt="Play Video" /></a>';
    $(placeholderSelectors).prepend(blankImg);
    var youtubeIcon = $(placeholderSelectors).find('.youtube-btn');
    if (youtubeIcon.length) {
        youtubeIcon.css({'display':'block'});
        youtubeIcon.detach().appendTo(placeholderSelectors +' #blank-screenshot');
    }
}

function linkVideoThumbnailExternally(videoURL, placeholderSelectors){
    var youtubeIcon = $(placeholderSelectors).find('.youtube-btn');
    $(placeholderSelectors).each(function(idx){
        $(this).unbind('click');
        $(this).on('click', function(e) {
            e.preventDefault();
            window.open('https://' + videoURL, '_blank');
        });
    });
    if (youtubeIcon.length) {
        youtubeIcon.css({'display':'block'});
        $(placeholderSelectors).not(youtubeIcon.attr('class')).find('img').each(function(idx){
            $(this).css({'visibility':'hidden'});
        });
    }
}

function updateVideoElements(iframePlaceholder, iframeHTML, thumbnailSelector, thumbnailURL, slug=''){
    $('#blank-screenshot').remove(); // pre-existing placeholder, possibly
    if ($(iframePlaceholder).length){
        $(iframePlaceholder).prepend(iframeHTML);
    }
    if (thumbnailSelector === '' || thumbnailURL === ''){
        return;
    }
    $(thumbnailSelector).each(function(idx){
        $(this).find('img.project-thumb-'+slug).attr('src', thumbnailURL);
        var playImg = $(this).find('.video-thumb-img');
        var playImgIcon = $(this).find('#video-play-btn');
        if (playImg.length && playImgIcon.length) {
            playImg.css({'display': 'block'});
            playImgIcon.css({'display': 'block'});
        }
    });
}

$(()=>{
    $('#btn-lang-view-all').on('click', (e)=> {
        e.preventDefault();
        $('.c-supported-languages .list > div').removeClass('hide');
        $('#btn-lang-view-all').hide();
        return false;
    });
});
;
/*!
 * jQuery Typeahead
 * Copyright (C) 2018 RunningCoder.org
 * Licensed under the MIT license
 *
 * @author Tom Bertrand
 * @version 2.10.6 (2018-7-30)
 * @link http://www.runningcoder.org/jquerytypeahead/
 */
!function(e){var t;"function"==typeof define&&define.amd?define("jquery-typeahead",["jquery"],function(t){return e(t)}):"object"==typeof module&&module.exports?module.exports=(void 0===t&&(t="undefined"!=typeof window?require("jquery"):require("jquery")(void 0)),e(t)):e(jQuery)}(function(j){"use strict";var i,s={input:null,minLength:2,maxLength:!(window.Typeahead={version:"2.10.6"}),maxItem:8,dynamic:!1,delay:300,order:null,offset:!1,hint:!1,accent:!1,highlight:!0,multiselect:null,group:!1,groupOrder:null,maxItemPerGroup:null,dropdownFilter:!1,dynamicFilter:null,backdrop:!1,backdropOnFocus:!1,cache:!1,ttl:36e5,compression:!1,searchOnFocus:!1,blurOnTab:!0,resultContainer:null,generateOnLoad:null,mustSelectItem:!1,href:null,display:["display"],template:null,templateValue:null,groupTemplate:null,correlativeTemplate:!1,emptyTemplate:!1,cancelButton:!0,loadingAnimation:!0,filter:!0,matcher:null,source:null,callback:{onInit:null,onReady:null,onShowLayout:null,onHideLayout:null,onSearch:null,onResult:null,onLayoutBuiltBefore:null,onLayoutBuiltAfter:null,onNavigateBefore:null,onNavigateAfter:null,onEnter:null,onLeave:null,onClickBefore:null,onClickAfter:null,onDropdownFilter:null,onSendRequest:null,onReceiveRequest:null,onPopulateSource:null,onCacheSave:null,onSubmit:null,onCancel:null},selector:{container:"typeahead__container",result:"typeahead__result",list:"typeahead__list",group:"typeahead__group",item:"typeahead__item",empty:"typeahead__empty",display:"typeahead__display",query:"typeahead__query",filter:"typeahead__filter",filterButton:"typeahead__filter-button",dropdown:"typeahead__dropdown",dropdownItem:"typeahead__dropdown-item",labelContainer:"typeahead__label-container",label:"typeahead__label",button:"typeahead__button",backdrop:"typeahead__backdrop",hint:"typeahead__hint",cancelButton:"typeahead__cancel-button"},debug:!1},o={from:"ãàáäâẽèéëêìíïîõòóöôùúüûñç",to:"aaaaaeeeeeiiiiooooouuuunc"},n=~window.navigator.appVersion.indexOf("MSIE 9."),r=~window.navigator.appVersion.indexOf("MSIE 10"),a=!!~window.navigator.userAgent.indexOf("Trident")&&~window.navigator.userAgent.indexOf("rv:11"),l=function(t,e){this.rawQuery=t.val()||"",this.query=t.val()||"",this.selector=t[0].selector,this.deferred=null,this.tmpSource={},this.source={},this.dynamicGroups=[],this.hasDynamicGroups=!1,this.generatedGroupCount=0,this.groupBy="group",this.groups=[],this.searchGroups=[],this.generateGroups=[],this.requestGroups=[],this.result=[],this.tmpResult={},this.groupTemplate="",this.resultHtml=null,this.resultCount=0,this.resultCountPerGroup={},this.options=e,this.node=t,this.namespace="."+this.helper.slugify.call(this,this.selector)+".typeahead",this.isContentEditable=void 0!==this.node.attr("contenteditable")&&"false"!==this.node.attr("contenteditable"),this.container=null,this.resultContainer=null,this.item=null,this.items=null,this.comparedItems=null,this.xhr={},this.hintIndex=null,this.filters={dropdown:{},dynamic:{}},this.dropdownFilter={static:[],dynamic:[]},this.dropdownFilterAll=null,this.isDropdownEvent=!1,this.requests={},this.backdrop={},this.hint={},this.label={},this.hasDragged=!1,this.focusOnly=!1,this.displayEmptyTemplate,this.__construct()};l.prototype={_validateCacheMethod:function(t){var e;if(!0===t)t="localStorage";else if("string"==typeof t&&!~["localStorage","sessionStorage"].indexOf(t))return!1;e=void 0!==window[t];try{window[t].setItem("typeahead","typeahead"),window[t].removeItem("typeahead")}catch(t){e=!1}return e&&t||!1},extendOptions:function(){if(this.options.cache=this._validateCacheMethod(this.options.cache),this.options.compression&&("object"==typeof LZString&&this.options.cache||(this.options.compression=!1)),this.options.maxLength&&!isNaN(this.options.maxLength)||(this.options.maxLength=1/0),void 0!==this.options.maxItem&&~[0,!1].indexOf(this.options.maxItem)&&(this.options.maxItem=1/0),this.options.maxItemPerGroup&&!/^\d+$/.test(this.options.maxItemPerGroup)&&(this.options.maxItemPerGroup=null),this.options.display&&!Array.isArray(this.options.display)&&(this.options.display=[this.options.display]),this.options.multiselect&&(this.items=[],this.comparedItems=[],"string"==typeof this.options.multiselect.matchOn&&(this.options.multiselect.matchOn=[this.options.multiselect.matchOn])),this.options.group&&(Array.isArray(this.options.group)||("string"==typeof this.options.group?this.options.group={key:this.options.group}:"boolean"==typeof this.options.group&&(this.options.group={key:"group"}),this.options.group.key=this.options.group.key||"group")),this.options.highlight&&!~["any",!0].indexOf(this.options.highlight)&&(this.options.highlight=!1),this.options.dropdownFilter&&this.options.dropdownFilter instanceof Object){Array.isArray(this.options.dropdownFilter)||(this.options.dropdownFilter=[this.options.dropdownFilter]);for(var t=0,e=this.options.dropdownFilter.length;t<e;++t)this.dropdownFilter[this.options.dropdownFilter[t].value?"static":"dynamic"].push(this.options.dropdownFilter[t])}this.options.dynamicFilter&&!Array.isArray(this.options.dynamicFilter)&&(this.options.dynamicFilter=[this.options.dynamicFilter]),this.options.accent&&("object"==typeof this.options.accent?this.options.accent.from&&this.options.accent.to&&(this.options.accent.from.length,this.options.accent.to.length):this.options.accent=o),this.options.groupTemplate&&(this.groupTemplate=this.options.groupTemplate),this.options.resultContainer&&("string"==typeof this.options.resultContainer&&(this.options.resultContainer=j(this.options.resultContainer)),this.options.resultContainer instanceof j&&this.options.resultContainer[0]&&(this.resultContainer=this.options.resultContainer)),this.options.group&&this.options.group.key&&(this.groupBy=this.options.group.key),this.options.callback&&this.options.callback.onClick&&(this.options.callback.onClickBefore=this.options.callback.onClick,delete this.options.callback.onClick),this.options.callback&&this.options.callback.onNavigate&&(this.options.callback.onNavigateBefore=this.options.callback.onNavigate,delete this.options.callback.onNavigate),this.options=j.extend(!0,{},s,this.options)},unifySourceFormat:function(){var t,e,i;for(t in this.dynamicGroups=[],Array.isArray(this.options.source)&&(this.options.source={group:{data:this.options.source}}),"string"==typeof this.options.source&&(this.options.source={group:{ajax:{url:this.options.source}}}),this.options.source.ajax&&(this.options.source={group:{ajax:this.options.source.ajax}}),(this.options.source.url||this.options.source.data)&&(this.options.source={group:this.options.source}),this.options.source)if(this.options.source.hasOwnProperty(t)){if("string"==typeof(e=this.options.source[t])&&(e={ajax:{url:e}}),i=e.url||e.ajax,Array.isArray(i)?(e.ajax="string"==typeof i[0]?{url:i[0]}:i[0],e.ajax.path=e.ajax.path||i[1]||null):"object"==typeof e.url?e.ajax=e.url:"string"==typeof e.url&&(e.ajax={url:e.url}),delete e.url,!e.data&&!e.ajax)return!1;e.display&&!Array.isArray(e.display)&&(e.display=[e.display]),e.minLength="number"==typeof e.minLength?e.minLength:this.options.minLength,e.maxLength="number"==typeof e.maxLength?e.maxLength:this.options.maxLength,e.dynamic="boolean"==typeof e.dynamic||this.options.dynamic,e.minLength>e.maxLength&&(e.minLength=e.maxLength),this.options.source[t]=e,this.options.source[t].dynamic&&this.dynamicGroups.push(t),e.cache=void 0!==e.cache?this._validateCacheMethod(e.cache):this.options.cache,e.compression&&("object"==typeof LZString&&e.cache||(e.compression=!1))}return this.hasDynamicGroups=this.options.dynamic||!!this.dynamicGroups.length,!0},init:function(){this.helper.executeCallback.call(this,this.options.callback.onInit,[this.node]),this.container=this.node.closest("."+this.options.selector.container)},delegateEvents:function(){var i=this,t=["focus"+this.namespace,"input"+this.namespace,"propertychange"+this.namespace,"keydown"+this.namespace,"keyup"+this.namespace,"search"+this.namespace,"generate"+this.namespace];j("html").on("touchmove",function(){i.hasDragged=!0}).on("touchstart",function(){i.hasDragged=!1}),this.node.closest("form").on("submit",function(t){if(!i.options.mustSelectItem||!i.helper.isEmpty(i.item))return i.options.backdropOnFocus||i.hideLayout(),i.options.callback.onSubmit?i.helper.executeCallback.call(i,i.options.callback.onSubmit,[i.node,this,i.item||i.items,t]):void 0;t.preventDefault()}).on("reset",function(){setTimeout(function(){i.node.trigger("input"+i.namespace),i.hideLayout()})});var s=!1;if(this.node.attr("placeholder")&&(r||a)){var e=!0;this.node.on("focusin focusout",function(){e=!(this.value||!this.placeholder)}),this.node.on("input",function(t){e&&(t.stopImmediatePropagation(),e=!1)})}this.node.off(this.namespace).on(t.join(" "),function(t,e){switch(t.type){case"generate":i.generateSource(Object.keys(i.options.source));break;case"focus":if(i.focusOnly){i.focusOnly=!1;break}i.options.backdropOnFocus&&(i.buildBackdropLayout(),i.showLayout()),i.options.searchOnFocus&&!i.item&&(i.deferred=j.Deferred(),i.assignQuery(),i.generateSource());break;case"keydown":8===t.keyCode&&i.options.multiselect&&i.options.multiselect.cancelOnBackspace&&""===i.query&&i.items.length?i.cancelMultiselectItem(i.items.length-1,null,t):t.keyCode&&~[9,13,27,38,39,40].indexOf(t.keyCode)&&(s=!0,i.navigate(t));break;case"keyup":n&&i.node[0].value.replace(/^\s+/,"").toString().length<i.query.length&&i.node.trigger("input"+i.namespace);break;case"propertychange":if(s){s=!1;break}case"input":i.deferred=j.Deferred(),i.assignQuery(),""===i.rawQuery&&""===i.query&&(t.originalEvent=e||{},i.helper.executeCallback.call(i,i.options.callback.onCancel,[i.node,i.item,t]),i.item=null),i.options.cancelButton&&i.toggleCancelButtonVisibility(),i.options.hint&&i.hint.container&&""!==i.hint.container.val()&&0!==i.hint.container.val().indexOf(i.rawQuery)&&(i.hint.container.val(""),i.isContentEditable&&i.hint.container.text("")),i.hasDynamicGroups?i.helper.typeWatch(function(){i.generateSource()},i.options.delay):i.generateSource();break;case"search":i.searchResult(),i.buildLayout(),i.result.length||i.searchGroups.length&&i.displayEmptyTemplate?i.showLayout():i.hideLayout(),i.deferred&&i.deferred.resolve()}return i.deferred&&i.deferred.promise()}),this.options.generateOnLoad&&this.node.trigger("generate"+this.namespace)},assignQuery:function(){this.isContentEditable?this.rawQuery=this.node.text():this.rawQuery=this.node.val().toString(),this.rawQuery=this.rawQuery.replace(/^\s+/,""),this.rawQuery!==this.query&&(this.query=this.rawQuery)},filterGenerateSource:function(){if(this.searchGroups=[],this.generateGroups=[],!this.focusOnly||this.options.multiselect)for(var t in this.options.source)if(this.options.source.hasOwnProperty(t)&&this.query.length>=this.options.source[t].minLength&&this.query.length<=this.options.source[t].maxLength){if(this.filters.dropdown&&"group"===this.filters.dropdown.key&&this.filters.dropdown.value!==t)continue;if(this.searchGroups.push(t),!this.options.source[t].dynamic&&this.source[t])continue;this.generateGroups.push(t)}},generateSource:function(t){if(this.filterGenerateSource(),Array.isArray(t)&&t.length)this.generateGroups=t;else if(!this.generateGroups.length)return void this.node.trigger("search"+this.namespace);if(this.requestGroups=[],this.generatedGroupCount=0,this.options.loadingAnimation&&this.container.addClass("loading"),!this.helper.isEmpty(this.xhr)){for(var e in this.xhr)this.xhr.hasOwnProperty(e)&&this.xhr[e].abort();this.xhr={}}for(var i,s,o,n,r,a,l,h=this,c=(e=0,this.generateGroups.length);e<c;++e){if(i=this.generateGroups[e],n=(o=this.options.source[i]).cache,r=o.compression,n&&(a=window[n].getItem("TYPEAHEAD_"+this.selector+":"+i))){r&&(a=LZString.decompressFromUTF16(a)),l=!1;try{(a=JSON.parse(a+"")).data&&a.ttl>(new Date).getTime()?(this.populateSource(a.data,i),l=!0):window[n].removeItem("TYPEAHEAD_"+this.selector+":"+i)}catch(t){}if(l)continue}!o.data||o.ajax?o.ajax&&(this.requests[i]||(this.requests[i]=this.generateRequestObject(i)),this.requestGroups.push(i)):"function"==typeof o.data?(s=o.data.call(this),Array.isArray(s)?h.populateSource(s,i):"function"==typeof s.promise&&function(e){j.when(s).then(function(t){t&&Array.isArray(t)&&h.populateSource(t,e)})}(i)):this.populateSource(j.extend(!0,[],o.data),i)}return this.requestGroups.length&&this.handleRequests(),!!this.generateGroups.length},generateRequestObject:function(s){var o=this,n=this.options.source[s],t={request:{url:n.ajax.url||null,dataType:"json",beforeSend:function(t,e){o.xhr[s]=t;var i=o.requests[s].callback.beforeSend||n.ajax.beforeSend;"function"==typeof i&&i.apply(null,arguments)}},callback:{beforeSend:null,done:null,fail:null,then:null,always:null},extra:{path:n.ajax.path||null,group:s},validForGroup:[s]};if("function"!=typeof n.ajax&&(n.ajax instanceof Object&&(t=this.extendXhrObject(t,n.ajax)),1<Object.keys(this.options.source).length))for(var e in this.requests)this.requests.hasOwnProperty(e)&&(this.requests[e].isDuplicated||t.request.url&&t.request.url===this.requests[e].request.url&&(this.requests[e].validForGroup.push(s),t.isDuplicated=!0,delete t.validForGroup));return t},extendXhrObject:function(t,e){return"object"==typeof e.callback&&(t.callback=e.callback,delete e.callback),"function"==typeof e.beforeSend&&(t.callback.beforeSend=e.beforeSend,delete e.beforeSend),t.request=j.extend(!0,t.request,e),"jsonp"!==t.request.dataType.toLowerCase()||t.request.jsonpCallback||(t.request.jsonpCallback="callback_"+t.extra.group),t},handleRequests:function(){var t,h=this,c=this.requestGroups.length;if(!1!==this.helper.executeCallback.call(this,this.options.callback.onSendRequest,[this.node,this.query]))for(var e=0,i=this.requestGroups.length;e<i;++e)t=this.requestGroups[e],this.requests[t].isDuplicated||function(t,r){if("function"==typeof h.options.source[t].ajax){var e=h.options.source[t].ajax.call(h,h.query);if("object"!=typeof(r=h.extendXhrObject(h.generateRequestObject(t),"object"==typeof e?e:{})).request||!r.request.url)return h.populateSource([],t);h.requests[t]=r}var a,i=!1,l={};if(~r.request.url.indexOf("{{query}}")&&(i||(r=j.extend(!0,{},r),i=!0),r.request.url=r.request.url.replace("{{query}}",encodeURIComponent(h.query))),r.request.data)for(var s in r.request.data)if(r.request.data.hasOwnProperty(s)&&~String(r.request.data[s]).indexOf("{{query}}")){i||(r=j.extend(!0,{},r),i=!0),r.request.data[s]=r.request.data[s].replace("{{query}}",h.query);break}j.ajax(r.request).done(function(t,e,i){for(var s,o=0,n=r.validForGroup.length;o<n;o++)s=r.validForGroup[o],"function"==typeof(a=h.requests[s]).callback.done&&(l[s]=a.callback.done.call(h,t,e,i))}).fail(function(t,e,i){for(var s=0,o=r.validForGroup.length;s<o;s++)(a=h.requests[r.validForGroup[s]]).callback.fail instanceof Function&&a.callback.fail.call(h,t,e,i)}).always(function(t,e,i){for(var s,o=0,n=r.validForGroup.length;o<n;o++){if(s=r.validForGroup[o],(a=h.requests[s]).callback.always instanceof Function&&a.callback.always.call(h,t,e,i),"abort"===e)return;h.populateSource(null!==t&&"function"==typeof t.promise&&[]||l[s]||t,a.extra.group,a.extra.path||a.request.path),0===(c-=1)&&h.helper.executeCallback.call(h,h.options.callback.onReceiveRequest,[h.node,h.query])}}).then(function(t,e){for(var i=0,s=r.validForGroup.length;i<s;i++)(a=h.requests[r.validForGroup[i]]).callback.then instanceof Function&&a.callback.then.call(h,t,e)})}(t,this.requests[t])},populateSource:function(i,t,e){var s=this,o=this.options.source[t],n=o.ajax&&o.data;e&&"string"==typeof e&&(i=this.helper.namespace.call(this,e,i)),Array.isArray(i)||(i=[]),n&&("function"==typeof n&&(n=n()),Array.isArray(n)&&(i=i.concat(n)));for(var r,a=o.display?"compiled"===o.display[0]?o.display[1]:o.display[0]:"compiled"===this.options.display[0]?this.options.display[1]:this.options.display[0],l=0,h=i.length;l<h;l++)null!==i[l]&&"boolean"!=typeof i[l]&&("string"==typeof i[l]&&((r={})[a]=i[l],i[l]=r),i[l].group=t);if(!this.hasDynamicGroups&&this.dropdownFilter.dynamic.length){var c,p,u={};for(l=0,h=i.length;l<h;l++)for(var d=0,f=this.dropdownFilter.dynamic.length;d<f;d++)c=this.dropdownFilter.dynamic[d].key,(p=i[l][c])&&(this.dropdownFilter.dynamic[d].value||(this.dropdownFilter.dynamic[d].value=[]),u[c]||(u[c]=[]),~u[c].indexOf(p.toLowerCase())||(u[c].push(p.toLowerCase()),this.dropdownFilter.dynamic[d].value.push(p)))}if(this.options.correlativeTemplate){var m=o.template||this.options.template,g="";if("function"==typeof m&&(m=m.call(this,"",{})),m){if(Array.isArray(this.options.correlativeTemplate))for(l=0,h=this.options.correlativeTemplate.length;l<h;l++)g+="{{"+this.options.correlativeTemplate[l]+"}} ";else g=m.replace(/<.+?>/g," ").replace(/\s{2,}/," ").trim();for(l=0,h=i.length;l<h;l++)i[l].compiled=j("<textarea />").html(g.replace(/\{\{([\w\-\.]+)(?:\|(\w+))?}}/g,function(t,e){return s.helper.namespace.call(s,e,i[l],"get","")}).trim()).text();o.display?~o.display.indexOf("compiled")||o.display.unshift("compiled"):~this.options.display.indexOf("compiled")||this.options.display.unshift("compiled")}else;}this.options.callback.onPopulateSource&&(i=this.helper.executeCallback.call(this,this.options.callback.onPopulateSource,[this.node,i,t,e])),this.tmpSource[t]=Array.isArray(i)&&i||[];var y=this.options.source[t].cache,v=this.options.source[t].compression,b=this.options.source[t].ttl||this.options.ttl;if(y&&!window[y].getItem("TYPEAHEAD_"+this.selector+":"+t)){this.options.callback.onCacheSave&&(i=this.helper.executeCallback.call(this,this.options.callback.onCacheSave,[this.node,i,t,e]));var k=JSON.stringify({data:i,ttl:(new Date).getTime()+b});v&&(k=LZString.compressToUTF16(k)),window[y].setItem("TYPEAHEAD_"+this.selector+":"+t,k)}this.incrementGeneratedGroup()},incrementGeneratedGroup:function(){if(this.generatedGroupCount++,this.generatedGroupCount===this.generateGroups.length){this.xhr={};for(var t=0,e=this.generateGroups.length;t<e;t++)this.source[this.generateGroups[t]]=this.tmpSource[this.generateGroups[t]];this.hasDynamicGroups||this.buildDropdownItemLayout("dynamic"),this.options.loadingAnimation&&this.container.removeClass("loading"),this.node.trigger("search"+this.namespace)}},navigate:function(t){if(this.helper.executeCallback.call(this,this.options.callback.onNavigateBefore,[this.node,this.query,t]),27===t.keyCode)return t.preventDefault(),void(this.query.length?(this.resetInput(),this.node.trigger("input"+this.namespace,[t])):(this.node.blur(),this.hideLayout()));if(this.result.length){var e,i=this.resultContainer.find("."+this.options.selector.item).not("[disabled]"),s=i.filter(".active"),o=s[0]?i.index(s):null,n=s[0]?s.attr("data-index"):null,r=null;if(this.clearActiveItem(),this.helper.executeCallback.call(this,this.options.callback.onLeave,[this.node,null!==o&&i.eq(o)||void 0,null!==n&&this.result[n]||void 0,t]),13===t.keyCode)return t.preventDefault(),void(0<s.length?"javascript:;"===s.find("a:first")[0].href?s.find("a:first").trigger("click",t):s.find("a:first")[0].click():this.node.closest("form").trigger("submit"));if(39!==t.keyCode){9===t.keyCode?this.options.blurOnTab?this.hideLayout():0<s.length?o+1<i.length?(t.preventDefault(),r=o+1,this.addActiveItem(i.eq(r))):this.hideLayout():i.length?(t.preventDefault(),r=0,this.addActiveItem(i.first())):this.hideLayout():38===t.keyCode?(t.preventDefault(),0<s.length?0<=o-1&&(r=o-1,this.addActiveItem(i.eq(r))):i.length&&(r=i.length-1,this.addActiveItem(i.last()))):40===t.keyCode&&(t.preventDefault(),0<s.length?o+1<i.length&&(r=o+1,this.addActiveItem(i.eq(r))):i.length&&(r=0,this.addActiveItem(i.first()))),e=null!==r?i.eq(r).attr("data-index"):null,this.helper.executeCallback.call(this,this.options.callback.onEnter,[this.node,null!==r&&i.eq(r)||void 0,null!==e&&this.result[e]||void 0,t]),t.preventInputChange&&~[38,40].indexOf(t.keyCode)&&this.buildHintLayout(null!==e&&e<this.result.length?[this.result[e]]:null),this.options.hint&&this.hint.container&&this.hint.container.css("color",t.preventInputChange?this.hint.css.color:null===e&&this.hint.css.color||this.hint.container.css("background-color")||"fff");var a=null===e||t.preventInputChange?this.rawQuery:this.getTemplateValue.call(this,this.result[e]);this.node.val(a),this.isContentEditable&&this.node.text(a),this.helper.executeCallback.call(this,this.options.callback.onNavigateAfter,[this.node,i,null!==r&&i.eq(r).find("a:first")||void 0,null!==e&&this.result[e]||void 0,this.query,t])}else null!==o?i.eq(o).find("a:first")[0].click():this.options.hint&&""!==this.hint.container.val()&&this.helper.getCaret(this.node[0])>=this.query.length&&i.filter('[data-index="'+this.hintIndex+'"]').find("a:first")[0].click()}},getTemplateValue:function(i){if(i){var t=i.group&&this.options.source[i.group].templateValue||this.options.templateValue;if("function"==typeof t&&(t=t.call(this)),!t)return this.helper.namespace.call(this,i.matchedKey,i).toString();var s=this;return t.replace(/\{\{([\w\-.]+)}}/gi,function(t,e){return s.helper.namespace.call(s,e,i,"get","")})}},clearActiveItem:function(){this.resultContainer.find("."+this.options.selector.item).removeClass("active")},addActiveItem:function(t){t.addClass("active")},searchResult:function(){this.resetLayout(),!1!==this.helper.executeCallback.call(this,this.options.callback.onSearch,[this.node,this.query])&&(!this.searchGroups.length||this.options.multiselect&&this.options.multiselect.limit&&this.items.length>=this.options.multiselect.limit||this.searchResultData(),this.helper.executeCallback.call(this,this.options.callback.onResult,[this.node,this.query,this.result,this.resultCount,this.resultCountPerGroup]),this.isDropdownEvent&&(this.helper.executeCallback.call(this,this.options.callback.onDropdownFilter,[this.node,this.query,this.filters.dropdown,this.result]),this.isDropdownEvent=!1))},searchResultData:function(){var t,e,i,s,o,n,r,a,l,h,c,p=this.groupBy,u=null,d=this.query.toLowerCase(),f=this.options.maxItem,m=this.options.maxItemPerGroup,g=this.filters.dynamic&&!this.helper.isEmpty(this.filters.dynamic),y="function"==typeof this.options.matcher&&this.options.matcher;this.options.accent&&(d=this.helper.removeAccent.call(this,d));for(var v=0,b=this.searchGroups.length;v<b;++v)if(F=this.searchGroups[v],!this.filters.dropdown||"group"!==this.filters.dropdown.key||this.filters.dropdown.value===F){o=void 0!==this.options.source[F].filter?this.options.source[F].filter:this.options.filter,r="function"==typeof this.options.source[F].matcher&&this.options.source[F].matcher||y;for(var k=0,w=this.source[F].length;k<w&&(!(this.resultItemCount>=f)||this.options.callback.onResult);k++)if((!g||this.dynamicFilter.validate.apply(this,[this.source[F][k]]))&&null!==(t=this.source[F][k])&&"boolean"!=typeof t&&(!this.options.multiselect||this.isMultiselectUniqueData(t))&&(!this.filters.dropdown||(t[this.filters.dropdown.key]||"").toLowerCase()===(this.filters.dropdown.value||"").toLowerCase())){if((u="group"===p?F:t[p]?t[p]:t.group)&&!this.tmpResult[u]&&(this.tmpResult[u]=[],this.resultCountPerGroup[u]=0),m&&"group"===p&&this.tmpResult[u].length>=m&&!this.options.callback.onResult)break;for(var x=0,C=(S=this.options.source[F].display||this.options.display).length;x<C;++x){if(!1!==o){if(void 0===(s=/\./.test(S[x])?this.helper.namespace.call(this,S[x],t):t[S[x]])||""===s)continue;s=this.helper.cleanStringFromScript(s)}if("function"==typeof o){if(void 0===(n=o.call(this,t,s)))break;if(!n)continue;"object"==typeof n&&(t=n)}if(~[void 0,!0].indexOf(o)){if(null===s)continue;if(i=(i=s).toString().toLowerCase(),this.options.accent&&(i=this.helper.removeAccent.call(this,i)),e=i.indexOf(d),this.options.correlativeTemplate&&"compiled"===S[x]&&e<0&&/\s/.test(d)){l=!0,c=i;for(var q=0,A=(h=d.split(" ")).length;q<A;q++)if(""!==h[q]){if(!~c.indexOf(h[q])){l=!1;break}c=c.replace(h[q],"")}}if(e<0&&!l)continue;if(this.options.offset&&0!==e)continue;if(r){if(void 0===(a=r.call(this,t,s)))break;if(!a)continue;"object"==typeof a&&(t=a)}}if(this.resultCount++,this.resultCountPerGroup[u]++,this.resultItemCount<f){if(m&&this.tmpResult[u].length>=m)break;this.tmpResult[u].push(j.extend(!0,{matchedKey:S[x]},t)),this.resultItemCount++}break}if(!this.options.callback.onResult){if(this.resultItemCount>=f)break;if(m&&this.tmpResult[u].length>=m&&"group"===p)break}}}if(this.options.order){var O,S=[];for(var F in this.tmpResult)if(this.tmpResult.hasOwnProperty(F)){for(v=0,b=this.tmpResult[F].length;v<b;v++)O=this.options.source[this.tmpResult[F][v].group].display||this.options.display,~S.indexOf(O[0])||S.push(O[0]);this.tmpResult[F].sort(this.helper.sort(S,"asc"===this.options.order,function(t){return t.toString().toUpperCase()}))}}var L=[],I=[];for(v=0,b=(I="function"==typeof this.options.groupOrder?this.options.groupOrder.apply(this,[this.node,this.query,this.tmpResult,this.resultCount,this.resultCountPerGroup]):Array.isArray(this.options.groupOrder)?this.options.groupOrder:"string"==typeof this.options.groupOrder&&~["asc","desc"].indexOf(this.options.groupOrder)?Object.keys(this.tmpResult).sort(this.helper.sort([],"asc"===this.options.groupOrder,function(t){return t.toString().toUpperCase()})):Object.keys(this.tmpResult)).length;v<b;v++)L=L.concat(this.tmpResult[I[v]]||[]);this.groups=JSON.parse(JSON.stringify(I)),this.result=L},buildLayout:function(){this.buildHtmlLayout(),this.buildBackdropLayout(),this.buildHintLayout(),this.options.callback.onLayoutBuiltBefore&&(this.tmpResultHtml=this.helper.executeCallback.call(this,this.options.callback.onLayoutBuiltBefore,[this.node,this.query,this.result,this.resultHtml])),this.tmpResultHtml instanceof j?this.resultContainer.html(this.tmpResultHtml):this.resultHtml instanceof j&&this.resultContainer.html(this.resultHtml),this.options.callback.onLayoutBuiltAfter&&this.helper.executeCallback.call(this,this.options.callback.onLayoutBuiltAfter,[this.node,this.query,this.result])},buildHtmlLayout:function(){if(!1!==this.options.resultContainer){var h;if(this.resultContainer||(this.resultContainer=j("<div/>",{class:this.options.selector.result}),this.container.append(this.resultContainer)),!this.result.length)if(this.options.multiselect&&this.options.multiselect.limit&&this.items.length>=this.options.multiselect.limit)h=this.options.multiselect.limitTemplate?"function"==typeof this.options.multiselect.limitTemplate?this.options.multiselect.limitTemplate.call(this,this.query):this.options.multiselect.limitTemplate.replace(/\{\{query}}/gi,j("<div>").text(this.helper.cleanStringFromScript(this.query)).html()):"Can't select more than "+this.items.length+" items.";else{if(!this.options.emptyTemplate||""===this.query)return;h="function"==typeof this.options.emptyTemplate?this.options.emptyTemplate.call(this,this.query):this.options.emptyTemplate.replace(/\{\{query}}/gi,j("<div>").text(this.helper.cleanStringFromScript(this.query)).html())}this.displayEmptyTemplate=!!h;var o=this.query.toLowerCase();this.options.accent&&(o=this.helper.removeAccent.call(this,o));var c=this,t=this.groupTemplate||"<ul></ul>",p=!1;this.groupTemplate?t=j(t.replace(/<([^>]+)>\{\{(.+?)}}<\/[^>]+>/g,function(t,e,i,s,o){var n="",r="group"===i?c.groups:[i];if(!c.result.length)return!0===p?"":(p=!0,"<"+e+' class="'+c.options.selector.empty+'">'+h+"</"+e+">");for(var a=0,l=r.length;a<l;++a)n+="<"+e+' data-group-template="'+r[a]+'"><ul></ul></'+e+">";return n})):(t=j(t),this.result.length||t.append(h instanceof j?h:'<li class="'+c.options.selector.empty+'">'+h+"</li>")),t.addClass(this.options.selector.list+(this.helper.isEmpty(this.result)?" empty":""));for(var e,i,n,s,r,a,l,u,d,f,m,g,y,v=this.groupTemplate&&this.result.length&&c.groups||[],b=0,k=this.result.length;b<k;++b)e=(n=this.result[b]).group,s=!this.options.multiselect&&this.options.source[n.group].href||this.options.href,u=[],d=this.options.source[n.group].display||this.options.display,this.options.group&&(e=n[this.options.group.key],this.options.group.template&&("function"==typeof this.options.group.template?i=this.options.group.template.call(this,n):"string"==typeof this.options.group.template&&(i=this.options.group.template.replace(/\{\{([\w\-\.]+)}}/gi,function(t,e){return c.helper.namespace.call(c,e,n,"get","")}))),t.find('[data-search-group="'+e+'"]')[0]||(this.groupTemplate?t.find('[data-group-template="'+e+'"] ul'):t).append(j("<li/>",{class:c.options.selector.group,html:j("<a/>",{href:"javascript:;",html:i||e,tabindex:-1}),"data-search-group":e}))),this.groupTemplate&&v.length&&~(m=v.indexOf(e||n.group))&&v.splice(m,1),r=j("<li/>",{class:c.options.selector.item+" "+c.options.selector.group+"-"+this.helper.slugify.call(this,e),disabled:!!n.disabled,"data-group":e,"data-index":b,html:j("<a/>",{href:s&&!n.disabled?(g=s,y=n,y.href=c.generateHref.call(c,g,y)):"javascript:;",html:function(){if(a=n.group&&c.options.source[n.group].template||c.options.template)"function"==typeof a&&(a=a.call(c,c.query,n)),l=a.replace(/\{\{([^\|}]+)(?:\|([^}]+))*}}/gi,function(t,e,i){var s=c.helper.cleanStringFromScript(String(c.helper.namespace.call(c,e,n,"get","")));return~(i=i&&i.split("|")||[]).indexOf("slugify")&&(s=c.helper.slugify.call(c,s)),~i.indexOf("raw")||!0===c.options.highlight&&o&&~d.indexOf(e)&&(s=c.helper.highlight.call(c,s,o.split(" "),c.options.accent)),s});else{for(var t=0,e=d.length;t<e;t++)void 0!==(f=/\./.test(d[t])?c.helper.namespace.call(c,d[t],n,"get",""):n[d[t]])&&""!==f&&u.push(f);l='<span class="'+c.options.selector.display+'">'+c.helper.cleanStringFromScript(String(u.join(" ")))+"</span>"}(!0===c.options.highlight&&o&&!a||"any"===c.options.highlight)&&(l=c.helper.highlight.call(c,l,o.split(" "),c.options.accent)),j(this).append(l)}})}),function(t,i,e){e.on("click",function(t,e){i.disabled?t.preventDefault():(e&&"object"==typeof e&&(t.originalEvent=e),c.options.mustSelectItem&&c.helper.isEmpty(i)?t.preventDefault():(c.options.multiselect||(c.item=i),!1!==c.helper.executeCallback.call(c,c.options.callback.onClickBefore,[c.node,j(this),i,t])&&(t.originalEvent&&t.originalEvent.defaultPrevented||t.isDefaultPrevented()||(c.options.multiselect?(c.query=c.rawQuery="",c.addMultiselectItemLayout(i)):(c.focusOnly=!0,c.query=c.rawQuery=c.getTemplateValue.call(c,i),c.isContentEditable&&(c.node.text(c.query),c.helper.setCaretAtEnd(c.node[0]))),c.hideLayout(),c.node.val(c.query).focus(),c.options.cancelButton&&c.toggleCancelButtonVisibility(),c.helper.executeCallback.call(c,c.options.callback.onClickAfter,[c.node,j(this),i,t])))))}),e.on("mouseenter",function(t){i.disabled||(c.clearActiveItem(),c.addActiveItem(j(this))),c.helper.executeCallback.call(c,c.options.callback.onEnter,[c.node,j(this),i,t])}),e.on("mouseleave",function(t){i.disabled||c.clearActiveItem(),c.helper.executeCallback.call(c,c.options.callback.onLeave,[c.node,j(this),i,t])})}(0,n,r),(this.groupTemplate?t.find('[data-group-template="'+e+'"] ul'):t).append(r);if(this.result.length&&v.length)for(b=0,k=v.length;b<k;++b)t.find('[data-group-template="'+v[b]+'"]').remove();this.resultHtml=t}},generateHref:function(t,o){var n=this;return"string"==typeof t?t=t.replace(/\{\{([^\|}]+)(?:\|([^}]+))*}}/gi,function(t,e,i){var s=n.helper.namespace.call(n,e,o,"get","");return~(i=i&&i.split("|")||[]).indexOf("slugify")&&(s=n.helper.slugify.call(n,s)),s}):"function"==typeof t&&(t=t.call(this,o)),t},getMultiselectComparedData:function(t){var e="";if(Array.isArray(this.options.multiselect.matchOn))for(var i=0,s=this.options.multiselect.matchOn.length;i<s;++i)e+=void 0!==t[this.options.multiselect.matchOn[i]]?t[this.options.multiselect.matchOn[i]]:"";else{var o=JSON.parse(JSON.stringify(t)),n=["group","matchedKey","compiled","href"];for(i=0,s=n.length;i<s;++i)delete o[n[i]];e=JSON.stringify(o)}return e},buildBackdropLayout:function(){this.options.backdrop&&(this.backdrop.container||(this.backdrop.css=j.extend({opacity:.6,filter:"alpha(opacity=60)",position:"fixed",top:0,right:0,bottom:0,left:0,"z-index":1040,"background-color":"#000"},this.options.backdrop),this.backdrop.container=j("<div/>",{class:this.options.selector.backdrop,css:this.backdrop.css}).insertAfter(this.container)),this.container.addClass("backdrop").css({"z-index":this.backdrop.css["z-index"]+1,position:"relative"}))},buildHintLayout:function(t){if(this.options.hint)if(this.node[0].scrollWidth>Math.ceil(this.node.innerWidth()))this.hint.container&&this.hint.container.val("");else{var e=this,i="",s=(t=t||this.result,this.query.toLowerCase());if(this.options.accent&&(s=this.helper.removeAccent.call(this,s)),this.hintIndex=null,this.searchGroups.length){if(this.hint.container||(this.hint.css=j.extend({"border-color":"transparent",position:"absolute",top:0,display:"inline","z-index":-1,float:"none",color:"silver","box-shadow":"none",cursor:"default","-webkit-user-select":"none","-moz-user-select":"none","-ms-user-select":"none","user-select":"none"},this.options.hint),this.hint.container=j("<"+this.node[0].nodeName+"/>",{type:this.node.attr("type"),class:this.node.attr("class"),readonly:!0,unselectable:"on","aria-hidden":"true",tabindex:-1,click:function(){e.node.focus()}}).addClass(this.options.selector.hint).css(this.hint.css).insertAfter(this.node),this.node.parent().css({position:"relative"})),this.hint.container.css("color",this.hint.css.color),s)for(var o,n,r,a=0,l=t.length;a<l;a++)if(!t[a].disabled){n=t[a].group;for(var h=0,c=(o=this.options.source[n].display||this.options.display).length;h<c;h++)if(r=String(t[a][o[h]]).toLowerCase(),this.options.accent&&(r=this.helper.removeAccent.call(this,r)),0===r.indexOf(s)){i=String(t[a][o[h]]),this.hintIndex=a;break}if(null!==this.hintIndex)break}var p=0<i.length&&this.rawQuery+i.substring(this.query.length)||"";this.hint.container.val(p),this.isContentEditable&&this.hint.container.text(p)}}},buildDropdownLayout:function(){if(this.options.dropdownFilter){var i=this;j("<span/>",{class:this.options.selector.filter,html:function(){j(this).append(j("<button/>",{type:"button",class:i.options.selector.filterButton,style:"display: none;",click:function(){i.container.toggleClass("filter");var e=i.namespace+"-dropdown-filter";j("html").off(e),i.container.hasClass("filter")&&j("html").on("click"+e+" touchend"+e,function(t){j(t.target).closest("."+i.options.selector.filter)[0]&&j(t.target).closest(i.container)[0]||i.hasDragged||(i.container.removeClass("filter"),j("html").off(e))})}})),j(this).append(j("<ul/>",{class:i.options.selector.dropdown}))}}).insertAfter(i.container.find("."+i.options.selector.query))}},buildDropdownItemLayout:function(t){if(this.options.dropdownFilter){var e,i,o=this,n="string"==typeof this.options.dropdownFilter&&this.options.dropdownFilter||"All",r=this.container.find("."+this.options.selector.dropdown);"static"!==t||!0!==this.options.dropdownFilter&&"string"!=typeof this.options.dropdownFilter||this.dropdownFilter.static.push({key:"group",template:"{{group}}",all:n,value:Object.keys(this.options.source)});for(var s=0,a=this.dropdownFilter[t].length;s<a;s++){i=this.dropdownFilter[t][s],Array.isArray(i.value)||(i.value=[i.value]),i.all&&(this.dropdownFilterAll=i.all);for(var l=0,h=i.value.length;l<=h;l++)l===h&&s!==a-1||l===h&&s===a-1&&"static"===t&&this.dropdownFilter.dynamic.length||(e=this.dropdownFilterAll||n,i.value[l]?e=i.template?i.template.replace(new RegExp("{{"+i.key+"}}","gi"),i.value[l]):i.value[l]:this.container.find("."+o.options.selector.filterButton).html(e),function(e,i,s){r.append(j("<li/>",{class:o.options.selector.dropdownItem+" "+o.helper.slugify.call(o,i.key+"-"+(i.value[e]||n)),html:j("<a/>",{href:"javascript:;",html:s,click:function(t){t.preventDefault(),c.call(o,{key:i.key,value:i.value[e]||"*",template:s})}})}))}(l,i,e))}this.dropdownFilter[t].length&&this.container.find("."+o.options.selector.filterButton).removeAttr("style")}function c(t){"*"===t.value?delete this.filters.dropdown:this.filters.dropdown=t,this.container.removeClass("filter").find("."+this.options.selector.filterButton).html(t.template),this.isDropdownEvent=!0,this.node.trigger("input"+this.namespace),this.options.multiselect&&this.adjustInputSize(),this.node.focus()}},dynamicFilter:{isEnabled:!1,init:function(){this.options.dynamicFilter&&(this.dynamicFilter.bind.call(this),this.dynamicFilter.isEnabled=!0)},validate:function(t){var e,i,s=null,o=null;for(var n in this.filters.dynamic)if(this.filters.dynamic.hasOwnProperty(n)&&(i=~n.indexOf(".")?this.helper.namespace.call(this,n,t,"get"):t[n],"|"!==this.filters.dynamic[n].modifier||s||(s=i==this.filters.dynamic[n].value||!1),"&"===this.filters.dynamic[n].modifier)){if(i!=this.filters.dynamic[n].value){o=!1;break}o=!0}return e=s,null!==o&&!0===(e=o)&&null!==s&&(e=s),!!e},set:function(t,e){var i=t.match(/^([|&])?(.+)/);e?this.filters.dynamic[i[2]]={modifier:i[1]||"|",value:e}:delete this.filters.dynamic[i[2]],this.dynamicFilter.isEnabled&&this.generateSource()},bind:function(){for(var t,e=this,i=0,s=this.options.dynamicFilter.length;i<s;i++)"string"==typeof(t=this.options.dynamicFilter[i]).selector&&(t.selector=j(t.selector)),t.selector instanceof j&&t.selector[0]&&t.key&&function(t){t.selector.off(e.namespace).on("change"+e.namespace,function(){e.dynamicFilter.set.apply(e,[t.key,e.dynamicFilter.getValue(this)])}).trigger("change"+e.namespace)}(t)},getValue:function(t){var e;return"SELECT"===t.tagName?e=t.value:"INPUT"===t.tagName&&("checkbox"===t.type?e=t.checked&&t.getAttribute("value")||t.checked||null:"radio"===t.type&&t.checked&&(e=t.value)),e}},buildMultiselectLayout:function(){if(this.options.multiselect){var t,e=this;this.label.container=j("<span/>",{class:this.options.selector.labelContainer,"data-padding-left":parseFloat(this.node.css("padding-left"))||0,"data-padding-right":parseFloat(this.node.css("padding-right"))||0,"data-padding-top":parseFloat(this.node.css("padding-top"))||0,click:function(t){j(t.target).hasClass(e.options.selector.labelContainer)&&e.node.focus()}}),this.node.closest("."+this.options.selector.query).prepend(this.label.container),this.options.multiselect.data&&(Array.isArray(this.options.multiselect.data)?this.populateMultiselectData(this.options.multiselect.data):"function"==typeof this.options.multiselect.data&&(t=this.options.multiselect.data.call(this),Array.isArray(t)?this.populateMultiselectData(t):"function"==typeof t.promise&&j.when(t).then(function(t){t&&Array.isArray(t)&&e.populateMultiselectData(t)})))}},isMultiselectUniqueData:function(t){for(var e=!0,i=0,s=this.comparedItems.length;i<s;++i)if(this.comparedItems[i]===this.getMultiselectComparedData(t)){e=!1;break}return e},populateMultiselectData:function(t){for(var e=0,i=t.length;e<i;++e)this.addMultiselectItemLayout(t[e]);this.node.trigger("search"+this.namespace,{origin:"populateMultiselectData"})},addMultiselectItemLayout:function(t){if(this.isMultiselectUniqueData(t)){this.items.push(t),this.comparedItems.push(this.getMultiselectComparedData(t));var e,i=this.getTemplateValue(t),s=this,o=this.options.multiselect.href?"a":"span",n=j("<span/>",{class:this.options.selector.label,html:j("<"+o+"/>",{text:i,click:function(t){var e=j(this).closest("."+s.options.selector.label),i=s.label.container.find("."+s.options.selector.label).index(e);s.options.multiselect.callback&&s.helper.executeCallback.call(s,s.options.multiselect.callback.onClick,[s.node,s.items[i],t])},href:this.options.multiselect.href?(e=s.items[s.items.length-1],s.generateHref.call(s,s.options.multiselect.href,e)):null})});return n.append(j("<span/>",{class:this.options.selector.cancelButton,html:"×",click:function(t){var e=j(this).closest("."+s.options.selector.label),i=s.label.container.find("."+s.options.selector.label).index(e);s.cancelMultiselectItem(i,e,t)}})),this.label.container.append(n),this.adjustInputSize(),!0}},cancelMultiselectItem:function(t,e,i){var s=this.items[t];(e=e||this.label.container.find("."+this.options.selector.label).eq(t)).remove(),this.items.splice(t,1),this.comparedItems.splice(t,1),this.options.multiselect.callback&&this.helper.executeCallback.call(this,this.options.multiselect.callback.onCancel,[this.node,s,i]),this.adjustInputSize(),this.focusOnly=!0,this.node.focus().trigger("input"+this.namespace,{origin:"cancelMultiselectItem"})},adjustInputSize:function(){var i=this.node[0].getBoundingClientRect().width-(parseFloat(this.label.container.data("padding-right"))||0)-(parseFloat(this.label.container.css("padding-left"))||0),s=0,o=0,n=0,r=!1,a=0;this.label.container.find("."+this.options.selector.label).filter(function(t,e){0===t&&(a=j(e)[0].getBoundingClientRect().height+parseFloat(j(e).css("margin-bottom")||0)),s=j(e)[0].getBoundingClientRect().width+parseFloat(j(e).css("margin-right")||0),.7*i<n+s&&!r&&(o++,r=!0),n+s<i?n+=s:(r=!1,n=s)});var t=parseFloat(this.label.container.data("padding-left")||0)+(r?0:n),e=o*a+parseFloat(this.label.container.data("padding-top")||0);this.container.find("."+this.options.selector.query).find("input, textarea, [contenteditable], .typeahead__hint").css({paddingLeft:t,paddingTop:e})},showLayout:function(){!this.container.hasClass("result")&&(this.result.length||this.displayEmptyTemplate||this.options.backdropOnFocus)&&(function(){var e=this;j("html").off("keydown"+this.namespace).on("keydown"+this.namespace,function(t){t.keyCode&&9===t.keyCode&&setTimeout(function(){j(":focus").closest(e.container).find(e.node)[0]||e.hideLayout()},0)}),j("html").off("click"+this.namespace+" touchend"+this.namespace).on("click"+this.namespace+" touchend"+this.namespace,function(t){j(t.target).closest(e.container)[0]||j(t.target).closest("."+e.options.selector.item)[0]||t.target.className===e.options.selector.cancelButton||e.hasDragged||e.hideLayout()})}.call(this),this.container.addClass([this.result.length||this.searchGroups.length&&this.displayEmptyTemplate?"result ":"",this.options.hint&&this.searchGroups.length?"hint":"",this.options.backdrop||this.options.backdropOnFocus?"backdrop":""].join(" ")),this.helper.executeCallback.call(this,this.options.callback.onShowLayout,[this.node,this.query]))},hideLayout:function(){(this.container.hasClass("result")||this.container.hasClass("backdrop"))&&(this.container.removeClass("result hint filter"+(this.options.backdropOnFocus&&j(this.node).is(":focus")?"":" backdrop")),this.options.backdropOnFocus&&this.container.hasClass("backdrop")||(j("html").off(this.namespace),this.helper.executeCallback.call(this,this.options.callback.onHideLayout,[this.node,this.query])))},resetLayout:function(){this.result=[],this.tmpResult={},this.groups=[],this.resultCount=0,this.resultCountPerGroup={},this.resultItemCount=0,this.resultHtml=null,this.options.hint&&this.hint.container&&(this.hint.container.val(""),this.isContentEditable&&this.hint.container.text(""))},resetInput:function(){this.node.val(""),this.isContentEditable&&this.node.text(""),this.query="",this.rawQuery=""},buildCancelButtonLayout:function(){if(this.options.cancelButton){var e=this;j("<span/>",{class:this.options.selector.cancelButton,html:"×",mousedown:function(t){t.stopImmediatePropagation(),t.preventDefault(),e.resetInput(),e.node.trigger("input"+e.namespace,[t])}}).insertBefore(this.node)}},toggleCancelButtonVisibility:function(){this.container.toggleClass("cancel",!!this.query.length)},__construct:function(){this.extendOptions(),this.unifySourceFormat()&&(this.dynamicFilter.init.apply(this),this.init(),this.buildDropdownLayout(),this.buildDropdownItemLayout("static"),this.buildMultiselectLayout(),this.delegateEvents(),this.buildCancelButtonLayout(),this.helper.executeCallback.call(this,this.options.callback.onReady,[this.node]))},helper:{isEmpty:function(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0},removeAccent:function(t){if("string"==typeof t){var e=o;return"object"==typeof this.options.accent&&(e=this.options.accent),t=t.toLowerCase().replace(new RegExp("["+e.from+"]","g"),function(t){return e.to[e.from.indexOf(t)]})}},slugify:function(t){return""!==(t=String(t))&&(t=(t=this.helper.removeAccent.call(this,t)).replace(/[^-a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")),t},sort:function(s,i,o){var n=function(t){for(var e=0,i=s.length;e<i;e++)if(void 0!==t[s[e]])return o(t[s[e]]);return t};return i=[-1,1][+!!i],function(t,e){return t=n(t),e=n(e),i*((e<t)-(t<e))}},replaceAt:function(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)},highlight:function(t,e,i){t=String(t);var s=i&&this.helper.removeAccent.call(this,t)||t,o=[];Array.isArray(e)||(e=[e]),e.sort(function(t,e){return e.length-t.length});for(var n=e.length-1;0<=n;n--)""!==e[n].trim()?e[n]=e[n].replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"):e.splice(n,1);s.replace(new RegExp("(?:"+e.join("|")+")(?!([^<]+)?>)","gi"),function(t,e,i){o.push({offset:i,length:t.length})});for(n=o.length-1;0<=n;n--)t=this.helper.replaceAt(t,o[n].offset,o[n].length,"<strong>"+t.substr(o[n].offset,o[n].length)+"</strong>");return t},getCaret:function(t){var e=0;if(t.selectionStart)return t.selectionStart;if(document.selection){var i=document.selection.createRange();if(null===i)return e;var s=t.createTextRange(),o=s.duplicate();s.moveToBookmark(i.getBookmark()),o.setEndPoint("EndToStart",s),e=o.text.length}else if(window.getSelection){var n=window.getSelection();if(n.rangeCount){var r=n.getRangeAt(0);r.commonAncestorContainer.parentNode==t&&(e=r.endOffset)}}return e},setCaretAtEnd:function(t){if(void 0!==window.getSelection&&void 0!==document.createRange){var e=document.createRange();e.selectNodeContents(t),e.collapse(!1);var i=window.getSelection();i.removeAllRanges(),i.addRange(e)}else if(void 0!==document.body.createTextRange){var s=document.body.createTextRange();s.moveToElementText(t),s.collapse(!1),s.select()}},cleanStringFromScript:function(t){return"string"==typeof t&&t.replace(/<\/?(?:script|iframe)\b[^>]*>/gm,"")||t},executeCallback:function(t,e){if(t){var i;if("function"==typeof t)i=t;else if(("string"==typeof t||Array.isArray(t))&&("string"==typeof t&&(t=[t,[]]),"function"!=typeof(i=this.helper.namespace.call(this,t[0],window))))return;return i.apply(this,(t[1]||[]).concat(e||[]))}},namespace:function(t,e,i,s){if("string"!=typeof t||""===t)return!1;var o=void 0!==s?s:void 0;if(!~t.indexOf("."))return e[t]||o;for(var n=t.split("."),r=e||window,a=(i=i||"get",""),l=0,h=n.length;l<h;l++){if(void 0===r[a=n[l]]){if(~["get","delete"].indexOf(i))return void 0!==s?s:void 0;r[a]={}}if(~["set","create","delete"].indexOf(i)&&l===h-1){if("set"!==i&&"create"!==i)return delete r[a],!0;r[a]=o}r=r[a]}return r},typeWatch:(i=0,function(t,e){clearTimeout(i),i=setTimeout(t,e)})}},j.fn.typeahead=j.typeahead=function(t){return e.typeahead(this,t)};var e={typeahead:function(t,e){if(e&&e.source&&"object"==typeof e.source){if("function"==typeof t){if(!e.input)return;t=j(e.input)}if(void 0===t[0].value&&(t[0].value=t.text()),t.length){if(1===t.length)return t[0].selector=t.selector||e.input||t[0].nodeName.toLowerCase(),window.Typeahead[t[0].selector]=new l(t,e);for(var i,s={},o=0,n=t.length;o<n;++o)void 0!==s[i=t[o].nodeName.toLowerCase()]&&(i+=o),t[o].selector=i,window.Typeahead[i]=s[i]=new l(t.eq(o),e);return s}}}};return window.console=window.console||{log:function(){}},Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),"trim"in String.prototype||(String.prototype.trim=function(){return this.replace(/^\s+/,"").replace(/\s+$/,"")}),"indexOf"in Array.prototype||(Array.prototype.indexOf=function(t,e){void 0===e&&(e=0),e<0&&(e+=this.length),e<0&&(e=0);for(var i=this.length;e<i;e++)if(e in this&&this[e]===t)return e;return-1}),Object.keys||(Object.keys=function(t){var e,i=[];for(e in t)Object.prototype.hasOwnProperty.call(t,e)&&i.push(e);return i}),l});