/*! Auxin WordPress Framework - v2.4.6 - 2019-07-17
 *  All required plugins 
 *  http://averta.net
 */



/*! 
 * 
 * ================== js/libs/plugins/plugins-config.js =================== 
 **/ 


if( typeof Object.create !== 'function' ){ Object.create = function (obj){ function F(){} F.prototype = obj; return new F();}; }

// config for lazysizes
window.lazySizesConfig = window.lazySizesConfig || {};
window.lazySizesConfig.lazyClass    = 'aux-preload';
window.lazySizesConfig.loadingClass = 'aux-preloading';
window.lazySizesConfig.loadedClass  = 'aux-preloaded';

// On Loading
// an event right before of the "unveil" transformation of lazyload
document.addEventListener('lazybeforeunveil', function( e ){
    var color = e.target.getAttribute( 'data-bg-color' );
    if( color ){
        e.target.style.backgroundColor = color;
    }
});

document.addEventListener('lazyloaded', function( e ){
    if( e.target.getAttribute('data-bg-color') ){
    	e.target.style.backgroundColor = 'initial';
    }
    if( e.target.classList.contains('aux-has-preload-height') ){
        e.target.classList.remove('aux-has-preload-height');
        e.target.style.height = 'auto';
    }

    // Lazyload videos
    if( e.target.nodeName === "VIDEO" ){
        var video = e.target;

        for (var source in video.children) {
            var videoSource = video.children[source];
            if ( videoSource.tagName === "SOURCE" && videoSource.getAttribute('data-src') ) {
                videoSource.src = videoSource.getAttribute('data-src');
            }
        }
        video.load();

        // autoPlay video
        if( video.classList.contains('aux-autoplay') ){
            video.play();
        }
    }
});

(function($, window, document, undefined){
    "use strict";

    var resposiveNotLoadedImages = function(){
        var width, height, lazysizeImages = document.querySelectorAll('.aux-preload');

        Array.prototype.forEach.call(lazysizeImages, function(el, i){
            if( ( width = el.getAttribute('width') ) && ( height = el.getAttribute('height') ) ){
                el.style.height = el.clientWidth/(width/height) + 'px';
                el.classList.add('aux-has-preload-height');
            }
        });
    };

    window.addEventListener("orientationchange", resposiveNotLoadedImages);
    window.addEventListener('resize', resposiveNotLoadedImages);
    $(resposiveNotLoadedImages);

})(jQuery, window, document);


/*! 
 * 
 * ================== js/libs/plugins/jquery.easing.js =================== 
 **/ 

/*
 * jQuery Easing v1.4.1 - http://gsgd.co.uk/sandbox/jquery/easing/
 * Open source under the BSD License.
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * https://raw.github.com/gdsmith/jquery-easing/master/LICENSE
*/

(function (factory) {
	if (typeof define === "function" && define.amd) {
		define(['jquery'], function ($) {
			return factory($);
		});
	} else if (typeof module === "object" && typeof module.exports === "object") {
		exports = factory(require('jquery'));
	} else {
		factory(jQuery);
	}
})(function($){

// Preserve the original jQuery "swing" easing as "jswing"
$.easing.jswing = $.easing.swing;

var pow = Math.pow,
	sqrt = Math.sqrt,
	sin = Math.sin,
	cos = Math.cos,
	PI = Math.PI,
	c1 = 1.70158,
	c2 = c1 * 1.525,
	c3 = c1 + 1,
	c4 = ( 2 * PI ) / 3,
	c5 = ( 2 * PI ) / 4.5;

// x is the fraction of animation progress, in the range 0..1
function bounceOut(x) {
	var n1 = 7.5625,
		d1 = 2.75;
	if ( x < 1/d1 ) {
		return n1*x*x;
	} else if ( x < 2/d1 ) {
		return n1*(x-=(1.5/d1))*x + 0.75;
	} else if ( x < 2.5/d1 ) {
		return n1*(x-=(2.25/d1))*x + 0.9375;
	} else {
		return n1*(x-=(2.625/d1))*x + 0.984375;
	}
}

$.extend( $.easing,
{
	def: 'easeOutQuad',
	swing: function (x) {
		return $.easing[$.easing.def](x);
	},
	easeInQuad: function (x) {
		return x * x;
	},
	easeOutQuad: function (x) {
		return 1 - ( 1 - x ) * ( 1 - x );
	},
	easeInOutQuad: function (x) {
		return x < 0.5 ?
			2 * x * x :
			1 - pow( -2 * x + 2, 2 ) / 2;
	},
	easeInCubic: function (x) {
		return x * x * x;
	},
	easeOutCubic: function (x) {
		return 1 - pow( 1 - x, 3 );
	},
	easeInOutCubic: function (x) {
		return x < 0.5 ?
			4 * x * x * x :
			1 - pow( -2 * x + 2, 3 ) / 2;
	},
	easeInQuart: function (x) {
		return x * x * x * x;
	},
	easeOutQuart: function (x) {
		return 1 - pow( 1 - x, 4 );
	},
	easeInOutQuart: function (x) {
		return x < 0.5 ?
			8 * x * x * x * x :
			1 - pow( -2 * x + 2, 4 ) / 2;
	},
	easeInQuint: function (x) {
		return x * x * x * x * x;
	},
	easeOutQuint: function (x) {
		return 1 - pow( 1 - x, 5 );
	},
	easeInOutQuint: function (x) {
		return x < 0.5 ?
			16 * x * x * x * x * x :
			1 - pow( -2 * x + 2, 5 ) / 2;
	},
	easeInSine: function (x) {
		return 1 - cos( x * PI/2 );
	},
	easeOutSine: function (x) {
		return sin( x * PI/2 );
	},
	easeInOutSine: function (x) {
		return -( cos( PI * x ) - 1 ) / 2;
	},
	easeInExpo: function (x) {
		return x === 0 ? 0 : pow( 2, 10 * x - 10 );
	},
	easeOutExpo: function (x) {
		return x === 1 ? 1 : 1 - pow( 2, -10 * x );
	},
	easeInOutExpo: function (x) {
		return x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ?
			pow( 2, 20 * x - 10 ) / 2 :
			( 2 - pow( 2, -20 * x + 10 ) ) / 2;
	},
	easeInCirc: function (x) {
		return 1 - sqrt( 1 - pow( x, 2 ) );
	},
	easeOutCirc: function (x) {
		return sqrt( 1 - pow( x - 1, 2 ) );
	},
	easeInOutCirc: function (x) {
		return x < 0.5 ?
			( 1 - sqrt( 1 - pow( 2 * x, 2 ) ) ) / 2 :
			( sqrt( 1 - pow( -2 * x + 2, 2 ) ) + 1 ) / 2;
	},
	easeInElastic: function (x) {
		return x === 0 ? 0 : x === 1 ? 1 :
			-pow( 2, 10 * x - 10 ) * sin( ( x * 10 - 10.75 ) * c4 );
	},
	easeOutElastic: function (x) {
		return x === 0 ? 0 : x === 1 ? 1 :
			pow( 2, -10 * x ) * sin( ( x * 10 - 0.75 ) * c4 ) + 1;
	},
	easeInOutElastic: function (x) {
		return x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ?
			-( pow( 2, 20 * x - 10 ) * sin( ( 20 * x - 11.125 ) * c5 )) / 2 :
			pow( 2, -20 * x + 10 ) * sin( ( 20 * x - 11.125 ) * c5 ) / 2 + 1;
	},
	easeInBack: function (x) {
		return c3 * x * x * x - c1 * x * x;
	},
	easeOutBack: function (x) {
		return 1 + c3 * pow( x - 1, 3 ) + c1 * pow( x - 1, 2 );
	},
	easeInOutBack: function (x) {
		return x < 0.5 ?
			( pow( 2 * x, 2 ) * ( ( c2 + 1 ) * 2 * x - c2 ) ) / 2 :
			( pow( 2 * x - 2, 2 ) *( ( c2 + 1 ) * ( x * 2 - 2 ) + c2 ) + 2 ) / 2;
	},
	easeInBounce: function (x) {
		return 1 - bounceOut( 1 - x );
	},
	easeOutBounce: bounceOut,
	easeInOutBounce: function (x) {
		return x < 0.5 ?
			( 1 - bounceOut( 1 - 2 * x ) ) / 2 :
			( 1 + bounceOut( 2 * x - 1 ) ) / 2;
	}
});

});


/*! 
 * 
 * ================== js/libs/plugins/jquery.debouncedresize.js =================== 
 **/ 

/*
 * debouncedresize: special jQuery event that happens once after a window resize
 *
 * latest ORIGINAL version and complete README available on Github:
 * https://github.com/louisremi/jquery-smartresize
 * latest Bower package can be found also on Github:
 * https://github.com/AndrewDryga/jQuery.Easing
 *
 * Copyright 2012 @louis_remi
 * Licensed under the MIT license.
 *
 * This saved you an hour of work?
 * Send me music http://www.amazon.co.uk/wishlist/HNTU0468LQON
 */
(function($) {

var $event = $.event,
	$special,
	resizeTimeout;

$special = $event.special.debouncedresize = {
	setup: function() {
		$( this ).on( "resize", $special.handler );
	},
	teardown: function() {
		$( this ).off( "resize", $special.handler );
	},
	handler: function( event, execAsap ) {
		// Save the context
		var context = this,
			args = arguments,
			dispatch = function() {
				// set correct event type
				event.type = "debouncedresize";
				$event.dispatch.apply( context, args );
			};

		if ( resizeTimeout ) {
			clearTimeout( resizeTimeout );
		}

		execAsap ?
			dispatch() :
			resizeTimeout = setTimeout( dispatch, $special.threshold );
	},
	threshold: 150
};

})(jQuery);


/*! 
 * 
 * ================== js/libs/plugins/jquery.fitvids.js =================== 
 **/ 

/*global jQuery */
/*jshint browser:true */
/*!
* FitVids 1.1
*
* Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
*
*/

(function( $ ){

  "use strict";

  $.fn.fitVids = function( options ) {
    var settings = {
      customSelector: null
    };

    if(!document.getElementById('fit-vids-style')) {
      // appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js
      var head = document.head || document.getElementsByTagName('head')[0];
      var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}';
      var div = document.createElement('div');
      div.innerHTML = '<p>x</p><style id="fit-vids-style">' + css + '</style>';
      head.appendChild(div.childNodes[1]);
    }

    if ( options ) {
      $.extend( settings, options );
    }

    return this.each(function(){
      var selectors = [
        "iframe[src*='player.vimeo.com']",
        "iframe[src*='youtube.com']",
        "iframe[src*='youtube-nocookie.com']",
        "iframe[src*='kickstarter.com'][src*='video.html']",
        "object",
        "embed"
      ];

      if (settings.customSelector) {
        selectors.push(settings.customSelector);
      }

      var $allVideos = $(this).find(selectors.join(','));
      $allVideos = $allVideos.not("object object"); // SwfObj conflict patch

      $allVideos.each(function(){
        var $this = $(this);
        if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
        var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
            width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
            aspectRatio = height / width;
        if(!$this.attr('id')){
          var videoID = 'fitvid' + Math.floor(Math.random()*999999);
          $this.attr('id', videoID);
        }
        $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%");
        $this.removeAttr('height').removeAttr('width');
      });
    });
  };
// Works with either jQuery or Zepto
})( window.jQuery || window.Zepto );


/*! 
 * 
 * ================== js/libs/plugins/jquery.mousewheel.js =================== 
 **/ 

/*!
 * jQuery Mousewheel 3.1.13
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix  = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
        toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
                    ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
        slice  = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    var special = $.event.special.mousewheel = {
        version: '3.1.12',

        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
            // Store the line height and page height for this particular element
            $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
            $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
            // Clean up the data we added to the element
            $.removeData(this, 'mousewheel-line-height');
            $.removeData(this, 'mousewheel-page-height');
        },

        getLineHeight: function(elem) {
            var $elem = $(elem),
                $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent']();
            if (!$parent.length) {
                $parent = $('body');
            }
            return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16;
        },

        getPageHeight: function(elem) {
            return $(elem).height();
        },

        settings: {
            adjustOldDeltas: true, // see shouldAdjustOldDeltas() below
            normalizeOffset: true  // calls getBoundingClientRect for each event
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
        },

        unmousewheel: function(fn) {
            return this.unbind('mousewheel', fn);
        }
    });


    function handler(event) {
        var orgEvent   = event || window.event,
            args       = slice.call(arguments, 1),
            delta      = 0,
            deltaX     = 0,
            deltaY     = 0,
            absDelta   = 0,
            offsetX    = 0,
            offsetY    = 0;
        event = $.event.fix(orgEvent);
        event.type = 'mousewheel';

        // Old school scrollwheel delta
        if ( 'detail'      in orgEvent ) { deltaY = orgEvent.detail * -1;      }
        if ( 'wheelDelta'  in orgEvent ) { deltaY = orgEvent.wheelDelta;       }
        if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY;      }
        if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
        if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }

        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;

        // New school wheel delta (wheel event)
        if ( 'deltaY' in orgEvent ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( 'deltaX' in orgEvent ) {
            deltaX = orgEvent.deltaX;
            if ( deltaY === 0 ) { delta  = deltaX * -1; }
        }

        // No change actually happened, no reason to go any further
        if ( deltaY === 0 && deltaX === 0 ) { return; }

        // Need to convert lines and pages to pixels if we aren't already in pixels
        // There are three delta modes:
        //   * deltaMode 0 is by pixels, nothing to do
        //   * deltaMode 1 is by lines
        //   * deltaMode 2 is by pages
        if ( orgEvent.deltaMode === 1 ) {
            var lineHeight = $.data(this, 'mousewheel-line-height');
            delta  *= lineHeight;
            deltaY *= lineHeight;
            deltaX *= lineHeight;
        } else if ( orgEvent.deltaMode === 2 ) {
            var pageHeight = $.data(this, 'mousewheel-page-height');
            delta  *= pageHeight;
            deltaY *= pageHeight;
            deltaX *= pageHeight;
        }

        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );

        if ( !lowestDelta || absDelta < lowestDelta ) {
            lowestDelta = absDelta;

            // Adjust older deltas if necessary
            if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
                lowestDelta /= 40;
            }
        }

        // Adjust older deltas if necessary
        if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
            // Divide all the things by 40!
            delta  /= 40;
            deltaX /= 40;
            deltaY /= 40;
        }

        // Get a whole, normalized value for the deltas
        delta  = Math[ delta  >= 1 ? 'floor' : 'ceil' ](delta  / lowestDelta);
        deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
        deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);

        // Normalise offsetX and offsetY properties
        if ( special.settings.normalizeOffset && this.getBoundingClientRect ) {
            var boundingRect = this.getBoundingClientRect();
            offsetX = event.clientX - boundingRect.left;
            offsetY = event.clientY - boundingRect.top;
        }

        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;
        event.offsetX = offsetX;
        event.offsetY = offsetY;
        // Go ahead and set deltaMode to 0 since we converted to pixels
        // Although this is a little odd since we overwrite the deltaX/Y
        // properties with normalized deltas.
        event.deltaMode = 0;

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
        nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

    function nullLowestDelta() {
        lowestDelta = null;
    }

    function shouldAdjustOldDeltas(orgEvent, absDelta) {
        // If this is an older event and the delta is divisable by 120,
        // then we are assuming that the browser is treating this as an
        // older mouse wheel event and that we should divide the deltas
        // by 40 to try and get a more usable deltaFactor.
        // Side note, this actually impacts the reported scroll distance
        // in older browsers and can cause scrolling to be slower than native.
        // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
        return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
    }

}));


/*! 
 * 
 * ================== js/libs/plugins/jquery.twbsPagination.js =================== 
 **/ 

/*!
 * jQuery pagination plugin v1.2.6
 * http://esimakin.github.io/twbs-pagination/
 *
 * Copyright 2014, Eugene Simakin
 * Released under Apache 2.0 license
 * http://apache.org/licenses/LICENSE-2.0.html
 */
(function ($, window, document, undefined) {

    'use strict';

    var old = $.fn.twbsPagination;

    // PROTOTYPE AND CONSTRUCTOR

    var TwbsPagination = function (element, options) {
        this.$element = $(element);
        this.options = $.extend({}, $.fn.twbsPagination.defaults, options);

        if (this.options.startPage < 1 || this.options.startPage > this.options.totalPages) {
            throw new Error('Start page option is incorrect');
        }

        this.options.totalPages = parseInt(this.options.totalPages);
        if (isNaN(this.options.totalPages)) {
            throw new Error('Total pages option is not correct!');
        }

        this.options.visiblePages = parseInt(this.options.visiblePages);
        if (isNaN(this.options.visiblePages)) {
            throw new Error('Visible pages option is not correct!');
        }

        if (this.options.totalPages < this.options.visiblePages) {
            this.options.visiblePages = this.options.totalPages;
        }

        if (this.options.onPageClick instanceof Function) {
            this.$element.first().on('page', this.options.onPageClick);
        }

        if (this.options.href) {
            var match, regexp = this.options.href.replace(/[-\/\\^$*+?.|[\]]/g, '\\$&');
            regexp = regexp.replace(this.options.hrefVariable, '(\\d+)');
            if ((match = new RegExp(regexp, 'i').exec(window.location.href)) != null) {
                this.options.startPage = parseInt(match[1], 10);
            }
        }

        var tagName = (typeof this.$element.prop === 'function') ?
            this.$element.prop('tagName') : this.$element.attr('tagName');

        if (tagName === 'UL') {
            this.$listContainer = this.$element;
        } else {
            this.$listContainer = $('<ul></ul>');
        }

        this.$listContainer.addClass(this.options.paginationClass);

        if (tagName !== 'UL') {
            this.$element.append(this.$listContainer);
        }

        this.render(this.getPages(this.options.startPage));
        this.setupEvents();

        if (this.options.initiateStartPageClick) {
            this.$element.trigger('page', this.options.startPage);
        }

        return this;
    };

    TwbsPagination.prototype = {

        constructor: TwbsPagination,

        destroy: function () {
            this.$element.empty();
            this.$element.removeData('twbs-pagination');
            this.$element.off('page');

            return this;
        },

        show: function (page) {
            if (page < 1 || page > this.options.totalPages) {
                throw new Error('Page is incorrect.');
            }

            this.render(this.getPages(page));
            this.setupEvents();

            this.$element.trigger('page', page);

            return this;
        },

        buildListItems: function (pages) {
            var listItems = [];

            if (this.options.first) {
                listItems.push(this.buildItem('first', 1));
            }

            if (this.options.prev) {
                var prev = pages.currentPage > 1 ? pages.currentPage - 1 : this.options.loop ? this.options.totalPages  : 1;
                listItems.push(this.buildItem('prev', prev));
            }

            for (var i = 0; i < pages.numeric.length; i++) {
                listItems.push(this.buildItem('page', pages.numeric[i]));
            }

            if (this.options.next) {
                var next = pages.currentPage < this.options.totalPages ? pages.currentPage + 1 : this.options.loop ? 1 : this.options.totalPages;
                listItems.push(this.buildItem('next', next));
            }

            if (this.options.last) {
                listItems.push(this.buildItem('last', this.options.totalPages));
            }

            return listItems;
        },

        buildItem: function (type, page) {
            var $itemContainer = $('<li></li>'),
                $itemContent = $('<a></a>'),
                itemText = null;

            switch (type) {
                case 'page':
                    itemText = page;
                    $itemContainer.addClass(this.options.pageClass);
                    break;
                case 'first':
                    itemText = this.options.first;
                    $itemContainer.addClass(this.options.firstClass);
                    break;
                case 'prev':
                    itemText = this.options.prev;
                    $itemContainer.addClass(this.options.prevClass);
                    break;
                case 'next':
                    itemText = this.options.next;
                    $itemContainer.addClass(this.options.nextClass);
                    break;
                case 'last':
                    itemText = this.options.last;
                    $itemContainer.addClass(this.options.lastClass);
                    break;
                default:
                    break;
            }

            $itemContainer.data('page', page);
            $itemContainer.data('page-type', type);
            $itemContainer.append($itemContent.attr('href', this.makeHref(page)).html(itemText));

            return $itemContainer;
        },

        getPages: function (currentPage) {
            var pages = [];

            var half = Math.floor(this.options.visiblePages / 2);
            var start = currentPage - half + 1 - this.options.visiblePages % 2;
            var end = currentPage + half;

            // handle boundary case
            if (start <= 0) {
                start = 1;
                end = this.options.visiblePages;
            }
            if (end > this.options.totalPages) {
                start = this.options.totalPages - this.options.visiblePages + 1;
                end = this.options.totalPages;
            }

            var itPage = start;
            while (itPage <= end) {
                pages.push(itPage);
                itPage++;
            }

            return {"currentPage": currentPage, "numeric": pages};
        },

        render: function (pages) {
            var _this = this;
            this.$listContainer.children().remove();
            this.$listContainer.append(this.buildListItems(pages));

            this.$listContainer.children().each(function () {
                var $this = $(this),
                    pageType = $this.data('page-type');

                switch (pageType) {
                    case 'page':
                        if ($this.data('page') === pages.currentPage) {
                            $this.addClass(_this.options.activeClass);
                        }
                        break;
                    case 'first':
                            $this.toggleClass(_this.options.disabledClass, pages.currentPage === 1);
                        break;
                    case 'last':
                            $this.toggleClass(_this.options.disabledClass, pages.currentPage === _this.options.totalPages);
                        break;
                    case 'prev':
                            $this.toggleClass(_this.options.disabledClass, !_this.options.loop && pages.currentPage === 1);
                        break;
                    case 'next':
                            $this.toggleClass(_this.options.disabledClass,
                                !_this.options.loop && pages.currentPage === _this.options.totalPages);
                        break;
                    default:
                        break;
                }

            });
        },

        setupEvents: function () {
            var _this = this;
            this.$listContainer.find('li').each(function () {
                var $this = $(this);
                $this.off();
                if ($this.hasClass(_this.options.disabledClass) || $this.hasClass(_this.options.activeClass)) {
                    $this.on('click', false);
                    return;
                }
                $this.click(function (evt) {
                    // Prevent click event if href is not set.
                    !_this.options.href && evt.preventDefault();
                    _this.show(parseInt($this.data('page')));
                });
            });
        },

        makeHref: function (c) {
            return this.options.href ? this.options.href.replace(this.options.hrefVariable, c) : "#";
        }

    };

    // PLUGIN DEFINITION

    $.fn.twbsPagination = function (option) {
        var args = Array.prototype.slice.call(arguments, 1);
        var methodReturn;

        var $this = $(this);
        var data = $this.data('twbs-pagination');
        var options = typeof option === 'object' && option;

        if (!data) $this.data('twbs-pagination', (data = new TwbsPagination(this, options) ));
        if (typeof option === 'string') methodReturn = data[ option ].apply(data, args);

        return ( methodReturn === undefined ) ? $this : methodReturn;
    };

    $.fn.twbsPagination.defaults = {
        totalPages: 0,
        startPage: 1,
        visiblePages: 5,
        initiateStartPageClick: true,
        href: false,
        hrefVariable: '{{number}}',
        first: 'First',
        prev: 'Previous',
        next: 'Next',
        last: 'Last',
        loop: false,
        onPageClick: null,
        paginationClass: 'pagination',
        nextClass: 'next',
        prevClass: 'prev',
        lastClass: 'last',
        firstClass: 'first',
        pageClass: 'page',
        activeClass: 'active',
        disabledClass: 'disabled'
    };

    $.fn.twbsPagination.Constructor = TwbsPagination;

    $.fn.twbsPagination.noConflict = function () {
        $.fn.twbsPagination = old;
        return this;
    };

})(window.jQuery, window, document);


/*! 
 * 
 * ================== js/libs/plugins/tilt.jquery.js =================== 
 **/ 

'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if ((typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function (root, jQuery) {
            if (jQuery === undefined) {
                // require('jQuery') returns a factory that requires window to
                // build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop
                // if it's defined (how jquery works)
                if (typeof window !== 'undefined') {
                    jQuery = require('jquery');
                } else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        // Browser globals
        factory(jQuery);
    }
})(function ($) {
    $.fn.tilt = function (options) {

        /**
         * RequestAnimationFrame
         */
        var requestTick = function requestTick() {
            if (this.ticking) return;
            requestAnimationFrame(updateTransforms.bind(this));
            this.ticking = true;
        };

        /**
         * Bind mouse movement evens on instance
         */
        var bindEvents = function bindEvents() {
            var _this = this;
            $(this).on('mousemove', mouseMove);
            $(this).on('mouseenter', mouseEnter);
            if (this.settings.reset) $(this).on('mouseleave', mouseLeave);
            if (this.settings.glare) $(window).on('resize', updateGlareSize.bind(_this));
        };

        /**
         * Set transition only on mouse leave and mouse enter so it doesn't influence mouse move transforms
         */
        var setTransition = function setTransition() {
            var _this2 = this;

            if (this.timeout !== undefined) clearTimeout(this.timeout);
            $(this).css({ 'transition': this.settings.speed + 'ms ' + this.settings.easing });
            if (this.settings.glare) this.glareElement.css({ 'transition': 'opacity ' + this.settings.speed + 'ms ' + this.settings.easing });
            this.timeout = setTimeout(function () {
                $(_this2).css({ 'transition': '' });
                if (_this2.settings.glare) _this2.glareElement.css({ 'transition': '' });
            }, this.settings.speed);
        };

        /**
         * When user mouse enters tilt element
         */
        var mouseEnter = function mouseEnter(event) {
            this.ticking = false;
            $(this).css({ 'will-change': 'transform' });
            setTransition.call(this);

            // Trigger change event
            $(this).trigger("tilt.mouseEnter");
        };

        /**
         * Return the x,y position of the mouse on the tilt element
         * @returns {{x: *, y: *}}
         */
        var getMousePositions = function getMousePositions(event) {
            if (typeof event === "undefined") {
                event = {
                    pageX: $(this).offset().left + $(this).outerWidth() / 2,
                    pageY: $(this).offset().top + $(this).outerHeight() / 2
                };
            }
            return { x: event.pageX, y: event.pageY };
        };

        /**
         * When user mouse moves over the tilt element
         */
        var mouseMove = function mouseMove(event) {
            this.mousePositions = getMousePositions(event);
            requestTick.call(this);
        };

        /**
         * When user mouse leaves tilt element
         */
        var mouseLeave = function mouseLeave() {
            setTransition.call(this);
            this.reset = true;
            requestTick.call(this);

            // Trigger change event
            $(this).trigger("tilt.mouseLeave");
        };

        /**
         * Get tilt values
         *
         * @returns {{x: tilt value, y: tilt value}}
         */
        var getValues = function getValues() {
            var reverse = this.settings.reverse ? 1 : -1;
            var width = $(this).outerWidth();
            var height = $(this).outerHeight();
            var left = $(this).offset().left;
            var top = $(this).offset().top;
            var percentageX = (this.mousePositions.x - left) / width;
            var percentageY = (this.mousePositions.y - top) / height;
            // x or y position inside instance / width of instance = percentage of position inside instance * the max tilt value
            var tiltX = (this.settings.maxTilt / 2 - percentageX * this.settings.maxTilt).toFixed(2);
            var tiltY = (percentageY * this.settings.maxTilt - this.settings.maxTilt / 2).toFixed(2);
            // angle
            var angle = Math.atan2(this.mousePositions.x - (left + width / 2), -(this.mousePositions.y - (top + height / 2))) * (180 / Math.PI);
            // Return x & y tilt values
            return { tiltX: reverse * tiltX, tiltY: reverse * tiltY, 'percentageX': percentageX * 100, 'percentageY': percentageY * 100, angle: angle };
        };

        /**
         * Update tilt transforms on mousemove
         */
        var updateTransforms = function updateTransforms() {
            this.transforms = getValues.call(this);

            if (this.reset) {
                this.reset = false;
                $(this).css('transform', 'perspective(' + this.settings.perspective + 'px) rotateX(0deg) rotateY(0deg)');

                // Rotate glare if enabled
                if (this.settings.glare) {
                    this.glareElement.css('transform', 'rotate(180deg) translate(-50%, -50%)');
                    this.glareElement.css('opacity', '0');
                }

                return;
            } else {
                $(this).css('transform', 'perspective(' + this.settings.perspective + 'px) rotateX(' + (this.settings.disableAxis === 'x' ? 0 : this.transforms.tiltY) + 'deg) rotateY(' + (this.settings.disableAxis === 'y' ? 0 : this.transforms.tiltX) + 'deg) scale3d(' + this.settings.scale + ',' + this.settings.scale + ',' + this.settings.scale + ')');

                // Rotate glare if enabled
                if (this.settings.glare) {
                    this.glareElement.css('transform', 'rotate(' + this.transforms.angle + 'deg) translate(-50%, -50%)');
                    this.glareElement.css('opacity', '' + this.transforms.percentageY * this.settings.maxGlare / 100);
                }
            }

            // Trigger change event
            $(this).trigger("change", [this.transforms]);

            this.ticking = false;
        };

        /**
         * Prepare elements
         */
        var prepareGlare = function prepareGlare() {
            var glarePrerender = this.settings.glarePrerender;

            // If option pre-render is enabled we assume all html/css is present for an optimal glare effect.
            if (!glarePrerender)
                // Create glare element
                $(this).append('<div class="js-tilt-glare"><div class="js-tilt-glare-inner"></div></div>');

            // Store glare selector if glare is enabled
            this.glareElementWrapper = $(this).find(".js-tilt-glare");
            this.glareElement = $(this).find(".js-tilt-glare-inner");

            // Remember? We assume all css is already set, so just return
            if (glarePrerender) return;

            // Abstracted re-usable glare styles
            var stretch = {
                'position': 'absolute',
                'top': '0',
                'left': '0',
                'width': '100%',
                'height': '100%'
            };

            // Style glare wrapper
            this.glareElementWrapper.css(stretch).css({
                'overflow': 'hidden',
                'pointer-events': 'none'
            });

            // Style glare element
            this.glareElement.css({
                'position': 'absolute',
                'top': '50%',
                'left': '50%',
                'background-image': 'linear-gradient(0deg, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%)',
                'width': '' + $(this).outerWidth() * 2,
                'height': '' + $(this).outerWidth() * 2,
                'transform': 'rotate(180deg) translate(-50%, -50%)',
                'transform-origin': '0% 0%',
                'opacity': '0'
            });
        };

        /**
         * Update glare on resize
         */
        var updateGlareSize = function updateGlareSize() {
            this.glareElement.css({
                'width': '' + $(this).outerWidth() * 2,
                'height': '' + $(this).outerWidth() * 2
            });
        };

        /**
         * Public methods
         */
        $.fn.tilt.destroy = function () {
            $(this).each(function () {
                $(this).find('.js-tilt-glare').remove();
                $(this).css({ 'will-change': '', 'transform': '' });
                $(this).off('mousemove mouseenter mouseleave');
            });
        };

        $.fn.tilt.getValues = function () {
            var results = [];
            $(this).each(function () {
                this.mousePositions = getMousePositions.call(this);
                results.push(getValues.call(this));
            });
            return results;
        };

        $.fn.tilt.reset = function () {
            $(this).each(function () {
                var _this3 = this;

                this.mousePositions = getMousePositions.call(this);
                this.settings = $(this).data('settings');
                mouseLeave.call(this);
                setTimeout(function () {
                    _this3.reset = false;
                }, this.settings.transition);
            });
        };

        /**
         * Loop every instance
         */
        return this.each(function () {
            var _this4 = this;

            /**
             * Default settings merged with user settings
             * Can be set trough data attributes or as parameter.
             * @type {*}
             */
            this.settings = $.extend({
                maxTilt: $(this).is('[data-tilt-max]') ? $(this).data('tilt-max') : 20,
                perspective: $(this).is('[data-tilt-perspective]') ? $(this).data('tilt-perspective') : 300,
                easing: $(this).is('[data-tilt-easing]') ? $(this).data('tilt-easing') : 'cubic-bezier(.03,.98,.52,.99)',
                scale: $(this).is('[data-tilt-scale]') ? $(this).data('tilt-scale') : '1',
                speed: $(this).is('[data-tilt-speed]') ? $(this).data('tilt-speed') : '400',
                transition: $(this).is('[data-tilt-transition]') ? $(this).data('tilt-transition') : true,
                disableAxis: $(this).is('[data-tilt-disable-axis]') ? $(this).data('tilt-disable-axis') : null,
                axis: $(this).is('[data-tilt-axis]') ? $(this).data('tilt-axis') : null,
                reset: $(this).is('[data-tilt-reset]') ? $(this).data('tilt-reset') : true,
                glare: $(this).is('[data-tilt-glare]') ? $(this).data('tilt-glare') : false,
                maxGlare: $(this).is('[data-tilt-maxglare]') ? $(this).data('tilt-maxglare') : 1,
                reverse: $(this).is('[data-tilt-reverse]') ? $(this).data('tilt-reverse') : false,
               
            }, options);

            // Add deprecation warning & set disableAxis to deprecated axis setting
            if (this.settings.axis !== null) {
                console.warn('Tilt.js: the axis setting has been renamed to disableAxis. See https://github.com/gijsroge/tilt.js/pull/26 for more information');
                this.settings.disableAxis = this.settings.axis;
            }

            this.init = function () {
                // Store settings
                $(_this4).data('settings', _this4.settings);

                // Prepare element
                if (_this4.settings.glare) prepareGlare.call(_this4);

                // Bind events
                bindEvents.call(_this4);
            };

            // Init
            this.init();
        });
    };

    /**
     * Auto load
     */
    $('[data-tilt]').tilt();

    return true;
});
//# sourceMappingURL=tilt.jquery.js.map
;


/*! 
 * 
 * ================== js/libs/plugins/jquery.matchHeight.js =================== 
 **/ 

/**
* jquery-match-height 0.7.0 by @liabru
* http://brm.io/jquery-match-height/
* License: MIT
*/

;(function(factory) { // eslint-disable-line no-extra-semi
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof module !== 'undefined' && module.exports) {
        // CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Global
        factory(jQuery);
    }
})(function($) {
    /*
    *  internal
    */

    var _previousResizeWidth = -1,
        _updateTimeout = -1;

    /*
    *  _parse
    *  value parse utility function
    */

    var _parse = function(value) {
        // parse value and convert NaN to 0
        return parseFloat(value) || 0;
    };

    /*
    *  _rows
    *  utility function returns array of jQuery selections representing each row
    *  (as displayed after float wrapping applied by browser)
    */

    var _rows = function(elements) {
        var tolerance = 1,
            $elements = $(elements),
            lastTop = null,
            rows = [];

        // group elements by their top position
        $elements.each(function(){
            var $that = $(this),
                top = $that.offset().top - _parse($that.css('margin-top')),
                lastRow = rows.length > 0 ? rows[rows.length - 1] : null;

            if (lastRow === null) {
                // first item on the row, so just push it
                rows.push($that);
            } else {
                // if the row top is the same, add to the row group
                if (Math.floor(Math.abs(lastTop - top)) <= tolerance) {
                    rows[rows.length - 1] = lastRow.add($that);
                } else {
                    // otherwise start a new row group
                    rows.push($that);
                }
            }

            // keep track of the last row top
            lastTop = top;
        });

        return rows;
    };

    /*
    *  _parseOptions
    *  handle plugin options
    */

    var _parseOptions = function(options) {
        var opts = {
            byRow: true,
            property: 'height',
            target: null,
            remove: false
        };

        if (typeof options === 'object') {
            return $.extend(opts, options);
        }

        if (typeof options === 'boolean') {
            opts.byRow = options;
        } else if (options === 'remove') {
            opts.remove = true;
        }

        return opts;
    };

    /*
    *  matchHeight
    *  plugin definition
    */

    var matchHeight = $.fn.matchHeight = function(options) {
        var opts = _parseOptions(options);

        // handle remove
        if (opts.remove) {
            var that = this;

            // remove fixed height from all selected elements
            this.css(opts.property, '');

            // remove selected elements from all groups
            $.each(matchHeight._groups, function(key, group) {
                group.elements = group.elements.not(that);
            });

            // TODO: cleanup empty groups

            return this;
        }

        if (this.length <= 1 && !opts.target) {
            return this;
        }

        // keep track of this group so we can re-apply later on load and resize events
        matchHeight._groups.push({
            elements: this,
            options: opts
        });

        // match each element's height to the tallest element in the selection
        matchHeight._apply(this, opts);

        return this;
    };

    /*
    *  plugin global options
    */

    matchHeight.version = '0.7.0';
    matchHeight._groups = [];
    matchHeight._throttle = 80;
    matchHeight._maintainScroll = false;
    matchHeight._beforeUpdate = null;
    matchHeight._afterUpdate = null;
    matchHeight._rows = _rows;
    matchHeight._parse = _parse;
    matchHeight._parseOptions = _parseOptions;

    /*
    *  matchHeight._apply
    *  apply matchHeight to given elements
    */

    matchHeight._apply = function(elements, options) {
        var opts = _parseOptions(options),
            $elements = $(elements),
            rows = [$elements];

        // take note of scroll position
        var scrollTop = $(window).scrollTop(),
            htmlHeight = $('html').outerHeight(true);

        // get hidden parents
        var $hiddenParents = $elements.parents().filter(':hidden');

        // cache the original inline style
        $hiddenParents.each(function() {
            var $that = $(this);
            $that.data('style-cache', $that.attr('style'));
        });

        // temporarily must force hidden parents visible
        $hiddenParents.css('display', 'block');

        // get rows if using byRow, otherwise assume one row
        if (opts.byRow && !opts.target) {

            // must first force an arbitrary equal height so floating elements break evenly
            $elements.each(function() {
                var $that = $(this),
                    display = $that.css('display');

                // temporarily force a usable display value
                if (display !== 'inline-block' && display !== 'flex' && display !== 'inline-flex') {
                    display = 'block';
                }

                // cache the original inline style
                $that.data('style-cache', $that.attr('style'));

                $that.css({
                    'display': display,
                    'padding-top': '0',
                    'padding-bottom': '0',
                    'margin-top': '0',
                    'margin-bottom': '0',
                    'border-top-width': '0',
                    'border-bottom-width': '0',
                    'height': '100px',
                    'overflow': 'hidden'
                });
            });

            // get the array of rows (based on element top position)
            rows = _rows($elements);

            // revert original inline styles
            $elements.each(function() {
                var $that = $(this);
                $that.attr('style', $that.data('style-cache') || '');
            });
        }

        $.each(rows, function(key, row) {
            var $row = $(row),
                targetHeight = 0;

            if (!opts.target) {
                // skip apply to rows with only one item
                if (opts.byRow && $row.length <= 1) {
                    $row.css(opts.property, '');
                    return;
                }

                // iterate the row and find the max height
                $row.each(function(){
                    var $that = $(this),
                        style = $that.attr('style'),
                        display = $that.css('display');

                    // temporarily force a usable display value
                    if (display !== 'inline-block' && display !== 'flex' && display !== 'inline-flex') {
                        display = 'block';
                    }

                    // ensure we get the correct actual height (and not a previously set height value)
                    var css = { 'display': display };
                    css[opts.property] = '';
                    $that.css(css);

                    // find the max height (including padding, but not margin)
                    if ($that.outerHeight(false) > targetHeight) {
                        targetHeight = $that.outerHeight(false);
                    }

                    // revert styles
                    if (style) {
                        $that.attr('style', style);
                    } else {
                        $that.css('display', '');
                    }
                });
            } else {
                // if target set, use the height of the target element
                targetHeight = opts.target.outerHeight(false);
            }

            // iterate the row and apply the height to all elements
            $row.each(function(){
                var $that = $(this),
                    verticalPadding = 0;

                // don't apply to a target
                if (opts.target && $that.is(opts.target)) {
                    return;
                }

                // handle padding and border correctly (required when not using border-box)
                if ($that.css('box-sizing') !== 'border-box') {
                    verticalPadding += _parse($that.css('border-top-width')) + _parse($that.css('border-bottom-width'));
                    verticalPadding += _parse($that.css('padding-top')) + _parse($that.css('padding-bottom'));
                }

                // set the height (accounting for padding and border)
                $that.css(opts.property, (targetHeight - verticalPadding) + 'px');
            });
        });

        // revert hidden parents
        $hiddenParents.each(function() {
            var $that = $(this);
            $that.attr('style', $that.data('style-cache') || null);
        });

        // restore scroll position if enabled
        if (matchHeight._maintainScroll) {
            $(window).scrollTop((scrollTop / htmlHeight) * $('html').outerHeight(true));
        }

        return this;
    };

    /*
    *  matchHeight._applyDataApi
    *  applies matchHeight to all elements with a data-match-height attribute
    */

    matchHeight._applyDataApi = function() {
        var groups = {};

        // generate groups by their groupId set by elements using data-match-height
        $('[data-match-height], [data-mh]').each(function() {
            var $this = $(this),
                groupId = $this.attr('data-mh') || $this.attr('data-match-height');

            if (groupId in groups) {
                groups[groupId] = groups[groupId].add($this);
            } else {
                groups[groupId] = $this;
            }
        });

        // apply matchHeight to each group
        $.each(groups, function() {
            this.matchHeight(true);
        });
    };

    /*
    *  matchHeight._update
    *  updates matchHeight on all current groups with their correct options
    */

    var _update = function(event) {
        if (matchHeight._beforeUpdate) {
            matchHeight._beforeUpdate(event, matchHeight._groups);
        }

        $.each(matchHeight._groups, function() {
            matchHeight._apply(this.elements, this.options);
        });

        if (matchHeight._afterUpdate) {
            matchHeight._afterUpdate(event, matchHeight._groups);
        }
    };

    matchHeight._update = function(throttle, event) {
        // prevent update if fired from a resize event
        // where the viewport width hasn't actually changed
        // fixes an event looping bug in IE8
        if (event && event.type === 'resize') {
            var windowWidth = $(window).width();
            if (windowWidth === _previousResizeWidth) {
                return;
            }
            _previousResizeWidth = windowWidth;
        }

        // throttle updates
        if (!throttle) {
            _update(event);
        } else if (_updateTimeout === -1) {
            _updateTimeout = setTimeout(function() {
                _update(event);
                _updateTimeout = -1;
            }, matchHeight._throttle);
        }
    };

    /*
    *  bind events
    */

    // apply on DOM ready event
    $(matchHeight._applyDataApi);

    // update heights on load and resize events
    $(window).bind('load', function(event) {
        matchHeight._update(false, event);
    });

    // throttled update heights on resize events
    $(window).bind('resize orientationchange', function(event) {
        matchHeight._update(true, event);
    });

});


/*! 
 * 
 * ================== js/libs/plugins/jquery.placeholder.js =================== 
 **/ 

/*!
 * jQuery Placeholder Plugin v2.3.1
 * https://github.com/mathiasbynens/jquery-placeholder
 *
 * Copyright 2011, 2015 Mathias Bynens
 * Released under the MIT license
 */
(function(factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {

    /****
     * Allows plugin behavior simulation in modern browsers for easier debugging. 
     * When setting to true, use attribute "placeholder-x" rather than the usual "placeholder" in your inputs/textareas 
     * i.e. <input type="text" placeholder-x="my placeholder text" />
     */
    var debugMode = false; 

    // Opera Mini v7 doesn't support placeholder although its DOM seems to indicate so
    var isOperaMini = Object.prototype.toString.call(window.operamini) === '[object OperaMini]';
    var isInputSupported = 'placeholder' in document.createElement('input') && !isOperaMini && !debugMode;
    var isTextareaSupported = 'placeholder' in document.createElement('textarea') && !isOperaMini && !debugMode;
    var valHooks = $.valHooks;
    var propHooks = $.propHooks;
    var hooks;
    var placeholder;
    var settings = {};

    if (isInputSupported && isTextareaSupported) {

        placeholder = $.fn.placeholder = function() {
            return this;
        };

        placeholder.input = true;
        placeholder.textarea = true;

    } else {

        placeholder = $.fn.placeholder = function(options) {

            var defaults = {customClass: 'placeholder'};
            settings = $.extend({}, defaults, options);

            return this.filter((isInputSupported ? 'textarea' : ':input') + '[' + (debugMode ? 'placeholder-x' : 'placeholder') + ']')
                .not('.'+settings.customClass)
                .not(':radio, :checkbox, [type=hidden]')
                .bind({
                    'focus.placeholder': clearPlaceholder,
                    'blur.placeholder': setPlaceholder
                })
                .data('placeholder-enabled', true)
                .trigger('blur.placeholder');
        };

        placeholder.input = isInputSupported;
        placeholder.textarea = isTextareaSupported;

        hooks = {
            'get': function(element) {

                var $element = $(element);
                var $passwordInput = $element.data('placeholder-password');

                if ($passwordInput) {
                    return $passwordInput[0].value;
                }

                return $element.data('placeholder-enabled') && $element.hasClass(settings.customClass) ? '' : element.value;
            },
            'set': function(element, value) {

                var $element = $(element);
                var $replacement;
                var $passwordInput;

                if (value !== '') {

                    $replacement = $element.data('placeholder-textinput');
                    $passwordInput = $element.data('placeholder-password');

                    if ($replacement) {
                        clearPlaceholder.call($replacement[0], true, value) || (element.value = value);
                        $replacement[0].value = value;

                    } else if ($passwordInput) {
                        clearPlaceholder.call(element, true, value) || ($passwordInput[0].value = value);
                        element.value = value;
                    }
                }

                if (!$element.data('placeholder-enabled')) {
                    element.value = value;
                    return $element;
                }

                if (value === '') {
                    
                    element.value = value;
                    
                    // Setting the placeholder causes problems if the element continues to have focus.
                    if (element != safeActiveElement()) {
                        // We can't use `triggerHandler` here because of dummy text/password inputs :(
                        setPlaceholder.call(element);
                    }

                } else {
                    
                    if ($element.hasClass(settings.customClass)) {
                        clearPlaceholder.call(element);
                    }

                    element.value = value;
                }
                // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
                return $element;
            }
        };

        if (!isInputSupported) {
            valHooks.input = hooks;
            propHooks.value = hooks;
        }

        if (!isTextareaSupported) {
            valHooks.textarea = hooks;
            propHooks.value = hooks;
        }

        $(function() {
            // Look for forms
            $(document).delegate('form', 'submit.placeholder', function() {
                
                // Clear the placeholder values so they don't get submitted
                var $inputs = $('.'+settings.customClass, this).each(function() {
                    clearPlaceholder.call(this, true, '');
                });

                setTimeout(function() {
                    $inputs.each(setPlaceholder);
                }, 10);
            });
        });

        // Clear placeholder values upon page reload
        $(window).bind('beforeunload.placeholder', function() {

            var clearPlaceholders = true;

            try {
                // Prevent IE javascript:void(0) anchors from causing cleared values
                if (document.activeElement.toString() === 'javascript:void(0)') {
                    clearPlaceholders = false;
                }
            } catch (exception) { }

            if (clearPlaceholders) {
                $('.'+settings.customClass).each(function() {
                    this.value = '';
                });
            }
        });
    }

    function args(elem) {
        // Return an object of element attributes
        var newAttrs = {};
        var rinlinejQuery = /^jQuery\d+$/;

        $.each(elem.attributes, function(i, attr) {
            if (attr.specified && !rinlinejQuery.test(attr.name)) {
                newAttrs[attr.name] = attr.value;
            }
        });

        return newAttrs;
    }

    function clearPlaceholder(event, value) {
        
        var input = this;
        var $input = $(this);
        
        if (input.value === $input.attr((debugMode ? 'placeholder-x' : 'placeholder')) && $input.hasClass(settings.customClass)) {
            
            input.value = '';
            $input.removeClass(settings.customClass);

            if ($input.data('placeholder-password')) {

                $input = $input.hide().nextAll('input[type="password"]:first').show().attr('id', $input.removeAttr('id').data('placeholder-id'));
                
                // If `clearPlaceholder` was called from `$.valHooks.input.set`
                if (event === true) {
                    $input[0].value = value;

                    return value;
                }

                $input.focus();

            } else {
                input == safeActiveElement() && input.select();
            }
        }
    }

    function setPlaceholder(event) {
        var $replacement;
        var input = this;
        var $input = $(this);
        var id = input.id;

        // If the placeholder is activated, triggering blur event (`$input.trigger('blur')`) should do nothing.
        if (event && event.type === 'blur' && $input.hasClass(settings.customClass)) {
            return;
        }

        if (input.value === '') {
            if (input.type === 'password') {
                if (!$input.data('placeholder-textinput')) {
                    
                    try {
                        $replacement = $input.clone().prop({ 'type': 'text' });
                    } catch(e) {
                        $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
                    }

                    $replacement
                        .removeAttr('name')
                        .data({
                            'placeholder-enabled': true,
                            'placeholder-password': $input,
                            'placeholder-id': id
                        })
                        .bind('focus.placeholder', clearPlaceholder);

                    $input
                        .data({
                            'placeholder-textinput': $replacement,
                            'placeholder-id': id
                        })
                        .before($replacement);
                }

                input.value = '';
                $input = $input.removeAttr('id').hide().prevAll('input[type="text"]:first').attr('id', $input.data('placeholder-id')).show();

            } else {
                
                var $passwordInput = $input.data('placeholder-password');

                if ($passwordInput) {
                    $passwordInput[0].value = '';
                    $input.attr('id', $input.data('placeholder-id')).show().nextAll('input[type="password"]:last').hide().removeAttr('id');
                }
            }

            $input.addClass(settings.customClass);
            $input[0].value = $input.attr((debugMode ? 'placeholder-x' : 'placeholder'));

        } else {
            $input.removeClass(settings.customClass);
        }
    }

    function safeActiveElement() {
        // Avoid IE9 `document.activeElement` of death
        try {
            return document.activeElement;
        } catch (exception) {}
    }
}));


/*! 
 * 
 * ================== js/libs/plugins/jquery.avt.isotope.js =================== 
 **/ 

/*!
 * Isotope PACKAGED v3.0.6
 *
 * Licensed GPLv3 for open source use
 * or Isotope Commercial License for commercial use
 *
 * https://isotope.metafizzy.co
 * Copyright 2010-2018 Metafizzy
 */

/**
 * Bridget makes jQuery widgets
 * v2.0.1
 * MIT license
 */

/* jshint browser: true, strict: true, undef: true, unused: true */

( function( window, factory ) {
  // universal module definition
  /*jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'jquery-bridget/jquery-bridget',[ 'jquery' ], function( jQuery ) {
      return factory( window, jQuery );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('jquery')
    );
  } else {
    // browser global
    window.jQueryBridget = factory(
      window,
      window.jQuery
    );
  }

}( window, function factory( window, jQuery ) {
'use strict';

// ----- utils ----- //

var arraySlice = Array.prototype.slice;

// helper function for logging errors
// $.error breaks jQuery chaining
var console = window.console;
var logError = typeof console == 'undefined' ? function() {} :
  function( message ) {
    console.error( message );
  };

// ----- jQueryBridget ----- //

function jQueryBridget( namespace, PluginClass, $ ) {
  $ = $ || jQuery || window.jQuery;
  if ( !$ ) {
    return;
  }

  // add option method -> $().plugin('option', {...})
  if ( !PluginClass.prototype.option ) {
    // option setter
    PluginClass.prototype.option = function( opts ) {
      // bail out if not an object
      if ( !$.isPlainObject( opts ) ){
        return;
      }
      this.options = $.extend( true, this.options, opts );
    };
  }

  // make jQuery plugin
  $.fn[ namespace ] = function( arg0 /*, arg1 */ ) {
    if ( typeof arg0 == 'string' ) {
      // method call $().plugin( 'methodName', { options } )
      // shift arguments by 1
      var args = arraySlice.call( arguments, 1 );
      return methodCall( this, arg0, args );
    }
    // just $().plugin({ options })
    plainCall( this, arg0 );
    return this;
  };

  // $().plugin('methodName')
  function methodCall( $elems, methodName, args ) {
    var returnValue;
    var pluginMethodStr = '$().' + namespace + '("' + methodName + '")';

    $elems.each( function( i, elem ) {
      // get instance
      var instance = $.data( elem, namespace );
      if ( !instance ) {
        logError( namespace + ' not initialized. Cannot call methods, i.e. ' +
          pluginMethodStr );
        return;
      }

      var method = instance[ methodName ];
      if ( !method || methodName.charAt(0) == '_' ) {
        logError( pluginMethodStr + ' is not a valid method' );
        return;
      }

      // apply method, get return value
      var value = method.apply( instance, args );
      // set return value if value is returned, use only first value
      returnValue = returnValue === undefined ? value : returnValue;
    });

    return returnValue !== undefined ? returnValue : $elems;
  }

  function plainCall( $elems, options ) {
    $elems.each( function( i, elem ) {
      var instance = $.data( elem, namespace );
      if ( instance ) {
        // set options & init
        instance.option( options );
        instance._init();
      } else {
        // initialize new instance
        instance = new PluginClass( elem, options );
        $.data( elem, namespace, instance );
      }
    });
  }

  updateJQuery( $ );

}

// ----- updateJQuery ----- //

// set $.bridget for v1 backwards compatibility
function updateJQuery( $ ) {
  if ( !$ || ( $ && $.bridget ) ) {
    return;
  }
  $.bridget = jQueryBridget;
}

updateJQuery( jQuery || window.jQuery );

// -----  ----- //

return jQueryBridget;

}));

/**
 * EvEmitter v1.1.0
 * Lil' event emitter
 * MIT License
 */

/* jshint unused: true, undef: true, strict: true */

( function( global, factory ) {
  // universal module definition
  /* jshint strict: false */ /* globals define, module, window */
  if ( typeof define == 'function' && define.amd ) {
    // AMD - RequireJS
    define( 'ev-emitter/ev-emitter',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS - Browserify, Webpack
    module.exports = factory();
  } else {
    // Browser globals
    global.EvEmitter = factory();
  }

}( typeof window != 'undefined' ? window : this, function() {



function EvEmitter() {}

var proto = EvEmitter.prototype;

proto.on = function( eventName, listener ) {
  if ( !eventName || !listener ) {
    return;
  }
  // set events hash
  var events = this._events = this._events || {};
  // set listeners array
  var listeners = events[ eventName ] = events[ eventName ] || [];
  // only add once
  if ( listeners.indexOf( listener ) == -1 ) {
    listeners.push( listener );
  }

  return this;
};

proto.once = function( eventName, listener ) {
  if ( !eventName || !listener ) {
    return;
  }
  // add event
  this.on( eventName, listener );
  // set once flag
  // set onceEvents hash
  var onceEvents = this._onceEvents = this._onceEvents || {};
  // set onceListeners object
  var onceListeners = onceEvents[ eventName ] = onceEvents[ eventName ] || {};
  // set flag
  onceListeners[ listener ] = true;

  return this;
};

proto.off = function( eventName, listener ) {
  var listeners = this._events && this._events[ eventName ];
  if ( !listeners || !listeners.length ) {
    return;
  }
  var index = listeners.indexOf( listener );
  if ( index != -1 ) {
    listeners.splice( index, 1 );
  }

  return this;
};

proto.emitEvent = function( eventName, args ) {
  var listeners = this._events && this._events[ eventName ];
  if ( !listeners || !listeners.length ) {
    return;
  }
  // copy over to avoid interference if .off() in listener
  listeners = listeners.slice(0);
  args = args || [];
  // once stuff
  var onceListeners = this._onceEvents && this._onceEvents[ eventName ];

  for ( var i=0; i < listeners.length; i++ ) {
    var listener = listeners[i]
    var isOnce = onceListeners && onceListeners[ listener ];
    if ( isOnce ) {
      // remove listener
      // remove before trigger to prevent recursion
      this.off( eventName, listener );
      // unset once flag
      delete onceListeners[ listener ];
    }
    // trigger listener
    listener.apply( this, args );
  }

  return this;
};

proto.allOff = function() {
  delete this._events;
  delete this._onceEvents;
};

return EvEmitter;

}));

/*!
 * getSize v2.0.3
 * measure size of elements
 * MIT license
 */

/* jshint browser: true, strict: true, undef: true, unused: true */
/* globals console: false */

( function( window, factory ) {
  /* jshint strict: false */ /* globals define, module */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'get-size/get-size',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory();
  } else {
    // browser global
    window.getSize = factory();
  }

})( window, function factory() {
'use strict';

// -------------------------- helpers -------------------------- //

// get a number from a string, not a percentage
function getStyleSize( value ) {
  var num = parseFloat( value );
  // not a percent like '100%', and a number
  var isValid = value.indexOf('%') == -1 && !isNaN( num );
  return isValid && num;
}

function noop() {}

var logError = typeof console == 'undefined' ? noop :
  function( message ) {
    console.error( message );
  };

// -------------------------- measurements -------------------------- //

var measurements = [
  'paddingLeft',
  'paddingRight',
  'paddingTop',
  'paddingBottom',
  'marginLeft',
  'marginRight',
  'marginTop',
  'marginBottom',
  'borderLeftWidth',
  'borderRightWidth',
  'borderTopWidth',
  'borderBottomWidth'
];

var measurementsLength = measurements.length;

function getZeroSize() {
  var size = {
    width: 0,
    height: 0,
    innerWidth: 0,
    innerHeight: 0,
    outerWidth: 0,
    outerHeight: 0
  };
  for ( var i=0; i < measurementsLength; i++ ) {
    var measurement = measurements[i];
    size[ measurement ] = 0;
  }
  return size;
}

// -------------------------- getStyle -------------------------- //

/**
 * getStyle, get style of element, check for Firefox bug
 * https://bugzilla.mozilla.org/show_bug.cgi?id=548397
 */
function getStyle( elem ) {
  var style = getComputedStyle( elem );
  if ( !style ) {
    logError( 'Style returned ' + style +
      '. Are you running this code in a hidden iframe on Firefox? ' +
      'See https://bit.ly/getsizebug1' );
  }
  return style;
}

// -------------------------- setup -------------------------- //

var isSetup = false;

var isBoxSizeOuter;

/**
 * setup
 * check isBoxSizerOuter
 * do on first getSize() rather than on page load for Firefox bug
 */
function setup() {
  // setup once
  if ( isSetup ) {
    return;
  }
  isSetup = true;

  // -------------------------- box sizing -------------------------- //

  /**
   * Chrome & Safari measure the outer-width on style.width on border-box elems
   * IE11 & Firefox<29 measures the inner-width
   */
  var div = document.createElement('div');
  div.style.width = '200px';
  div.style.padding = '1px 2px 3px 4px';
  div.style.borderStyle = 'solid';
  div.style.borderWidth = '1px 2px 3px 4px';
  div.style.boxSizing = 'border-box';

  var body = document.body || document.documentElement;
  body.appendChild( div );
  var style = getStyle( div );
  // round value for browser zoom. desandro/masonry#928
  isBoxSizeOuter = Math.round( getStyleSize( style.width ) ) == 200;
  getSize.isBoxSizeOuter = isBoxSizeOuter;

  body.removeChild( div );
}

// -------------------------- getSize -------------------------- //

function getSize( elem ) {
  setup();

  // use querySeletor if elem is string
  if ( typeof elem == 'string' ) {
    elem = document.querySelector( elem );
  }

  // do not proceed on non-objects
  if ( !elem || typeof elem != 'object' || !elem.nodeType ) {
    return;
  }

  var style = getStyle( elem );

  // if hidden, everything is 0
  if ( style.display == 'none' ) {
    return getZeroSize();
  }

  var size = {};
  size.width = elem.offsetWidth;
  size.height = elem.offsetHeight;

  var isBorderBox = size.isBorderBox = style.boxSizing == 'border-box';

  // get all measurements
  for ( var i=0; i < measurementsLength; i++ ) {
    var measurement = measurements[i];
    var value = style[ measurement ];
    var num = parseFloat( value );
    // any 'auto', 'medium' value will be 0
    size[ measurement ] = !isNaN( num ) ? num : 0;
  }

  var paddingWidth = size.paddingLeft + size.paddingRight;
  var paddingHeight = size.paddingTop + size.paddingBottom;
  var marginWidth = size.marginLeft + size.marginRight;
  var marginHeight = size.marginTop + size.marginBottom;
  var borderWidth = size.borderLeftWidth + size.borderRightWidth;
  var borderHeight = size.borderTopWidth + size.borderBottomWidth;

  var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;

  // overwrite width and height if we can get it from style
  var styleWidth = getStyleSize( style.width );
  if ( styleWidth !== false ) {
    size.width = styleWidth +
      // add padding and border unless it's already including it
      ( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );
  }

  var styleHeight = getStyleSize( style.height );
  if ( styleHeight !== false ) {
    size.height = styleHeight +
      // add padding and border unless it's already including it
      ( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );
  }

  size.innerWidth = size.width - ( paddingWidth + borderWidth );
  size.innerHeight = size.height - ( paddingHeight + borderHeight );

  size.outerWidth = size.width + marginWidth;
  size.outerHeight = size.height + marginHeight;

  return size;
}

return getSize;

});

/**
 * matchesSelector v2.0.2
 * matchesSelector( element, '.selector' )
 * MIT license
 */

/*jshint browser: true, strict: true, undef: true, unused: true */

( function( window, factory ) {
  /*global define: false, module: false */
  'use strict';
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'desandro-matches-selector/matches-selector',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory();
  } else {
    // browser global
    window.matchesSelector = factory();
  }

}( window, function factory() {
  'use strict';

  var matchesMethod = ( function() {
    var ElemProto = window.Element.prototype;
    // check for the standard method name first
    if ( ElemProto.matches ) {
      return 'matches';
    }
    // check un-prefixed
    if ( ElemProto.matchesSelector ) {
      return 'matchesSelector';
    }
    // check vendor prefixes
    var prefixes = [ 'webkit', 'moz', 'ms', 'o' ];

    for ( var i=0; i < prefixes.length; i++ ) {
      var prefix = prefixes[i];
      var method = prefix + 'MatchesSelector';
      if ( ElemProto[ method ] ) {
        return method;
      }
    }
  })();

  return function matchesSelector( elem, selector ) {
    return elem[ matchesMethod ]( selector );
  };

}));

/**
 * Fizzy UI utils v2.0.7
 * MIT license
 */

/*jshint browser: true, undef: true, unused: true, strict: true */

( function( window, factory ) {
  // universal module definition
  /*jshint strict: false */ /*globals define, module, require */

  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'fizzy-ui-utils/utils',[
      'desandro-matches-selector/matches-selector'
    ], function( matchesSelector ) {
      return factory( window, matchesSelector );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('desandro-matches-selector')
    );
  } else {
    // browser global
    window.fizzyUIUtils = factory(
      window,
      window.matchesSelector
    );
  }

}( window, function factory( window, matchesSelector ) {



var utils = {};

// ----- extend ----- //

// extends objects
utils.extend = function( a, b ) {
  for ( var prop in b ) {
    a[ prop ] = b[ prop ];
  }
  return a;
};

// ----- modulo ----- //

utils.modulo = function( num, div ) {
  return ( ( num % div ) + div ) % div;
};

// ----- makeArray ----- //

var arraySlice = Array.prototype.slice;

// turn element or nodeList into an array
utils.makeArray = function( obj ) {
  if ( Array.isArray( obj ) ) {
    // use object if already an array
    return obj;
  }
  // return empty array if undefined or null. #6
  if ( obj === null || obj === undefined ) {
    return [];
  }

  var isArrayLike = typeof obj == 'object' && typeof obj.length == 'number';
  if ( isArrayLike ) {
    // convert nodeList to array
    return arraySlice.call( obj );
  }

  // array of single index
  return [ obj ];
};

// ----- removeFrom ----- //

utils.removeFrom = function( ary, obj ) {
  var index = ary.indexOf( obj );
  if ( index != -1 ) {
    ary.splice( index, 1 );
  }
};

// ----- getParent ----- //

utils.getParent = function( elem, selector ) {
  while ( elem.parentNode && elem != document.body ) {
    elem = elem.parentNode;
    if ( matchesSelector( elem, selector ) ) {
      return elem;
    }
  }
};

// ----- getQueryElement ----- //

// use element as selector string
utils.getQueryElement = function( elem ) {
  if ( typeof elem == 'string' ) {
    return document.querySelector( elem );
  }
  return elem;
};

// ----- handleEvent ----- //

// enable .ontype to trigger from .addEventListener( elem, 'type' )
utils.handleEvent = function( event ) {
  var method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

// ----- filterFindElements ----- //

utils.filterFindElements = function( elems, selector ) {
  // make array of elems
  elems = utils.makeArray( elems );
  var ffElems = [];

  elems.forEach( function( elem ) {
    // check that elem is an actual element
    if ( !( elem instanceof HTMLElement ) ) {
      return;
    }
    // add elem if no selector
    if ( !selector ) {
      ffElems.push( elem );
      return;
    }
    // filter & find items if we have a selector
    // filter
    if ( matchesSelector( elem, selector ) ) {
      ffElems.push( elem );
    }
    // find children
    var childElems = elem.querySelectorAll( selector );
    // concat childElems to filterFound array
    for ( var i=0; i < childElems.length; i++ ) {
      ffElems.push( childElems[i] );
    }
  });

  return ffElems;
};

// ----- debounceMethod ----- //

utils.debounceMethod = function( _class, methodName, threshold ) {
  threshold = threshold || 100;
  // original method
  var method = _class.prototype[ methodName ];
  var timeoutName = methodName + 'Timeout';

  _class.prototype[ methodName ] = function() {
    var timeout = this[ timeoutName ];
    clearTimeout( timeout );

    var args = arguments;
    var _this = this;
    this[ timeoutName ] = setTimeout( function() {
      method.apply( _this, args );
      delete _this[ timeoutName ];
    }, threshold );
  };
};

// ----- docReady ----- //

utils.docReady = function( callback ) {
  var readyState = document.readyState;
  if ( readyState == 'complete' || readyState == 'interactive' ) {
    // do async to allow for other scripts to run. metafizzy/flickity#441
    setTimeout( callback );
  } else {
    document.addEventListener( 'DOMContentLoaded', callback );
  }
};

// ----- htmlInit ----- //

// http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/
utils.toDashed = function( str ) {
  return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) {
    return $1 + '-' + $2;
  }).toLowerCase();
};

var console = window.console;
/**
 * allow user to initialize classes via [data-namespace] or .js-namespace class
 * htmlInit( Widget, 'widgetName' )
 * options are parsed from data-namespace-options
 */
utils.htmlInit = function( WidgetClass, namespace ) {
  utils.docReady( function() {
    var dashedNamespace = utils.toDashed( namespace );
    var dataAttr = 'data-' + dashedNamespace;
    var dataAttrElems = document.querySelectorAll( '[' + dataAttr + ']' );
    var jsDashElems = document.querySelectorAll( '.js-' + dashedNamespace );
    var elems = utils.makeArray( dataAttrElems )
      .concat( utils.makeArray( jsDashElems ) );
    var dataOptionsAttr = dataAttr + '-options';
    var jQuery = window.jQuery;

    elems.forEach( function( elem ) {
      var attr = elem.getAttribute( dataAttr ) ||
        elem.getAttribute( dataOptionsAttr );
      var options;
      try {
        options = attr && JSON.parse( attr );
      } catch ( error ) {
        // log error, do not initialize
        if ( console ) {
          console.error( 'Error parsing ' + dataAttr + ' on ' + elem.className +
          ': ' + error );
        }
        return;
      }
      // initialize
      var instance = new WidgetClass( elem, options );
      // make available via $().data('namespace')
      if ( jQuery ) {
        jQuery.data( elem, namespace, instance );
      }
    });

  });
};

// -----  ----- //

return utils;

}));

/**
 * Outlayer Item
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD - RequireJS
    define( 'outlayer/item',[
        'ev-emitter/ev-emitter',
        'get-size/get-size'
      ],
      factory
    );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS - Browserify, Webpack
    module.exports = factory(
      require('ev-emitter'),
      require('get-size')
    );
  } else {
    // browser global
    window.Outlayer = {};
    window.Outlayer.Item = factory(
      window.EvEmitter,
      window.getSize
    );
  }

}( window, function factory( EvEmitter, getSize ) {
'use strict';

// ----- helpers ----- //

function isEmptyObj( obj ) {
  for ( var prop in obj ) {
    return false;
  }
  prop = null;
  return true;
}

// -------------------------- CSS3 support -------------------------- //


var docElemStyle = document.documentElement.style;

var transitionProperty = typeof docElemStyle.transition == 'string' ?
  'transition' : 'WebkitTransition';
var transformProperty = typeof docElemStyle.transform == 'string' ?
  'transform' : 'WebkitTransform';

var transitionEndEvent = {
  WebkitTransition: 'webkitTransitionEnd',
  transition: 'transitionend'
}[ transitionProperty ];

// cache all vendor properties that could have vendor prefix
var vendorProperties = {
  transform: transformProperty,
  transition: transitionProperty,
  transitionDuration: transitionProperty + 'Duration',
  transitionProperty: transitionProperty + 'Property',
  transitionDelay: transitionProperty + 'Delay'
};

// -------------------------- Item -------------------------- //

function Item( element, layout ) {
  if ( !element ) {
    return;
  }

  this.element = element;
  // parent layout class, i.e. Masonry, Isotope, or Packery
  this.layout = layout;
  this.position = {
    x: 0,
    y: 0
  };

  this._create();
}

// inherit EvEmitter
var proto = Item.prototype = Object.create( EvEmitter.prototype );
proto.constructor = Item;

proto._create = function() {
  // transition objects
  this._transn = {
    ingProperties: {},
    clean: {},
    onEnd: {}
  };

  this.css({
    position: 'absolute'
  });
};

// trigger specified handler for event type
proto.handleEvent = function( event ) {
  var method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

proto.getSize = function() {
  this.size = getSize( this.element );
};

/**
 * apply CSS styles to element
 * @param {Object} style
 */
proto.css = function( style ) {
  var elemStyle = this.element.style;

  for ( var prop in style ) {
    // use vendor property if available
    var supportedProp = vendorProperties[ prop ] || prop;
    elemStyle[ supportedProp ] = style[ prop ];
  }
};

 // measure position, and sets it
proto.getPosition = function() {
  var style = getComputedStyle( this.element );
  var isOriginLeft = this.layout._getOption('originLeft');
  var isOriginTop = this.layout._getOption('originTop');
  var xValue = style[ isOriginLeft ? 'left' : 'right' ];
  var yValue = style[ isOriginTop ? 'top' : 'bottom' ];
  var x = parseFloat( xValue );
  var y = parseFloat( yValue );
  // convert percent to pixels
  var layoutSize = this.layout.size;
  if ( xValue.indexOf('%') != -1 ) {
    x = ( x / 100 ) * layoutSize.width;
  }
  if ( yValue.indexOf('%') != -1 ) {
    y = ( y / 100 ) * layoutSize.height;
  }
  // clean up 'auto' or other non-integer values
  x = isNaN( x ) ? 0 : x;
  y = isNaN( y ) ? 0 : y;
  // remove padding from measurement
  x -= isOriginLeft ? layoutSize.paddingLeft : layoutSize.paddingRight;
  y -= isOriginTop ? layoutSize.paddingTop : layoutSize.paddingBottom;

  this.position.x = x;
  this.position.y = y;
};

// set settled position, apply padding
proto.layoutPosition = function() {
  var layoutSize = this.layout.size;
  var style = {};
  var isOriginLeft = this.layout._getOption('originLeft');
  var isOriginTop = this.layout._getOption('originTop');

  // x
  var xPadding = isOriginLeft ? 'paddingLeft' : 'paddingRight';
  var xProperty = isOriginLeft ? 'left' : 'right';
  var xResetProperty = isOriginLeft ? 'right' : 'left';

  var x = this.position.x + layoutSize[ xPadding ];
  // set in percentage or pixels
  style[ xProperty ] = this.getXValue( x );
  // reset other property
  style[ xResetProperty ] = '';

  // y
  var yPadding = isOriginTop ? 'paddingTop' : 'paddingBottom';
  var yProperty = isOriginTop ? 'top' : 'bottom';
  var yResetProperty = isOriginTop ? 'bottom' : 'top';

  var y = this.position.y + layoutSize[ yPadding ];
  // set in percentage or pixels
  style[ yProperty ] = this.getYValue( y );
  // reset other property
  style[ yResetProperty ] = '';

  this.css( style );
  this.emitEvent( 'layout', [ this ] );
};

proto.getXValue = function( x ) {
  var isHorizontal = this.layout._getOption('horizontal');
  return this.layout.options.percentPosition && !isHorizontal ?
    ( ( x / this.layout.size.width ) * 100 ) + '%' : x + 'px';
};

proto.getYValue = function( y ) {
  var isHorizontal = this.layout._getOption('horizontal');
  return this.layout.options.percentPosition && isHorizontal ?
    ( ( y / this.layout.size.height ) * 100 ) + '%' : y + 'px';
};

proto._transitionTo = function( x, y ) {
  this.getPosition();
  // get current x & y from top/left
  var curX = this.position.x;
  var curY = this.position.y;

  var didNotMove = x == this.position.x && y == this.position.y;

  // save end position
  this.setPosition( x, y );

  // if did not move and not transitioning, just go to layout
  if ( didNotMove && !this.isTransitioning ) {
    this.layoutPosition();
    return;
  }

  var transX = x - curX;
  var transY = y - curY;
  var transitionStyle = {};
  transitionStyle.transform = this.getTranslate( transX, transY );

  this.transition({
    to: transitionStyle,
    onTransitionEnd: {
      transform: this.layoutPosition
    },
    isCleaning: true
  });
};

proto.getTranslate = function( x, y ) {
  // flip cooridinates if origin on right or bottom
  var isOriginLeft = this.layout._getOption('originLeft');
  var isOriginTop = this.layout._getOption('originTop');
  x = isOriginLeft ? x : -x;
  y = isOriginTop ? y : -y;
  return 'translate3d(' + x + 'px, ' + y + 'px, 0)';
};

// non transition + transform support
proto.goTo = function( x, y ) {
  this.setPosition( x, y );
  this.layoutPosition();
};

proto.moveTo = proto._transitionTo;

proto.setPosition = function( x, y ) {
  this.position.x = parseFloat( x );
  this.position.y = parseFloat( y );
};

// ----- transition ----- //

/**
 * @param {Object} style - CSS
 * @param {Function} onTransitionEnd
 */

// non transition, just trigger callback
proto._nonTransition = function( args ) {
  this.css( args.to );
  if ( args.isCleaning ) {
    this._removeStyles( args.to );
  }
  for ( var prop in args.onTransitionEnd ) {
    args.onTransitionEnd[ prop ].call( this );
  }
};

/**
 * proper transition
 * @param {Object} args - arguments
 *   @param {Object} to - style to transition to
 *   @param {Object} from - style to start transition from
 *   @param {Boolean} isCleaning - removes transition styles after transition
 *   @param {Function} onTransitionEnd - callback
 */
proto.transition = function( args ) {
  // redirect to nonTransition if no transition duration
  if ( !parseFloat( this.layout.options.transitionDuration ) ) {
    this._nonTransition( args );
    return;
  }

  var _transition = this._transn;
  // keep track of onTransitionEnd callback by css property
  for ( var prop in args.onTransitionEnd ) {
    _transition.onEnd[ prop ] = args.onTransitionEnd[ prop ];
  }
  // keep track of properties that are transitioning
  for ( prop in args.to ) {
    _transition.ingProperties[ prop ] = true;
    // keep track of properties to clean up when transition is done
    if ( args.isCleaning ) {
      _transition.clean[ prop ] = true;
    }
  }

  // set from styles
  if ( args.from ) {
    this.css( args.from );
    // force redraw. http://blog.alexmaccaw.com/css-transitions
    var h = this.element.offsetHeight;
    // hack for JSHint to hush about unused var
    h = null;
  }
  // enable transition
  this.enableTransition( args.to );
  // set styles that are transitioning
  this.css( args.to );

  this.isTransitioning = true;

};

// dash before all cap letters, including first for
// WebkitTransform => -webkit-transform
function toDashedAll( str ) {
  return str.replace( /([A-Z])/g, function( $1 ) {
    return '-' + $1.toLowerCase();
  });
}

var transitionProps = 'opacity,' + toDashedAll( transformProperty );

proto.enableTransition = function(/* style */) {
  // HACK changing transitionProperty during a transition
  // will cause transition to jump
  if ( this.isTransitioning ) {
    return;
  }

  // make `transition: foo, bar, baz` from style object
  // HACK un-comment this when enableTransition can work
  // while a transition is happening
  // var transitionValues = [];
  // for ( var prop in style ) {
  //   // dash-ify camelCased properties like WebkitTransition
  //   prop = vendorProperties[ prop ] || prop;
  //   transitionValues.push( toDashedAll( prop ) );
  // }
  // munge number to millisecond, to match stagger
  var duration = this.layout.options.transitionDuration;
  duration = typeof duration == 'number' ? duration + 'ms' : duration;
  // enable transition styles
  this.css({
    transitionProperty: transitionProps,
    transitionDuration: duration,
    transitionDelay: this.staggerDelay || 0
  });
  // listen for transition end event
  this.element.addEventListener( transitionEndEvent, this, false );
};

// ----- events ----- //

proto.onwebkitTransitionEnd = function( event ) {
  this.ontransitionend( event );
};

proto.onotransitionend = function( event ) {
  this.ontransitionend( event );
};

// properties that I munge to make my life easier
var dashedVendorProperties = {
  '-webkit-transform': 'transform'
};

proto.ontransitionend = function( event ) {
  // disregard bubbled events from children
  if ( event.target !== this.element ) {
    return;
  }
  var _transition = this._transn;
  // get property name of transitioned property, convert to prefix-free
  var propertyName = dashedVendorProperties[ event.propertyName ] || event.propertyName;

  // remove property that has completed transitioning
  delete _transition.ingProperties[ propertyName ];
  // check if any properties are still transitioning
  if ( isEmptyObj( _transition.ingProperties ) ) {
    // all properties have completed transitioning
    this.disableTransition();
  }
  // clean style
  if ( propertyName in _transition.clean ) {
    // clean up style
    this.element.style[ event.propertyName ] = '';
    delete _transition.clean[ propertyName ];
  }
  // trigger onTransitionEnd callback
  if ( propertyName in _transition.onEnd ) {
    var onTransitionEnd = _transition.onEnd[ propertyName ];
    onTransitionEnd.call( this );
    delete _transition.onEnd[ propertyName ];
  }

  this.emitEvent( 'transitionEnd', [ this ] );
};

proto.disableTransition = function() {
  this.removeTransitionStyles();
  this.element.removeEventListener( transitionEndEvent, this, false );
  this.isTransitioning = false;
};

/**
 * removes style property from element
 * @param {Object} style
**/
proto._removeStyles = function( style ) {
  // clean up transition styles
  var cleanStyle = {};
  for ( var prop in style ) {
    cleanStyle[ prop ] = '';
  }
  this.css( cleanStyle );
};

var cleanTransitionStyle = {
  transitionProperty: '',
  transitionDuration: '',
  transitionDelay: ''
};

proto.removeTransitionStyles = function() {
  // remove transition
  this.css( cleanTransitionStyle );
};

// ----- stagger ----- //

proto.stagger = function( delay ) {
  delay = isNaN( delay ) ? 0 : delay;
  this.staggerDelay = delay + 'ms';
};

// ----- show/hide/remove ----- //

// remove element from DOM
proto.removeElem = function() {
  this.element.parentNode.removeChild( this.element );
  // remove display: none
  this.css({ display: '' });
  this.emitEvent( 'remove', [ this ] );
};

proto.remove = function() {
  // just remove element if no transition support or no transition
  if ( !transitionProperty || !parseFloat( this.layout.options.transitionDuration ) ) {
    this.removeElem();
    return;
  }

  // start transition
  this.once( 'transitionEnd', function() {
    this.removeElem();
  });
  this.hide();
};

proto.reveal = function() {
  delete this.isHidden;
  // remove display: none
  this.css({ display: '' });

  var options = this.layout.options;

  var onTransitionEnd = {};
  var transitionEndProperty = this.getHideRevealTransitionEndProperty('visibleStyle');
  onTransitionEnd[ transitionEndProperty ] = this.onRevealTransitionEnd;

  this.transition({
    from: options.hiddenStyle,
    to: options.visibleStyle,
    isCleaning: true,
    onTransitionEnd: onTransitionEnd
  });
};

proto.onRevealTransitionEnd = function() {
  // check if still visible
  // during transition, item may have been hidden
  if ( !this.isHidden ) {
    this.emitEvent('reveal');
  }
};

/**
 * get style property use for hide/reveal transition end
 * @param {String} styleProperty - hiddenStyle/visibleStyle
 * @returns {String}
 */
proto.getHideRevealTransitionEndProperty = function( styleProperty ) {
  var optionStyle = this.layout.options[ styleProperty ];
  // use opacity
  if ( optionStyle.opacity ) {
    return 'opacity';
  }
  // get first property
  for ( var prop in optionStyle ) {
    return prop;
  }
};

proto.hide = function() {
  // set flag
  this.isHidden = true;
  // remove display: none
  this.css({ display: '' });

  var options = this.layout.options;

  var onTransitionEnd = {};
  var transitionEndProperty = this.getHideRevealTransitionEndProperty('hiddenStyle');
  onTransitionEnd[ transitionEndProperty ] = this.onHideTransitionEnd;

  this.transition({
    from: options.visibleStyle,
    to: options.hiddenStyle,
    // keep hidden stuff hidden
    isCleaning: true,
    onTransitionEnd: onTransitionEnd
  });
};

proto.onHideTransitionEnd = function() {
  // check if still hidden
  // during transition, item may have been un-hidden
  if ( this.isHidden ) {
    this.css({ display: 'none' });
    this.emitEvent('hide');
  }
};

proto.destroy = function() {
  this.css({
    position: '',
    left: '',
    right: '',
    top: '',
    bottom: '',
    transition: '',
    transform: ''
  });
};

return Item;

}));

/*!
 * Outlayer v2.1.1
 * the brains and guts of a layout library
 * MIT license
 */

( function( window, factory ) {
  'use strict';
  // universal module definition
  /* jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD - RequireJS
    define( 'outlayer/outlayer',[
        'ev-emitter/ev-emitter',
        'get-size/get-size',
        'fizzy-ui-utils/utils',
        './item'
      ],
      function( EvEmitter, getSize, utils, Item ) {
        return factory( window, EvEmitter, getSize, utils, Item);
      }
    );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS - Browserify, Webpack
    module.exports = factory(
      window,
      require('ev-emitter'),
      require('get-size'),
      require('fizzy-ui-utils'),
      require('./item')
    );
  } else {
    // browser global
    window.Outlayer = factory(
      window,
      window.EvEmitter,
      window.getSize,
      window.fizzyUIUtils,
      window.Outlayer.Item
    );
  }

}( window, function factory( window, EvEmitter, getSize, utils, Item ) {
'use strict';

// ----- vars ----- //

var console = window.console;
var jQuery = window.jQuery;
var noop = function() {};

// -------------------------- Outlayer -------------------------- //

// globally unique identifiers
var GUID = 0;
// internal store of all Outlayer intances
var instances = {};


/**
 * @param {Element, String} element
 * @param {Object} options
 * @constructor
 */
function Outlayer( element, options ) {
  var queryElement = utils.getQueryElement( element );
  if ( !queryElement ) {
    if ( console ) {
      console.error( 'Bad element for ' + this.constructor.namespace +
        ': ' + ( queryElement || element ) );
    }
    return;
  }
  this.element = queryElement;
  // add jQuery
  if ( jQuery ) {
    this.$element = jQuery( this.element );
  }

  // options
  this.options = utils.extend( {}, this.constructor.defaults );
  this.option( options );

  // add id for Outlayer.getFromElement
  var id = ++GUID;
  this.element.outlayerGUID = id; // expando
  instances[ id ] = this; // associate via id

  // kick it off
  this._create();

  var isInitLayout = this._getOption('initLayout');
  if ( isInitLayout ) {
    this.layout();
  }
}

// settings are for internal use only
Outlayer.namespace = 'outlayer';
Outlayer.Item = Item;

// default options
Outlayer.defaults = {
  containerStyle: {
    position: 'relative'
  },
  initLayout: true,
  originLeft: true,
  originTop: true,
  resize: true,
  resizeContainer: true,
  // item options
  transitionDuration: '0.4s',
  hiddenStyle: {
    opacity: 0,
    transform: 'scale(0.001)'
  },
  visibleStyle: {
    opacity: 1,
    transform: 'scale(1)'
  }
};

var proto = Outlayer.prototype;
// inherit EvEmitter
utils.extend( proto, EvEmitter.prototype );

/**
 * set options
 * @param {Object} opts
 */
proto.option = function( opts ) {
  utils.extend( this.options, opts );
};

/**
 * get backwards compatible option value, check old name
 */
proto._getOption = function( option ) {
  var oldOption = this.constructor.compatOptions[ option ];
  return oldOption && this.options[ oldOption ] !== undefined ?
    this.options[ oldOption ] : this.options[ option ];
};

Outlayer.compatOptions = {
  // currentName: oldName
  initLayout: 'isInitLayout',
  horizontal: 'isHorizontal',
  layoutInstant: 'isLayoutInstant',
  originLeft: 'isOriginLeft',
  originTop: 'isOriginTop',
  resize: 'isResizeBound',
  resizeContainer: 'isResizingContainer'
};

proto._create = function() {
  // get items from children
  this.reloadItems();
  // elements that affect layout, but are not laid out
  this.stamps = [];
  this.stamp( this.options.stamp );
  // set container style
  utils.extend( this.element.style, this.options.containerStyle );

  // bind resize method
  var canBindResize = this._getOption('resize');
  if ( canBindResize ) {
    this.bindResize();
  }
};

// goes through all children again and gets bricks in proper order
proto.reloadItems = function() {
  // collection of item elements
  this.items = this._itemize( this.element.children );
};


/**
 * turn elements into Outlayer.Items to be used in layout
 * @param {Array or NodeList or HTMLElement} elems
 * @returns {Array} items - collection of new Outlayer Items
 */
proto._itemize = function( elems ) {

  var itemElems = this._filterFindItemElements( elems );
  var Item = this.constructor.Item;

  // create new Outlayer Items for collection
  var items = [];
  for ( var i=0; i < itemElems.length; i++ ) {
    var elem = itemElems[i];
    var item = new Item( elem, this );
    items.push( item );
  }

  return items;
};

/**
 * get item elements to be used in layout
 * @param {Array or NodeList or HTMLElement} elems
 * @returns {Array} items - item elements
 */
proto._filterFindItemElements = function( elems ) {
  return utils.filterFindElements( elems, this.options.itemSelector );
};

/**
 * getter method for getting item elements
 * @returns {Array} elems - collection of item elements
 */
proto.getItemElements = function() {
  return this.items.map( function( item ) {
    return item.element;
  });
};

// ----- init & layout ----- //

/**
 * lays out all items
 */
proto.layout = function() {
  this._resetLayout();
  this._manageStamps();

  // don't animate first layout
  var layoutInstant = this._getOption('layoutInstant');
  var isInstant = layoutInstant !== undefined ?
    layoutInstant : !this._isLayoutInited;
  this.layoutItems( this.items, isInstant );

  // flag for initalized
  this._isLayoutInited = true;
};

// _init is alias for layout
proto._init = proto.layout;

/**
 * logic before any new layout
 */
proto._resetLayout = function() {
  this.getSize();
};


proto.getSize = function() {
  this.size = getSize( this.element );
};

/**
 * get measurement from option, for columnWidth, rowHeight, gutter
 * if option is String -> get element from selector string, & get size of element
 * if option is Element -> get size of element
 * else use option as a number
 *
 * @param {String} measurement
 * @param {String} size - width or height
 * @private
 */
proto._getMeasurement = function( measurement, size ) {
  var option = this.options[ measurement ];
  var elem;
  if ( !option ) {
    // default to 0
    this[ measurement ] = 0;
  } else {
    // use option as an element
    if ( typeof option == 'string' ) {
      elem = this.element.querySelector( option );
    } else if ( option instanceof HTMLElement ) {
      elem = option;
    }
    // use size of element, if element
    this[ measurement ] = elem ? getSize( elem )[ size ] : option;
  }
};

/**
 * layout a collection of item elements
 * @api public
 */
proto.layoutItems = function( items, isInstant ) {
  items = this._getItemsForLayout( items );

  this._layoutItems( items, isInstant );

  this._postLayout();
};

/**
 * get the items to be laid out
 * you may want to skip over some items
 * @param {Array} items
 * @returns {Array} items
 */
proto._getItemsForLayout = function( items ) {
  return items.filter( function( item ) {
    return !item.isIgnored;
  });
};

/**
 * layout items
 * @param {Array} items
 * @param {Boolean} isInstant
 */
proto._layoutItems = function( items, isInstant ) {
  this._emitCompleteOnItems( 'layout', items );

  if ( !items || !items.length ) {
    // no items, emit event with empty array
    return;
  }

  var queue = [];

  items.forEach( function( item ) {
    // get x/y object from method
    var position = this._getItemLayoutPosition( item );
    // enqueue
    position.item = item;
    position.isInstant = isInstant || item.isLayoutInstant;
    queue.push( position );
  }, this );

  this._processLayoutQueue( queue );
};

/**
 * get item layout position
 * @param {Outlayer.Item} item
 * @returns {Object} x and y position
 */
proto._getItemLayoutPosition = function( /* item */ ) {
  return {
    x: 0,
    y: 0
  };
};

/**
 * iterate over array and position each item
 * Reason being - separating this logic prevents 'layout invalidation'
 * thx @paul_irish
 * @param {Array} queue
 */
proto._processLayoutQueue = function( queue ) {
  this.updateStagger();
  queue.forEach( function( obj, i ) {
    this._positionItem( obj.item, obj.x, obj.y, obj.isInstant, i );
  }, this );
};

// set stagger from option in milliseconds number
proto.updateStagger = function() {
  var stagger = this.options.stagger;
  if ( stagger === null || stagger === undefined ) {
    this.stagger = 0;
    return;
  }
  this.stagger = getMilliseconds( stagger );
  return this.stagger;
};

/**
 * Sets position of item in DOM
 * @param {Outlayer.Item} item
 * @param {Number} x - horizontal position
 * @param {Number} y - vertical position
 * @param {Boolean} isInstant - disables transitions
 */
proto._positionItem = function( item, x, y, isInstant, i ) {
  if ( isInstant ) {
    // if not transition, just set CSS
    item.goTo( x, y );
  } else {
    item.stagger( i * this.stagger );
    item.moveTo( x, y );
  }
};

/**
 * Any logic you want to do after each layout,
 * i.e. size the container
 */
proto._postLayout = function() {
  this.resizeContainer();
};

proto.resizeContainer = function() {
  var isResizingContainer = this._getOption('resizeContainer');
  if ( !isResizingContainer ) {
    return;
  }
  var size = this._getContainerSize();
  if ( size ) {
    this._setContainerMeasure( size.width, true );
    this._setContainerMeasure( size.height, false );
  }
};

/**
 * Sets width or height of container if returned
 * @returns {Object} size
 *   @param {Number} width
 *   @param {Number} height
 */
proto._getContainerSize = noop;

/**
 * @param {Number} measure - size of width or height
 * @param {Boolean} isWidth
 */
proto._setContainerMeasure = function( measure, isWidth ) {
  if ( measure === undefined ) {
    return;
  }

  var elemSize = this.size;
  // add padding and border width if border box
  if ( elemSize.isBorderBox ) {
    measure += isWidth ? elemSize.paddingLeft + elemSize.paddingRight +
      elemSize.borderLeftWidth + elemSize.borderRightWidth :
      elemSize.paddingBottom + elemSize.paddingTop +
      elemSize.borderTopWidth + elemSize.borderBottomWidth;
  }

  measure = Math.max( measure, 0 );
  this.element.style[ isWidth ? 'width' : 'height' ] = measure + 'px';
};

/**
 * emit eventComplete on a collection of items events
 * @param {String} eventName
 * @param {Array} items - Outlayer.Items
 */
proto._emitCompleteOnItems = function( eventName, items ) {
  var _this = this;
  function onComplete() {
    _this.dispatchEvent( eventName + 'Complete', null, [ items ] );
  }

  var count = items.length;
  if ( !items || !count ) {
    onComplete();
    return;
  }

  var doneCount = 0;
  function tick() {
    doneCount++;
    if ( doneCount == count ) {
      onComplete();
    }
  }

  // bind callback
  items.forEach( function( item ) {
    item.once( eventName, tick );
  });
};

/**
 * emits events via EvEmitter and jQuery events
 * @param {String} type - name of event
 * @param {Event} event - original event
 * @param {Array} args - extra arguments
 */
proto.dispatchEvent = function( type, event, args ) {
  // add original event to arguments
  var emitArgs = event ? [ event ].concat( args ) : args;
  this.emitEvent( type, emitArgs );

  if ( jQuery ) {
    // set this.$element
    this.$element = this.$element || jQuery( this.element );
    if ( event ) {
      // create jQuery event
      var $event = jQuery.Event( event );
      $event.type = type;
      this.$element.trigger( $event, args );
    } else {
      // just trigger with type if no event available
      this.$element.trigger( type, args );
    }
  }
};

// -------------------------- ignore & stamps -------------------------- //


/**
 * keep item in collection, but do not lay it out
 * ignored items do not get skipped in layout
 * @param {Element} elem
 */
proto.ignore = function( elem ) {
  var item = this.getItem( elem );
  if ( item ) {
    item.isIgnored = true;
  }
};

/**
 * return item to layout collection
 * @param {Element} elem
 */
proto.unignore = function( elem ) {
  var item = this.getItem( elem );
  if ( item ) {
    delete item.isIgnored;
  }
};

/**
 * adds elements to stamps
 * @param {NodeList, Array, Element, or String} elems
 */
proto.stamp = function( elems ) {
  elems = this._find( elems );
  if ( !elems ) {
    return;
  }

  this.stamps = this.stamps.concat( elems );
  // ignore
  elems.forEach( this.ignore, this );
};

/**
 * removes elements to stamps
 * @param {NodeList, Array, or Element} elems
 */
proto.unstamp = function( elems ) {
  elems = this._find( elems );
  if ( !elems ){
    return;
  }

  elems.forEach( function( elem ) {
    // filter out removed stamp elements
    utils.removeFrom( this.stamps, elem );
    this.unignore( elem );
  }, this );
};

/**
 * finds child elements
 * @param {NodeList, Array, Element, or String} elems
 * @returns {Array} elems
 */
proto._find = function( elems ) {
  if ( !elems ) {
    return;
  }
  // if string, use argument as selector string
  if ( typeof elems == 'string' ) {
    elems = this.element.querySelectorAll( elems );
  }
  elems = utils.makeArray( elems );
  return elems;
};

proto._manageStamps = function() {
  if ( !this.stamps || !this.stamps.length ) {
    return;
  }

  this._getBoundingRect();

  this.stamps.forEach( this._manageStamp, this );
};

// update boundingLeft / Top
proto._getBoundingRect = function() {
  // get bounding rect for container element
  var boundingRect = this.element.getBoundingClientRect();
  var size = this.size;
  this._boundingRect = {
    left: boundingRect.left + size.paddingLeft + size.borderLeftWidth,
    top: boundingRect.top + size.paddingTop + size.borderTopWidth,
    right: boundingRect.right - ( size.paddingRight + size.borderRightWidth ),
    bottom: boundingRect.bottom - ( size.paddingBottom + size.borderBottomWidth )
  };
};

/**
 * @param {Element} stamp
**/
proto._manageStamp = noop;

/**
 * get x/y position of element relative to container element
 * @param {Element} elem
 * @returns {Object} offset - has left, top, right, bottom
 */
proto._getElementOffset = function( elem ) {
  var boundingRect = elem.getBoundingClientRect();
  var thisRect = this._boundingRect;
  var size = getSize( elem );
  var offset = {
    left: boundingRect.left - thisRect.left - size.marginLeft,
    top: boundingRect.top - thisRect.top - size.marginTop,
    right: thisRect.right - boundingRect.right - size.marginRight,
    bottom: thisRect.bottom - boundingRect.bottom - size.marginBottom
  };
  return offset;
};

// -------------------------- resize -------------------------- //

// enable event handlers for listeners
// i.e. resize -> onresize
proto.handleEvent = utils.handleEvent;

/**
 * Bind layout to window resizing
 */
proto.bindResize = function() {
  window.addEventListener( 'resize', this );
  this.isResizeBound = true;
};

/**
 * Unbind layout to window resizing
 */
proto.unbindResize = function() {
  window.removeEventListener( 'resize', this );
  this.isResizeBound = false;
};

proto.onresize = function() {
  this.resize();
};

utils.debounceMethod( Outlayer, 'onresize', 100 );

proto.resize = function() {
  // don't trigger if size did not change
  // or if resize was unbound. See #9
  if ( !this.isResizeBound || !this.needsResizeLayout() ) {
    return;
  }

  this.layout();
};

/**
 * check if layout is needed post layout
 * @returns Boolean
 */
proto.needsResizeLayout = function() {
  var size = getSize( this.element );
  // check that this.size and size are there
  // IE8 triggers resize on body size change, so they might not be
  var hasSizes = this.size && size;
  return hasSizes && size.innerWidth !== this.size.innerWidth;
};

// -------------------------- methods -------------------------- //

/**
 * add items to Outlayer instance
 * @param {Array or NodeList or Element} elems
 * @returns {Array} items - Outlayer.Items
**/
proto.addItems = function( elems ) {
  var items = this._itemize( elems );
  // add items to collection
  if ( items.length ) {
    this.items = this.items.concat( items );
  }
  return items;
};

/**
 * Layout newly-appended item elements
 * @param {Array or NodeList or Element} elems
 */
proto.appended = function( elems ) {
  var items = this.addItems( elems );
  if ( !items.length ) {
    return;
  }
  // layout and reveal just the new items
  this.layoutItems( items, true );
  this.reveal( items );
};

/**
 * Layout prepended elements
 * @param {Array or NodeList or Element} elems
 */
proto.prepended = function( elems ) {
  var items = this._itemize( elems );
  if ( !items.length ) {
    return;
  }
  // add items to beginning of collection
  var previousItems = this.items.slice(0);
  this.items = items.concat( previousItems );
  // start new layout
  this._resetLayout();
  this._manageStamps();
  // layout new stuff without transition
  this.layoutItems( items, true );
  this.reveal( items );
  // layout previous items
  this.layoutItems( previousItems );
};

/**
 * reveal a collection of items
 * @param {Array of Outlayer.Items} items
 */
proto.reveal = function( items ) {
  this._emitCompleteOnItems( 'reveal', items );
  if ( !items || !items.length ) {
    return;
  }
  var stagger = this.updateStagger();
  items.forEach( function( item, i ) {
    item.stagger( i * stagger );
    item.reveal();
  });
};

/**
 * hide a collection of items
 * @param {Array of Outlayer.Items} items
 */
proto.hide = function( items ) {
  this._emitCompleteOnItems( 'hide', items );
  if ( !items || !items.length ) {
    return;
  }
  var stagger = this.updateStagger();
  items.forEach( function( item, i ) {
    item.stagger( i * stagger );
    item.hide();
  });
};

/**
 * reveal item elements
 * @param {Array}, {Element}, {NodeList} items
 */
proto.revealItemElements = function( elems ) {
  var items = this.getItems( elems );
  this.reveal( items );
};

/**
 * hide item elements
 * @param {Array}, {Element}, {NodeList} items
 */
proto.hideItemElements = function( elems ) {
  var items = this.getItems( elems );
  this.hide( items );
};

/**
 * get Outlayer.Item, given an Element
 * @param {Element} elem
 * @param {Function} callback
 * @returns {Outlayer.Item} item
 */
proto.getItem = function( elem ) {
  // loop through items to get the one that matches
  for ( var i=0; i < this.items.length; i++ ) {
    var item = this.items[i];
    if ( item.element == elem ) {
      // return item
      return item;
    }
  }
};

/**
 * get collection of Outlayer.Items, given Elements
 * @param {Array} elems
 * @returns {Array} items - Outlayer.Items
 */
proto.getItems = function( elems ) {
  elems = utils.makeArray( elems );
  var items = [];
  elems.forEach( function( elem ) {
    var item = this.getItem( elem );
    if ( item ) {
      items.push( item );
    }
  }, this );

  return items;
};

/**
 * remove element(s) from instance and DOM
 * @param {Array or NodeList or Element} elems
 */
proto.remove = function( elems ) {
  var removeItems = this.getItems( elems );

  this._emitCompleteOnItems( 'remove', removeItems );

  // bail if no items to remove
  if ( !removeItems || !removeItems.length ) {
    return;
  }

  removeItems.forEach( function( item ) {
    item.remove();
    // remove item from collection
    utils.removeFrom( this.items, item );
  }, this );
};

// ----- destroy ----- //

// remove and disable Outlayer instance
proto.destroy = function() {
  // clean up dynamic styles
  var style = this.element.style;
  style.height = '';
  style.position = '';
  style.width = '';
  // destroy items
  this.items.forEach( function( item ) {
    item.destroy();
  });

  this.unbindResize();

  var id = this.element.outlayerGUID;
  delete instances[ id ]; // remove reference to instance by id
  delete this.element.outlayerGUID;
  // remove data for jQuery
  if ( jQuery ) {
    jQuery.removeData( this.element, this.constructor.namespace );
  }

};

// -------------------------- data -------------------------- //

/**
 * get Outlayer instance from element
 * @param {Element} elem
 * @returns {Outlayer}
 */
Outlayer.data = function( elem ) {
  elem = utils.getQueryElement( elem );
  var id = elem && elem.outlayerGUID;
  return id && instances[ id ];
};


// -------------------------- create Outlayer class -------------------------- //

/**
 * create a layout class
 * @param {String} namespace
 */
Outlayer.create = function( namespace, options ) {
  // sub-class Outlayer
  var Layout = subclass( Outlayer );
  // apply new options and compatOptions
  Layout.defaults = utils.extend( {}, Outlayer.defaults );
  utils.extend( Layout.defaults, options );
  Layout.compatOptions = utils.extend( {}, Outlayer.compatOptions  );

  Layout.namespace = namespace;

  Layout.data = Outlayer.data;

  // sub-class Item
  Layout.Item = subclass( Item );

  // -------------------------- declarative -------------------------- //

  utils.htmlInit( Layout, namespace );

  // -------------------------- jQuery bridge -------------------------- //

  // make into jQuery plugin
  if ( jQuery && jQuery.bridget ) {
    jQuery.bridget( namespace, Layout );
  }

  return Layout;
};

function subclass( Parent ) {
  function SubClass() {
    Parent.apply( this, arguments );
  }

  SubClass.prototype = Object.create( Parent.prototype );
  SubClass.prototype.constructor = SubClass;

  return SubClass;
}

// ----- helpers ----- //

// how many milliseconds are in each unit
var msUnits = {
  ms: 1,
  s: 1000
};

// munge time-like parameter into millisecond number
// '0.4s' -> 40
function getMilliseconds( time ) {
  if ( typeof time == 'number' ) {
    return time;
  }
  var matches = time.match( /(^\d*\.?\d*)(\w*)/ );
  var num = matches && matches[1];
  var unit = matches && matches[2];
  if ( !num.length ) {
    return 0;
  }
  num = parseFloat( num );
  var mult = msUnits[ unit ] || 1;
  return num * mult;
}

// ----- fin ----- //

// back in global
Outlayer.Item = Item;

return Outlayer;

}));

/**
 * Isotope Item
**/

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'isotope-layout/js/item',[
        'outlayer/outlayer'
      ],
      factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('outlayer')
    );
  } else {
    // browser global
    window.Isotope = window.Isotope || {};
    window.Isotope.Item = factory(
      window.Outlayer
    );
  }

}( window, function factory( Outlayer ) {
'use strict';

// -------------------------- Item -------------------------- //

// sub-class Outlayer Item
function Item() {
  Outlayer.Item.apply( this, arguments );
}

var proto = Item.prototype = Object.create( Outlayer.Item.prototype );

var _create = proto._create;
proto._create = function() {
  // assign id, used for original-order sorting
  this.id = this.layout.itemGUID++;
  _create.call( this );
  this.sortData = {};
};

proto.updateSortData = function() {
  if ( this.isIgnored ) {
    return;
  }
  // default sorters
  this.sortData.id = this.id;
  // for backward compatibility
  this.sortData['original-order'] = this.id;
  this.sortData.random = Math.random();
  // go thru getSortData obj and apply the sorters
  var getSortData = this.layout.options.getSortData;
  var sorters = this.layout._sorters;
  for ( var key in getSortData ) {
    var sorter = sorters[ key ];
    this.sortData[ key ] = sorter( this.element, this );
  }
};

// override reveal method
var _setPosition = proto.setPosition;
proto.setPosition = function() {  
  _setPosition.apply( this, arguments );

  if ( this.layout.options.imgSizes ) {
    if ( !this.imageElements ) {
      this.imageElements = this.element.querySelectorAll( 'img[sizes="auto"]' );
    }
    
    var images = this.imageElements;
    
    for ( var i = 0, len = images.length; i !== len; i++ ) {
      var img = images[i];
      img.setAttribute( 'sizes', img.offsetWidth + 'px' );
    }
  }
  
  if ( !this._lazyloadStarted && this.layout.options.lazyload ) {
    this._lazyloadStarted = true;
    this._lazyload();
  }
};

proto._lazyload = function() {
  this.layout.dispatchEvent( 'beforeItemLoading', null, [ this ] );

  var images = this.element.querySelectorAll('img[data-src]');
  for ( var i = 0, len = images.length; i !== len; i++ ) {
    var img = images[i];
    img.setAttribute('src', img.getAttribute('data-src'));
    img.removeAttribute('data-src');

    var srcset = img.getAttribute('data-srcset');
    if ( srcset ) {
      img.setAttribute('srcset', img.getAttribute('data-srcset'));
      img.removeAttribute('data-srcset');
    }

  }

  var imagesLoadedInstance;
  if ( this.layout.options.useImagesLoaded && window.imagesLoaded ) {
    imagesLoadedInstance = window.imagesLoaded( this.element );
  }

  this.layout.dispatchEvent( 'itemLoading', null, [ this, imagesLoadedInstance ] );
};

var _destroy = proto.destroy;
proto.destroy = function() {
  // call super
  _destroy.apply( this, arguments );
  // reset display, #741
  this.css({
    display: ''
  });
};

return Item;

}));

/**
 * Isotope LayoutMode
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'isotope-layout/js/layout-mode',[
        'get-size/get-size',
        'outlayer/outlayer'
      ],
      factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('get-size'),
      require('outlayer')
    );
  } else {
    // browser global
    window.Isotope = window.Isotope || {};
    window.Isotope.LayoutMode = factory(
      window.getSize,
      window.Outlayer
    );
  }

}( window, function factory( getSize, Outlayer ) {
  'use strict';

  // layout mode class
  function LayoutMode( isotope ) {
    this.isotope = isotope;
    // link properties
    if ( isotope ) {
      this.options = isotope.options[ this.namespace ];
      this.element = isotope.element;
      this.items = isotope.filteredItems;
      this.size = isotope.size;
    }
  }

  var proto = LayoutMode.prototype;

  /**
   * some methods should just defer to default Outlayer method
   * and reference the Isotope instance as `this`
  **/
  var facadeMethods = [
    '_resetLayout',
    '_getItemLayoutPosition',
    '_manageStamp',
    '_getContainerSize',
    '_getElementOffset',
    'needsResizeLayout',
    '_getOption'
  ];

  facadeMethods.forEach( function( methodName ) {
    proto[ methodName ] = function() {
      return Outlayer.prototype[ methodName ].apply( this.isotope, arguments );
    };
  });

  // -----  ----- //

  // for horizontal layout modes, check vertical size
  proto.needsVerticalResizeLayout = function() {
    // don't trigger if size did not change
    var size = getSize( this.isotope.element );
    // check that this.size and size are there
    // IE8 triggers resize on body size change, so they might not be
    var hasSizes = this.isotope.size && size;
    return hasSizes && size.innerHeight != this.isotope.size.innerHeight;
  };

  // ----- measurements ----- //

  proto._getMeasurement = function() {
    this.isotope._getMeasurement.apply( this, arguments );
  };

  proto.getColumnWidth = function() {
    this.getSegmentSize( 'column', 'Width' );
  };

  proto.getRowHeight = function() {
    this.getSegmentSize( 'row', 'Height' );
  };

  /**
   * get columnWidth or rowHeight
   * segment: 'column' or 'row'
   * size 'Width' or 'Height'
  **/
  proto.getSegmentSize = function( segment, size ) {
    var segmentName = segment + size;
    var outerSize = 'outer' + size;
    // columnWidth / outerWidth // rowHeight / outerHeight
    this._getMeasurement( segmentName, outerSize );
    // got rowHeight or columnWidth, we can chill
    if ( this[ segmentName ] ) {
      return;
    }
    // fall back to item of first element
    var firstItemSize = this.getFirstItemSize();
    this[ segmentName ] = firstItemSize && firstItemSize[ outerSize ] ||
      // or size of container
      this.isotope.size[ 'inner' + size ];
  };

  proto.getFirstItemSize = function() {
    var firstItem = this.isotope.filteredItems[0];
    return firstItem && firstItem.element && getSize( firstItem.element );
  };

  // ----- methods that should reference isotope ----- //

  proto.layout = function() {
    this.isotope.layout.apply( this.isotope, arguments );
  };

  proto.getSize = function() {
    this.isotope.getSize();
    this.size = this.isotope.size;
  };

  // -------------------------- create -------------------------- //

  LayoutMode.modes = {};

  LayoutMode.create = function( namespace, options ) {

    function Mode() {
      LayoutMode.apply( this, arguments );
    }

    Mode.prototype = Object.create( proto );
    Mode.prototype.constructor = Mode;

    // default options
    if ( options ) {
      Mode.options = options;
    }

    Mode.prototype.namespace = namespace;
    // register in Isotope
    LayoutMode.modes[ namespace ] = Mode;

    return Mode;
  };

  return LayoutMode;

}));

/*!
 * Masonry v4.2.1
 * Cascading grid layout library
 * https://masonry.desandro.com
 * MIT License
 * by David DeSandro
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'masonry-layout/masonry',[
        'outlayer/outlayer',
        'get-size/get-size'
      ],
      factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('outlayer'),
      require('get-size')
    );
  } else {
    // browser global
    window.Masonry = factory(
      window.Outlayer,
      window.getSize
    );
  }

}( window, function factory( Outlayer, getSize ) {



// -------------------------- masonryDefinition -------------------------- //

  // create an Outlayer layout class
  var Masonry = Outlayer.create('masonry');
  // isFitWidth -> fitWidth
  Masonry.compatOptions.fitWidth = 'isFitWidth';

  var proto = Masonry.prototype;

  proto._resetLayout = function() {
    this.getSize();
    this._getMeasurement( 'columnWidth', 'outerWidth' );
    this._getMeasurement( 'gutter', 'outerWidth' );
    this.measureColumns();

    // reset column Y
    this.colYs = [];
    for ( var i=0; i < this.cols; i++ ) {
      this.colYs.push( 0 );
    }

    this.maxY = 0;
    this.horizontalColIndex = 0;
  };

  proto.measureColumns = function() {
    this.getContainerWidth();
    // if columnWidth is 0, default to outerWidth of first item
    if ( !this.columnWidth ) {
      var firstItem = this.items[0];
      var firstItemElem = firstItem && firstItem.element;
      // columnWidth fall back to item of first element
      this.columnWidth = firstItemElem && getSize( firstItemElem ).outerWidth ||
        // if first elem has no width, default to size of container
        this.containerWidth;
    }

    var columnWidth = this.columnWidth += this.gutter;

    // calculate columns
    var containerWidth = this.containerWidth + this.gutter;
    var cols = containerWidth / columnWidth;
    // fix rounding errors, typically with gutters
    var excess = columnWidth - containerWidth % columnWidth;
    // if overshoot is less than a pixel, round up, otherwise floor it
    var mathMethod = excess && excess < 1 ? 'round' : 'floor';
    cols = Math[ mathMethod ]( cols );
    this.cols = Math.max( cols, 1 );
  };

  proto.getContainerWidth = function() {
    // container is parent if fit width
    var isFitWidth = this._getOption('fitWidth');
    var container = isFitWidth ? this.element.parentNode : this.element;
    // check that this.size and size are there
    // IE8 triggers resize on body size change, so they might not be
    var size = getSize( container );
    this.containerWidth = size && size.innerWidth;
  };

  proto._getItemLayoutPosition = function( item ) {
    item.getSize();
    // how many columns does this brick span
    var remainder = item.size.outerWidth % this.columnWidth;
    var mathMethod = remainder && remainder < 1 ? 'round' : 'ceil';
    // round if off by 1 pixel, otherwise use ceil
    var colSpan = Math[ mathMethod ]( item.size.outerWidth / this.columnWidth );
    colSpan = Math.min( colSpan, this.cols );
    // use horizontal or top column position
    var colPosMethod = this.options.horizontalOrder ?
      '_getHorizontalColPosition' : '_getTopColPosition';
    var colPosition = this[ colPosMethod ]( colSpan, item );
    // position the brick
    var position = {
      x: this.columnWidth * colPosition.col,
      y: colPosition.y
    };
    // apply setHeight to necessary columns
    var setHeight = colPosition.y + item.size.outerHeight;
    var setMax = colSpan + colPosition.col;
    for ( var i = colPosition.col; i < setMax; i++ ) {
      this.colYs[i] = setHeight;
    }

    return position;
  };

  proto._getTopColPosition = function( colSpan ) {
    var colGroup = this._getTopColGroup( colSpan );
    // get the minimum Y value from the columns
    var minimumY = Math.min.apply( Math, colGroup );

    return {
      col: colGroup.indexOf( minimumY ),
      y: minimumY,
    };
  };

  /**
   * @param {Number} colSpan - number of columns the element spans
   * @returns {Array} colGroup
   */
  proto._getTopColGroup = function( colSpan ) {
    if ( colSpan < 2 ) {
      // if brick spans only one column, use all the column Ys
      return this.colYs;
    }

    var colGroup = [];
    // how many different places could this brick fit horizontally
    var groupCount = this.cols + 1 - colSpan;
    // for each group potential horizontal position
    for ( var i = 0; i < groupCount; i++ ) {
      colGroup[i] = this._getColGroupY( i, colSpan );
    }
    return colGroup;
  };

  proto._getColGroupY = function( col, colSpan ) {
    if ( colSpan < 2 ) {
      return this.colYs[ col ];
    }
    // make an array of colY values for that one group
    var groupColYs = this.colYs.slice( col, col + colSpan );
    // and get the max value of the array
    return Math.max.apply( Math, groupColYs );
  };

  // get column position based on horizontal index. #873
  proto._getHorizontalColPosition = function( colSpan, item ) {
    var col = this.horizontalColIndex % this.cols;
    var isOver = colSpan > 1 && col + colSpan > this.cols;
    // shift to next row if item can't fit on current row
    col = isOver ? 0 : col;
    // don't let zero-size items take up space
    var hasSize = item.size.outerWidth && item.size.outerHeight;
    this.horizontalColIndex = hasSize ? col + colSpan : this.horizontalColIndex;

    return {
      col: col,
      y: this._getColGroupY( col, colSpan ),
    };
  };

  proto._manageStamp = function( stamp ) {
    var stampSize = getSize( stamp );
    var offset = this._getElementOffset( stamp );
    // get the columns that this stamp affects
    var isOriginLeft = this._getOption('originLeft');
    var firstX = isOriginLeft ? offset.left : offset.right;
    var lastX = firstX + stampSize.outerWidth;
    var firstCol = Math.floor( firstX / this.columnWidth );
    firstCol = Math.max( 0, firstCol );
    var lastCol = Math.floor( lastX / this.columnWidth );
    // lastCol should not go over if multiple of columnWidth #425
    lastCol -= lastX % this.columnWidth ? 0 : 1;
    lastCol = Math.min( this.cols - 1, lastCol );
    // set colYs to bottom of the stamp

    var isOriginTop = this._getOption('originTop');
    var stampMaxY = ( isOriginTop ? offset.top : offset.bottom ) +
      stampSize.outerHeight;
    for ( var i = firstCol; i <= lastCol; i++ ) {
      this.colYs[i] = Math.max( stampMaxY, this.colYs[i] );
    }
  };

  proto._getContainerSize = function() {
    this.maxY = Math.max.apply( Math, this.colYs );
    var size = {
      height: this.maxY
    };

    if ( this._getOption('fitWidth') ) {
      size.width = this._getContainerFitWidth();
    }

    return size;
  };

  proto._getContainerFitWidth = function() {
    var unusedCols = 0;
    // count unused columns
    var i = this.cols;
    while ( --i ) {
      if ( this.colYs[i] !== 0 ) {
        break;
      }
      unusedCols++;
    }
    // fit container to columns that have been used
    return ( this.cols - unusedCols ) * this.columnWidth - this.gutter;
  };

  proto.needsResizeLayout = function() {
    var previousWidth = this.containerWidth;
    this.getContainerWidth();
    return previousWidth != this.containerWidth;
  };

  return Masonry;

}));

/*!
 * Masonry layout mode
 * sub-classes Masonry
 * https://masonry.desandro.com
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'isotope-layout/js/layout-modes/masonry',[
        '../layout-mode',
        'masonry-layout/masonry'
      ],
      factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('../layout-mode')
      //require('masonry-layout')
    );
  } else {
    // browser global
    factory(
      window.Isotope.LayoutMode,
      window.Masonry
    );
  }

}( window, function factory( LayoutMode, Masonry ) {
'use strict';

// -------------------------- masonryDefinition -------------------------- //

  // create an Outlayer layout class
  var MasonryMode = LayoutMode.create('masonry');

  var proto = MasonryMode.prototype;

  var keepModeMethods = {
    _getElementOffset: true,
    layout: true,
    _getMeasurement: true
  };

  // inherit Masonry prototype
  for ( var method in Masonry.prototype ) {
    // do not inherit mode methods
    if ( !keepModeMethods[ method ] ) {
      proto[ method ] = Masonry.prototype[ method ];
    }
  }

  var measureColumns = proto.measureColumns;
  proto.measureColumns = function() {
    // set items, used if measuring first item
    this.items = this.isotope.filteredItems;
    measureColumns.call( this );
  };

  // point to mode options for fitWidth
  var _getOption = proto._getOption;
  proto._getOption = function( option ) {
    if ( option == 'fitWidth' ) {
      return this.options.isFitWidth !== undefined ?
        this.options.isFitWidth : this.options.fitWidth;
    }
    return _getOption.apply( this.isotope, arguments );
  };

  return MasonryMode;

}));

/**
 * justifyRows layout mode
 */

( function( window, factory ) {
  'use strict';
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'isotope-layout/js/layout-modes/justify-rows',[
        '../layout-mode'
      ],
      factory );
  } else if ( typeof exports == 'object' ) {
    // CommonJS
    module.exports = factory(
      require('../layout-mode')
    );
  } else {
    // browser global
    factory(
      window.Isotope.LayoutMode
    );
  }

}( window, function factory( LayoutMode ) {
'use strict';

var JustifyRows = LayoutMode.create('justifyRows');

var proto = JustifyRows.prototype;

proto._resetLayout = function() {
  this.x = 0;
  this.y = 0;
  this.maxY = 0;
  this._getMeasurement( 'gutter', 'outerWidth' );
};

proto._getRowHeight = function( rowItems, containerWidth ) {
  containerWidth = containerWidth - rowItems.length * this.gutter;
  var totalHeight = 0;
  for ( var i = 0, len = rowItems.length; i !== len; i++ ) {
    var itemEle = rowItems[i].element,
        w = parseInt( itemEle.getAttribute( 'data-width' ), 10 ) || rowItems[i].size.outerWidth,
        h = parseInt( itemEle.getAttribute( 'data-height' ), 10 ) || rowItems[i].size.outerHeight;

    totalHeight += w / h;
  }

  return containerWidth / totalHeight;
};

proto._resizeItems = function( rowItems, rowHeight ) {
  for ( var i = 0, len = rowItems.length; i !== len; i++ ) {
    var itemEle = rowItems[i].element,
        w = parseInt( itemEle.getAttribute( 'data-width' ), 10 ) || rowItems[i].size.outerWidth,
        h = parseInt( itemEle.getAttribute( 'data-height' ), 10 ) || rowItems[i].size.outerHeight;

    itemEle.style.width = rowHeight * w / h + 'px';
    itemEle.style.height = rowHeight + 'px';
  }
};

proto._beforeLayout = function() {
  var maxHeight = this.options.maxHeight || 200,
      containerWidth = this.isotope.size.innerWidth + this.gutter;

  var checkItems = this.isotope.filteredItems.slice( 0 ),
      row, rowHeight;
  
  newRow: while ( checkItems.length > 0 ) {
    
    for ( var i = 0, len = checkItems.length; i !== len; i++ ) {
      row = checkItems.slice( 0, i + 1 ),
      rowHeight = this._getRowHeight( row, containerWidth );

      if ( rowHeight < maxHeight ) {
        this._resizeItems( row, rowHeight );
        checkItems = checkItems.slice( i + 1 );
        continue newRow;
      }
    }

    // last row
    this._resizeItems( row, Math.min( rowHeight, maxHeight ) );
    break;  
  }
};

proto._getItemLayoutPosition = function( item ) {
  item.getSize();
  var itemWidth = item.size.outerWidth + this.gutter;
  // if this element cannot fit in the current row
  var containerWidth = this.isotope.size.innerWidth + this.gutter;
  if ( this.x !== 0 && itemWidth + this.x > containerWidth ) {
    this.x = 0;
    this.y = this.maxY;
  }

  var position = {
    x: this.x,
    y: this.y
  };

  this.maxY = Math.max( this.maxY, this.y + item.size.outerHeight );
  this.x += itemWidth;

  return position;
};

proto._getContainerSize = function() {
  return { height: this.maxY };
};

return JustifyRows;

}));

/**
 * fitRows layout mode
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'isotope-layout/js/layout-modes/fit-rows',[
        '../layout-mode'
      ],
      factory );
  } else if ( typeof exports == 'object' ) {
    // CommonJS
    module.exports = factory(
      require('../layout-mode')
    );
  } else {
    // browser global
    factory(
      window.Isotope.LayoutMode
    );
  }

}( window, function factory( LayoutMode ) {
'use strict';

var FitRows = LayoutMode.create('fitRows');

var proto = FitRows.prototype;

proto._resetLayout = function() {
  this.x = 0;
  this.y = 0;
  this.maxY = 0;
  this._getMeasurement( 'gutter', 'outerWidth' );
};

proto._getItemLayoutPosition = function( item ) {
  item.getSize();

  var itemWidth = item.size.outerWidth + this.gutter;
  // if this element cannot fit in the current row
  var containerWidth = this.isotope.size.innerWidth + this.gutter;
  if ( this.x !== 0 && itemWidth + this.x > containerWidth ) {
    this.x = 0;
    this.y = this.maxY;
  }

  var position = {
    x: this.x,
    y: this.y
  };

  this.maxY = Math.max( this.maxY, this.y + item.size.outerHeight );
  this.x += itemWidth;

  return position;
};

proto._getContainerSize = function() {
  return { height: this.maxY };
};

return FitRows;

}));

/**
 * vertical layout mode
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'isotope-layout/js/layout-modes/vertical',[
        '../layout-mode'
      ],
      factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('../layout-mode')
    );
  } else {
    // browser global
    factory(
      window.Isotope.LayoutMode
    );
  }

}( window, function factory( LayoutMode ) {
'use strict';

var Vertical = LayoutMode.create( 'vertical', {
  horizontalAlignment: 0
});

var proto = Vertical.prototype;

proto._resetLayout = function() {
  this.y = 0;
};

proto._getItemLayoutPosition = function( item ) {
  item.getSize();
  var x = ( this.isotope.size.innerWidth - item.size.outerWidth ) *
    this.options.horizontalAlignment;
  var y = this.y;
  this.y += item.size.outerHeight;
  return { x: x, y: y };
};

proto._getContainerSize = function() {
  return { height: this.y };
};

return Vertical;

}));

/*!
 * Isotope v3.0.6
 *
 * Licensed GPLv3 for open source use
 * or Isotope Commercial License for commercial use
 *
 * https://isotope.metafizzy.co
 * Copyright 2010-2018 Metafizzy
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( [
        'outlayer/outlayer',
        'get-size/get-size',
        'desandro-matches-selector/matches-selector',
        'fizzy-ui-utils/utils',
        'isotope-layout/js/item',
        'isotope-layout/js/layout-mode',
        // include default layout modes
        'isotope-layout/js/layout-modes/masonry',
        'isotope-layout/js/layout-modes/justify-rows',
        'isotope-layout/js/layout-modes/fit-rows',
        'isotope-layout/js/layout-modes/vertical'
      ],
      function( Outlayer, getSize, matchesSelector, utils, Item, LayoutMode ) {
        return factory( window, Outlayer, getSize, matchesSelector, utils, Item, LayoutMode );
      });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('outlayer'),
      require('get-size'),
      require('desandro-matches-selector'),
      require('fizzy-ui-utils'),
      require('isotope-layout/js/item'),
      require('isotope-layout/js/layout-mode'),
      // include default layout modes
      require('isotope-layout/js/layout-modes/masonry'),
      require('isotope-layout/js/layout-modes/fit-rows'),
      require('isotope-layout/js/layout-modes/justify-rows'),
      require('isotope-layout/js/layout-modes/vertical')
    );
  } else {
    // browser global
    window.Isotope = factory(
      window,
      window.Outlayer,
      window.getSize,
      window.matchesSelector,
      window.fizzyUIUtils,
      window.Isotope.Item,
      window.Isotope.LayoutMode
    );
  }

}( window, function factory( window, Outlayer, getSize, matchesSelector, utils,
  Item, LayoutMode ) {



// -------------------------- vars -------------------------- //

var jQuery = window.jQuery;

// -------------------------- helpers -------------------------- //

var trim = String.prototype.trim ?
  function( str ) {
    return str.trim();
  } :
  function( str ) {
    return str.replace( /^\s+|\s+$/g, '' );
  };

// -------------------------- isotopeDefinition -------------------------- //

  // create an Outlayer layout class
  var Isotope = Outlayer.create( 'isotope', {
    layoutMode: 'masonry',
    isJQueryFiltering: true,
    sortAscending: true,
    pagination: false,
    inPage: 20,
    page:1,
    useImagesLoaded: true,
    lazyload:false,
    resizeTransition: true
  });

  Isotope.Item = Item;
  Isotope.LayoutMode = LayoutMode;

  var proto = Isotope.prototype;

  proto._create = function() {
    this.itemGUID = 0;
    // functions that sort items
    this._sorters = {};
    this._getSorters();
    // call super
    Outlayer.prototype._create.call( this );

    // create layout modes
    this.modes = {};
    // start filteredItems with all items
    this.filteredItems = this.items;
    // keep of track of sortBys
    this.sortHistory = [ 'original-order' ];
    // create from registered layout modes
    for ( var name in LayoutMode.modes ) {
      this._initLayoutMode( name );
    }
  };

  proto.reloadItems = function() {
    // reset item ID counter
    this.itemGUID = 0;
    // call super
    Outlayer.prototype.reloadItems.call( this );
  };

  proto._itemize = function() {
    var items = Outlayer.prototype._itemize.apply( this, arguments );
    // assign ID for original-order
    for ( var i=0; i < items.length; i++ ) {
      var item = items[i];
      item.id = this.itemGUID++;
    }
    this._updateItemsSortData( items );
    return items;
  };


  // -------------------------- layout -------------------------- //

  proto._initLayoutMode = function( name ) {
    var Mode = LayoutMode.modes[ name ];
    // set mode options
    // HACK extend initial options, back-fill in default options
    var initialOpts = this.options[ name ] || {};
    this.options[ name ] = Mode.options ?
      utils.extend( Mode.options, initialOpts ) : initialOpts;
    // init layout mode instance
    this.modes[ name ] = new Mode( this );
  };


  proto.layout = function() {
    // if first time doing layout, do all magic
    if ( !this._isLayoutInited && this._getOption('initLayout') ) {
      this.arrange();
      return;
    }
    this._layout();
  };

  // private method to be used in layout() & magic()
  proto._layout = function() {
    // don't animate first layout
    var isInstant = this._getIsInstant();
    // layout flow
    this._resetLayout();
    this._manageStamps();

    this.layoutItems( this.filteredItems, isInstant );

    // flag for initalized
    this._isLayoutInited = true;
  };

  //override layoutItems method
  var _layoutItems = Isotope.prototype.layoutItems;
  Isotope.prototype.layoutItems = function( items, isInstant ) {
    this._beforeLayout( items, isInstant );
    _layoutItems.apply( this, arguments );
  };

  // filter + sort + layout
  proto.arrange = function( opts ) {
    // set any options pass
    this.option( opts );
    this._getIsInstant();
    // filter, sort, and layout

    // filter
    var filtered = this._filter( this.items );
    this.filteredItems = filtered.matches;
    this.notPaginatedItems = this.filteredItems;

    this._sort(); 

    if ( this.options.pagination ) {
      var paginationResult = this._pagination();
      filtered.needHide = filtered.needHide.concat( paginationResult.needHide );
      filtered.needReveal = paginationResult.needReveal;
    }

    this._bindArrangeComplete();
    this._hideRevealItems( filtered );

    this._layout();

    // reset isLayoutInstant
    if ( this.options.pagination ) {
      for ( var i = 0, l = this.filteredItems.length; i !== l; i++ ) {
        this.filteredItems[i].isLayoutInstant = false;
      }
    }

  };
  // alias to _init for main plugin method
  Isotope.prototype._init = Isotope.prototype.arrange;

  // hide and reveal items
  proto._hideRevealItems = function( items ) {
    if ( this._isInstant ) {
      this._noTransition( this._hideReveal, [ items ] );
    } else {
      this._hideReveal( items );
    }
  };
  // alias to _init for main plugin method
  proto._init = proto.arrange;

  proto._hideReveal = function( filtered ) {
    this.reveal( filtered.needReveal );
    this.hide( filtered.needHide );
  };


  // HACK
  // Don't animate/transition first layout
  // Or don't animate/transition other layouts
  proto._getIsInstant = function() {
    var isLayoutInstant = this._getOption('layoutInstant');
    var isInstant = isLayoutInstant !== undefined ? isLayoutInstant :
      !this._isLayoutInited;
    this._isInstant = isInstant;
    return isInstant;
  };

  // listen for layoutComplete, hideComplete and revealComplete
  // to trigger arrangeComplete
  proto._bindArrangeComplete = function() {
    // listen for 3 events to trigger arrangeComplete
    var isLayoutComplete, isHideComplete, isRevealComplete;
    var _this = this;
    function arrangeParallelCallback() {
      if ( isLayoutComplete && isHideComplete && isRevealComplete ) {
        _this.dispatchEvent( 'arrangeComplete', null, [ _this.filteredItems ] );
      }
    }
    this.once( 'layoutComplete', function() {
      isLayoutComplete = true;
      arrangeParallelCallback();
    });
    this.once( 'hideComplete', function() {
      isHideComplete = true;
      arrangeParallelCallback();
    });
    this.once( 'revealComplete', function() {
      isRevealComplete = true;
      arrangeParallelCallback();
    });
  };

  // -------------------------- page -------------------------- //
  
  // private method to devide filtered items to pages
  proto._pagination = function() {
    // move to fist page if filter changed
    if ( this._lastFilter !== this.options.filter ) {
      this._lastFilter = this.options.filter;
      this.options.page = 1;
    }

    if ( !this.notPaginatedItems ) {
      // make a copy from filtered items
      this.notPaginatedItems = this.filteredItems;
    }

    var page = this.options.page,
        items = this.notPaginatedItems,
        startItemInPage = ( page - 1 ) * this.options.inPage,
        endItemInPage = startItemInPage + this.options.inPage - 1,
        inPage = [], needHide = [], needReveal = [];

    var totalPages = Math.ceil( items.length / this.options.inPage ),
        pageChanged = this._lastPage !== page || this._totalPages !== totalPages;

    this._lastPage = page;
    this._totalPages = totalPages;

    for ( var i = 0, len = items.length; i !== len; i++ ) {
      var item = items[i];
      // is it in page?
      if ( i >= startItemInPage && i <= endItemInPage ) {
        inPage.push( item );
        if ( item.isHidden ) {
          needReveal.push( item );
          item.isLayoutInstant = true;
        }
      } else if ( !item.isHidden ) {
        needHide.push( item );
      }
    }
    
    // update filtered items
    this.filteredItems = inPage;

    if ( pageChanged ) {
      this.dispatchEvent( 'paginationUpdate', null, [ page, totalPages, inPage ] );
    }

    return {
      matches: inPage,
      needHide: needHide,
      needReveal: needReveal
    };

  };

  // change current page of isotope
  proto.page = function( pageNum ) {
    this.options.page = Math.max( 1, Math.min( pageNum, this.totalPages() ) );
    this._hideRevealItems( this._pagination() );
    this._layout();
  };

  // go to next page
  proto.nextPage = function() {
    this.page( this.options.page + 1 );
  };

  // go to previous page
  proto.previousPage = function() {
    this.page( this.options.page - 1 );
  };

  // go to last page
  proto.lastPage = function() {
    this.page( this.totalPages() );
  };

  // go to first page
  proto.firstPage = function() {
    this.page( 1 );
  };

  // get total pages
  proto.totalPages = function() {
    return this._totalPages;
  };

  // get current page
  proto.currentPage = function() {
    return this.options.page;
  };

  // -------------------------- filter -------------------------- //

  proto._filter = function( items ) {
    var filter = this.options.filter;
    filter = filter || '*';
    var matches = [];
    var hiddenMatched = [];
    var visibleUnmatched = [];

    var test = this._getFilterTest( filter );

    // test each item
    for ( var i=0; i < items.length; i++ ) {
      var item = items[i];
      if ( item.isIgnored ) {
        continue;
      }
      // add item to either matched or unmatched group
      var isMatched = test( item );
      // item.isFilterMatched = isMatched;
      // add to matches if its a match
      if ( isMatched ) {
          matches.push( item );
      }
      // add to additional group if item needs to be hidden or revealed
      if ( isMatched && item.isHidden ) {
        hiddenMatched.push( item );
      } else if ( !isMatched && !item.isHidden ) {
        visibleUnmatched.push( item );
      }
    }

    // return collections of items to be manipulated
    return {
      matches: matches,
      needReveal: hiddenMatched,
      needHide: visibleUnmatched
    };
  };

  // get a jQuery, function, or a matchesSelector test given the filter
  proto._getFilterTest = function( filter ) {
    if ( jQuery && this.options.isJQueryFiltering ) {
      // use jQuery
      return function( item ) {
        return jQuery( item.element ).is( filter );
      };
    }
    if ( typeof filter == 'function' ) {
      // use filter as function
      return function( item ) {
        return filter( item.element );
      };
    }
    // default, use filter as selector string
    return function( item ) {
      return matchesSelector( item.element, filter );
    };
  };

  // -------------------------- sorting -------------------------- //

  /**
   * @params {Array} elems
   * @public
   */
  proto.updateSortData = function( elems ) {
    // get items
    var items;
    if ( elems ) {
      elems = utils.makeArray( elems );
      items = this.getItems( elems );
    } else {
      // update all items if no elems provided
      items = this.items;
    }

    this._getSorters();
    this._updateItemsSortData( items );
  };

  proto._getSorters = function() {
    var getSortData = this.options.getSortData;
    for ( var key in getSortData ) {
      var sorter = getSortData[ key ];
      this._sorters[ key ] = mungeSorter( sorter );
    }
  };

  /**
   * @params {Array} items - of Isotope.Items
   * @private
   */
  proto._updateItemsSortData = function( items ) {
    // do not update if no items
    var len = items && items.length;

    for ( var i=0; len && i < len; i++ ) {
      var item = items[i];
      item.updateSortData();
    }
  };

  // ----- munge sorter ----- //

  // encapsulate this, as we just need mungeSorter
  // other functions in here are just for munging
  var mungeSorter = ( function() {
    // add a magic layer to sorters for convienent shorthands
    // `.foo-bar` will use the text of .foo-bar querySelector
    // `[foo-bar]` will use attribute
    // you can also add parser
    // `.foo-bar parseInt` will parse that as a number
    function mungeSorter( sorter ) {
      // if not a string, return function or whatever it is
      if ( typeof sorter != 'string' ) {
        return sorter;
      }
      // parse the sorter string
      var args = trim( sorter ).split(' ');
      var query = args[0];
      // check if query looks like [an-attribute]
      var attrMatch = query.match( /^\[(.+)\]$/ );
      var attr = attrMatch && attrMatch[1];
      var getValue = getValueGetter( attr, query );
      // use second argument as a parser
      var parser = Isotope.sortDataParsers[ args[1] ];
      // parse the value, if there was a parser
      sorter = parser ? function( elem ) {
        return elem && parser( getValue( elem ) );
      } :
      // otherwise just return value
      function( elem ) {
        return elem && getValue( elem );
      };

      return sorter;
    }

    // get an attribute getter, or get text of the querySelector
    function getValueGetter( attr, query ) {
      // if query looks like [foo-bar], get attribute
      if ( attr ) {
        return function getAttribute( elem ) {
          return elem.getAttribute( attr );
        };
      }

      // otherwise, assume its a querySelector, and get its text
      return function getChildText( elem ) {
        var child = elem.querySelector( query );
        return child && child.textContent;
      };
    }

    return mungeSorter;
  })();

  // parsers used in getSortData shortcut strings
  Isotope.sortDataParsers = {
    'parseInt': function( val ) {
      return parseInt( val, 10 );
    },
    'parseFloat': function( val ) {
      return parseFloat( val );
    }
  };

  // ----- sort method ----- //

  // sort filteredItem order
  proto._sort = function() {
    if ( !this.options.sortBy ) {
      return;
    }
    // keep track of sortBy History
    var sortBys = utils.makeArray( this.options.sortBy );
    if ( !this._getIsSameSortBy( sortBys ) ) {
      // concat all sortBy and sortHistory, add to front, oldest goes in last
      this.sortHistory = sortBys.concat( this.sortHistory );
    }
    // sort magic
    var itemSorter = getItemSorter( this.sortHistory, this.options.sortAscending );
    if ( this.options.pagination ) {
      this.notPaginatedItems.sort( itemSorter );
    } else {
      this.filteredItems.sort( itemSorter );
    }
  };

  // check if sortBys is same as start of sortHistory
  proto._getIsSameSortBy = function( sortBys ) {
    for ( var i=0; i < sortBys.length; i++ ) {
      if ( sortBys[i] != this.sortHistory[i] ) {
        return false;
      }
    }
    return true;
  };

  // returns a function used for sorting
  function getItemSorter( sortBys, sortAsc ) {
    return function sorter( itemA, itemB ) {
      // cycle through all sortKeys
      for ( var i = 0; i < sortBys.length; i++ ) {
        var sortBy = sortBys[i];
        var a = itemA.sortData[ sortBy ];
        var b = itemB.sortData[ sortBy ];
        if ( a > b || a < b ) {
          // if sortAsc is an object, use the value given the sortBy key
          var isAscending = sortAsc[ sortBy ] !== undefined ? sortAsc[ sortBy ] : sortAsc;
          var direction = isAscending ? 1 : -1;
          return ( a > b ? 1 : -1 ) * direction;
        }
      }
      return 0;
    };
  }

  // -------------------------- methods -------------------------- //

  // get layout mode
  proto._mode = function() {
    var layoutMode = this.options.layoutMode;
    var mode = this.modes[ layoutMode ];
    if ( !mode ) {
      // TODO console.error
      throw new Error( 'No layout mode: ' + layoutMode );
    }
    // HACK sync mode's options
    // any options set after init for layout mode need to be synced
    mode.options = this.options[ layoutMode ];
    return mode;
  };

  proto._resetLayout = function() {
    // trigger original reset layout
    Outlayer.prototype._resetLayout.call( this );
    this._mode()._resetLayout();
  };
  
  Isotope.prototype._beforeLayout = function ( items, isInstant ) {
    var mode = this._mode();
    if ( mode._beforeLayout ) {
      mode._beforeLayout( items, isInstant );
    }
  };  

  proto._getItemLayoutPosition = function( item  ) {
    return this._mode()._getItemLayoutPosition( item );
  };

  proto._manageStamp = function( stamp ) {
    this._mode()._manageStamp( stamp );
  };

  proto._getContainerSize = function() {
    return this._mode()._getContainerSize();
  };

  proto.needsResizeLayout = function() {
    return this._mode().needsResizeLayout();
  };

  // override resize method from outlayer
  Isotope.prototype.resize = function() {
    // don't trigger if size did not change
    // or if resize was unbound. See #9
    if ( !this.isResizeBound || !this.needsResizeLayout() ) {
      return;
    }

    // disable transition effect on page resize
    if ( !this.options.resizeTransition ) {
      this._noTransition( this.layout );
    } else {
      this.layout();
    }

  };

  // -------------------------- adding & removing -------------------------- //

  // HEADS UP overwrites default Outlayer appended
  proto.appended = function( elems ) {
    var items = this.addItems( elems );
    if ( !items.length ) {
      return;
    }

    var pagination = this.options.pagination;

    // filter, layout, reveal new items
    var filteredItems = this._filterRevealAdded( items, !pagination );
    if ( !pagination ) {
      // add to filteredItems
      this.filteredItems = this.filteredItems.concat( filteredItems );
    } else {
      // add new items to the notPaginatedItems instead of filtered items, it will be filtered again by pagination method next.
      this.notPaginatedItems = this.notPaginatedItems.concat( filteredItems );
      // start new layout
      this._resetLayout();
      this._manageStamps();
      var paginateResult = this._pagination();
      this._hideRevealItems( paginateResult );
      this.layoutItems( this.filteredItems );
    }

  };

  // HEADS UP overwrites default Outlayer prepended
  proto.prepended = function( elems ) {
    var items = this._itemize( elems );
    if ( !items.length ) {
      return;
    }

    // start new layout
    this._resetLayout();
    this._manageStamps();
    var pagination = this.options.pagination;

    // filter, layout, reveal new items
    var filteredItems = this._filterRevealAdded( items, !pagination );

    // layout previous items
    if ( !pagination )  { 
      this.layoutItems( this.filteredItems );
      // add to items and filteredItems
      this.filteredItems = filteredItems.concat( this.filteredItems );
    } else {
      // add new items to the notPaginatedItems instead of filtered items, it will be filtered again by pagination method next.
      this.notPaginatedItems = filteredItems.concat( this.notPaginatedItems );
      var paginateResult = this._pagination(); 
      this._hideRevealItems( paginateResult );
      this.layoutItems( this.filteredItems );
    }

    this.items = items.concat( this.items );
  };

  proto._filterRevealAdded = function( items ) {
    var filtered = this._filter( items );
    this.hide( filtered.needHide );
    // reveal all new items
    this.reveal( filtered.matches );
    // layout new items, no transition
    this.layoutItems( filtered.matches, true );
    return filtered.matches;
  };

  /**
   * Filter, sort, and layout newly-appended item elements
   * @param {Array or NodeList or Element} elems
   */
  proto.insert = function( elems ) {
    var items = this.addItems( elems );
    if ( !items.length ) {
      return;
    }
    // append item elements
    var i, item;
    var len = items.length;
    for ( i=0; i < len; i++ ) {
      item = items[i];
      this.element.appendChild( item.element );
    }
    // filter new stuff
    var filteredInsertItems = this._filter( items ).matches;
    // set flag
    for ( i=0; i < len; i++ ) {
      items[i].isLayoutInstant = true;
    }
    this.arrange();
    // reset flag
    for ( i=0; i < len; i++ ) {
      delete items[i].isLayoutInstant;
    }
    this.reveal( filteredInsertItems );
  };

  var _remove = proto.remove;
  proto.remove = function( elems ) {
    elems = utils.makeArray( elems );
    var removeItems = this.getItems( elems );
    // do regular thing
    _remove.call( this, elems );
    // bail if no items to remove
    var len = removeItems && removeItems.length;
    // remove elems from filteredItems
    for ( var i=0; len && i < len; i++ ) {
      var item = removeItems[i];
      // remove item from collection
      utils.removeFrom( this.filteredItems, item );
    }
  };

  proto.shuffle = function() {
    // update random sortData
    for ( var i=0; i < this.items.length; i++ ) {
      var item = this.items[i];
      item.sortData.random = Math.random();
    }
    this.options.sortBy = 'random';
    this._sort();
    this._layout();
  };

  /**
   * trigger fn without transition
   * kind of hacky to have this in the first place
   * @param {Function} fn
   * @param {Array} args
   * @returns ret
   * @private
   */
  proto._noTransition = function( fn, args ) {
    // save transitionDuration before disabling
    var transitionDuration = this.options.transitionDuration;
    // disable transition
    this.options.transitionDuration = 0;
    // do it
    var returnValue = fn.apply( this, args );
    // re-enable transition for reveal
    this.options.transitionDuration = transitionDuration;
    return returnValue;
  };

  // ----- helper methods ----- //

  /**
   * getter method for getting filtered item elements
   * @returns {Array} elems - collection of item elements
   */
  proto.getFilteredItemElements = function() {
    return this.filteredItems.map( function( item ) {
      return item.element;
    });
  };

  // -----  ----- //

  return Isotope;

}));


/*! 
 * 
 * ================== js/libs/plugins/packery-mode.pkgd.js =================== 
 **/ 

/*!
 * Packery layout mode PACKAGED v2.0.0
 * sub-classes Packery
 */

/**
 * Rect
 * low-level utility class for basic geometry
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /* globals define, module */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'packery/js/rect',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory();
  } else {
    // browser global
    window.Packery = window.Packery || {};
    window.Packery.Rect = factory();
  }

}( window, function factory() {


// -------------------------- Rect -------------------------- //

function Rect( props ) {
  // extend properties from defaults
  for ( var prop in Rect.defaults ) {
    this[ prop ] = Rect.defaults[ prop ];
  }

  for ( prop in props ) {
    this[ prop ] = props[ prop ];
  }

}

Rect.defaults = {
  x: 0,
  y: 0,
  width: 0,
  height: 0
};

var proto = Rect.prototype;

/**
 * Determines whether or not this rectangle wholly encloses another rectangle or point.
 * @param {Rect} rect
 * @returns {Boolean}
**/
proto.contains = function( rect ) {
  // points don't have width or height
  var otherWidth = rect.width || 0;
  var otherHeight = rect.height || 0;
  return this.x <= rect.x &&
    this.y <= rect.y &&
    this.x + this.width >= rect.x + otherWidth &&
    this.y + this.height >= rect.y + otherHeight;
};

/**
 * Determines whether or not the rectangle intersects with another.
 * @param {Rect} rect
 * @returns {Boolean}
**/
proto.overlaps = function( rect ) {
  var thisRight = this.x + this.width;
  var thisBottom = this.y + this.height;
  var rectRight = rect.x + rect.width;
  var rectBottom = rect.y + rect.height;

  // http://stackoverflow.com/a/306332
  return this.x < rectRight &&
    thisRight > rect.x &&
    this.y < rectBottom &&
    thisBottom > rect.y;
};

/**
 * @param {Rect} rect - the overlapping rect
 * @returns {Array} freeRects - rects representing the area around the rect
**/
proto.getMaximalFreeRects = function( rect ) {

  // if no intersection, return false
  if ( !this.overlaps( rect ) ) {
    return false;
  }

  var freeRects = [];
  var freeRect;

  var thisRight = this.x + this.width;
  var thisBottom = this.y + this.height;
  var rectRight = rect.x + rect.width;
  var rectBottom = rect.y + rect.height;

  // top
  if ( this.y < rect.y ) {
    freeRect = new Rect({
      x: this.x,
      y: this.y,
      width: this.width,
      height: rect.y - this.y
    });
    freeRects.push( freeRect );
  }

  // right
  if ( thisRight > rectRight ) {
    freeRect = new Rect({
      x: rectRight,
      y: this.y,
      width: thisRight - rectRight,
      height: this.height
    });
    freeRects.push( freeRect );
  }

  // bottom
  if ( thisBottom > rectBottom ) {
    freeRect = new Rect({
      x: this.x,
      y: rectBottom,
      width: this.width,
      height: thisBottom - rectBottom
    });
    freeRects.push( freeRect );
  }

  // left
  if ( this.x < rect.x ) {
    freeRect = new Rect({
      x: this.x,
      y: this.y,
      width: rect.x - this.x,
      height: this.height
    });
    freeRects.push( freeRect );
  }

  return freeRects;
};

proto.canFit = function( rect ) {
  return this.width >= rect.width && this.height >= rect.height;
};

return Rect;

}));

/**
 * Packer
 * bin-packing algorithm
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'packery/js/packer',[ './rect' ], factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('./rect')
    );
  } else {
    // browser global
    var Packery = window.Packery = window.Packery || {};
    Packery.Packer = factory( Packery.Rect );
  }

}( window, function factory( Rect ) {


// -------------------------- Packer -------------------------- //

/**
 * @param {Number} width
 * @param {Number} height
 * @param {String} sortDirection
 *   topLeft for vertical, leftTop for horizontal
 */
function Packer( width, height, sortDirection ) {
  this.width = width || 0;
  this.height = height || 0;
  this.sortDirection = sortDirection || 'downwardLeftToRight';

  this.reset();
}

var proto = Packer.prototype;

proto.reset = function() {
  this.spaces = [];

  var initialSpace = new Rect({
    x: 0,
    y: 0,
    width: this.width,
    height: this.height
  });

  this.spaces.push( initialSpace );
  // set sorter
  this.sorter = sorters[ this.sortDirection ] || sorters.downwardLeftToRight;
};

// change x and y of rect to fit with in Packer's available spaces
proto.pack = function( rect ) {
  for ( var i=0; i < this.spaces.length; i++ ) {
    var space = this.spaces[i];
    if ( space.canFit( rect ) ) {
      this.placeInSpace( rect, space );
      break;
    }
  }
};

proto.columnPack = function( rect ) {
  for ( var i=0; i < this.spaces.length; i++ ) {
    var space = this.spaces[i];
    var canFitInSpaceColumn = space.x <= rect.x &&
      space.x + space.width >= rect.x + rect.width &&
      space.height >= rect.height - 0.01; // fudge number for rounding error
    if ( canFitInSpaceColumn ) {
      rect.y = space.y;
      this.placed( rect );
      break;
    }
  }
};

proto.rowPack = function( rect ) {
  for ( var i=0; i < this.spaces.length; i++ ) {
    var space = this.spaces[i];
    var canFitInSpaceRow = space.y <= rect.y &&
      space.y + space.height >= rect.y + rect.height &&
      space.width >= rect.width - 0.01; // fudge number for rounding error
    if ( canFitInSpaceRow ) {
      rect.x = space.x;
      this.placed( rect );
      break;
    }
  }
};

proto.placeInSpace = function( rect, space ) {
  // place rect in space
  rect.x = space.x;
  rect.y = space.y;

  this.placed( rect );
};

// update spaces with placed rect
proto.placed = function( rect ) {
  // update spaces
  var revisedSpaces = [];
  for ( var i=0; i < this.spaces.length; i++ ) {
    var space = this.spaces[i];
    var newSpaces = space.getMaximalFreeRects( rect );
    // add either the original space or the new spaces to the revised spaces
    if ( newSpaces ) {
      revisedSpaces.push.apply( revisedSpaces, newSpaces );
    } else {
      revisedSpaces.push( space );
    }
  }

  this.spaces = revisedSpaces;

  this.mergeSortSpaces();
};

proto.mergeSortSpaces = function() {
  // remove redundant spaces
  Packer.mergeRects( this.spaces );
  this.spaces.sort( this.sorter );
};

// add a space back
proto.addSpace = function( rect ) {
  this.spaces.push( rect );
  this.mergeSortSpaces();
};

// -------------------------- utility functions -------------------------- //

/**
 * Remove redundant rectangle from array of rectangles
 * @param {Array} rects: an array of Rects
 * @returns {Array} rects: an array of Rects
**/
Packer.mergeRects = function( rects ) {
  var i = 0;
  var rect = rects[i];

  rectLoop:
  while ( rect ) {
    var j = 0;
    var compareRect = rects[ i + j ];

    while ( compareRect ) {
      if  ( compareRect == rect ) {
        j++; // next
      } else if ( compareRect.contains( rect ) ) {
        // remove rect
        rects.splice( i, 1 );
        rect = rects[i]; // set next rect
        continue rectLoop; // bail on compareLoop
      } else if ( rect.contains( compareRect ) ) {
        // remove compareRect
        rects.splice( i + j, 1 );
      } else {
        j++;
      }
      compareRect = rects[ i + j ]; // set next compareRect
    }
    i++;
    rect = rects[i];
  }

  return rects;
};


// -------------------------- sorters -------------------------- //

// functions for sorting rects in order
var sorters = {
  // top down, then left to right
  downwardLeftToRight: function( a, b ) {
    return a.y - b.y || a.x - b.x;
  },
  // left to right, then top down
  rightwardTopToBottom: function( a, b ) {
    return a.x - b.x || a.y - b.y;
  }
};


// --------------------------  -------------------------- //

return Packer;

}));

/**
 * Packery Item Element
**/

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'packery/js/item',[
        'outlayer/outlayer',
        './rect'
      ],
      factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('outlayer'),
      require('./rect')
    );
  } else {
    // browser global
    window.Packery.Item = factory(
      window.Outlayer,
      window.Packery.Rect
    );
  }

}( window, function factory( Outlayer, Rect ) {


// -------------------------- Item -------------------------- //

var docElemStyle = document.documentElement.style;

var transformProperty = typeof docElemStyle.transform == 'string' ?
  'transform' : 'WebkitTransform';

// sub-class Item
var Item = function PackeryItem() {
  Outlayer.Item.apply( this, arguments );
};

var proto = Item.prototype = Object.create( Outlayer.Item.prototype );

var __create = proto._create;
proto._create = function() {
  // call default _create logic
  __create.call( this );
  this.rect = new Rect();
};

var _moveTo = proto.moveTo;
proto.moveTo = function( x, y ) {
  // don't shift 1px while dragging
  var dx = Math.abs( this.position.x - x );
  var dy = Math.abs( this.position.y - y );

  var canHackGoTo = this.layout.dragItemCount && !this.isPlacing &&
    !this.isTransitioning && dx < 1 && dy < 1;
  if ( canHackGoTo ) {
    this.goTo( x, y );
    return;
  }
  _moveTo.apply( this, arguments );
};

// -------------------------- placing -------------------------- //

proto.enablePlacing = function() {
  this.removeTransitionStyles();
  // remove transform property from transition
  if ( this.isTransitioning && transformProperty ) {
    this.element.style[ transformProperty ] = 'none';
  }
  this.isTransitioning = false;
  this.getSize();
  this.layout._setRectSize( this.element, this.rect );
  this.isPlacing = true;
};

proto.disablePlacing = function() {
  this.isPlacing = false;
};

// -----  ----- //

// remove element from DOM
proto.removeElem = function() {
  this.element.parentNode.removeChild( this.element );
  // add space back to packer
  this.layout.packer.addSpace( this.rect );
  this.emitEvent( 'remove', [ this ] );
};

// ----- dropPlaceholder ----- //

proto.showDropPlaceholder = function() {
  var dropPlaceholder = this.dropPlaceholder;
  if ( !dropPlaceholder ) {
    // create dropPlaceholder
    dropPlaceholder = this.dropPlaceholder = document.createElement('div');
    dropPlaceholder.className = 'packery-drop-placeholder';
    dropPlaceholder.style.position = 'absolute';
  }

  dropPlaceholder.style.width = this.size.width + 'px';
  dropPlaceholder.style.height = this.size.height + 'px';
  this.positionDropPlaceholder();
  this.layout.element.appendChild( dropPlaceholder );
};

proto.positionDropPlaceholder = function() {
  this.dropPlaceholder.style[ transformProperty ] = 'translate(' +
    this.rect.x + 'px, ' + this.rect.y + 'px)';
};

proto.hideDropPlaceholder = function() {
  this.layout.element.removeChild( this.dropPlaceholder );
};

// -----  ----- //

return Item;

}));

/*!
 * Packery v2.0.0
 * Gapless, draggable grid layouts
 *
 * Licensed GPLv3 for open source use
 * or Packery Commercial License for commercial use
 *
 * http://packery.metafizzy.co
 * Copyright 2016 Metafizzy
 */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'packery/js/packery',[
        'get-size/get-size',
        'outlayer/outlayer',
        './rect',
        './packer',
        './item'
      ],
      factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('get-size'),
      require('outlayer'),
      require('./rect'),
      require('./packer'),
      require('./item')
    );
  } else {
    // browser global
    window.Packery = factory(
      window.getSize,
      window.Outlayer,
      window.Packery.Rect,
      window.Packery.Packer,
      window.Packery.Item
    );
  }

}( window, function factory( getSize, Outlayer, Rect, Packer, Item ) {


// ----- Rect ----- //

// allow for pixel rounding errors IE8-IE11 & Firefox; #227
Rect.prototype.canFit = function( rect ) {
  return this.width >= rect.width - 1 && this.height >= rect.height - 1;
};

// -------------------------- Packery -------------------------- //

// create an Outlayer layout class
var Packery = Outlayer.create('packery');
Packery.Item = Item;

var proto = Packery.prototype;

proto._create = function() {
  // call super
  Outlayer.prototype._create.call( this );

  // initial properties
  this.packer = new Packer();
  // packer for drop targets
  this.shiftPacker = new Packer();
  this.isEnabled = true;

  this.dragItemCount = 0;

  // create drag handlers
  var _this = this;
  this.handleDraggabilly = {
    dragStart: function() {
      _this.itemDragStart( this.element );
    },
    dragMove: function() {
      _this.itemDragMove( this.element, this.position.x, this.position.y );
    },
    dragEnd: function() {
      _this.itemDragEnd( this.element );
    }
  };

  this.handleUIDraggable = {
    start: function handleUIDraggableStart( event, ui ) {
      // HTML5 may trigger dragstart, dismiss HTML5 dragging
      if ( !ui ) {
        return;
      }
      _this.itemDragStart( event.currentTarget );
    },
    drag: function handleUIDraggableDrag( event, ui ) {
      if ( !ui ) {
        return;
      }
      _this.itemDragMove( event.currentTarget, ui.position.left, ui.position.top );
    },
    stop: function handleUIDraggableStop( event, ui ) {
      if ( !ui ) {
        return;
      }
      _this.itemDragEnd( event.currentTarget );
    }
  };

};


// ----- init & layout ----- //

/**
 * logic before any new layout
 */
proto._resetLayout = function() {
  this.getSize();

  this._getMeasurements();

  // reset packer
  var width, height, sortDirection;
  // packer settings, if horizontal or vertical
  if ( this._getOption('horizontal') ) {
    width = Infinity;
    height = this.size.innerHeight + this.gutter;
    sortDirection = 'rightwardTopToBottom';
  } else {
    width = this.size.innerWidth + this.gutter;
    height = Infinity;
    sortDirection = 'downwardLeftToRight';
  }

  this.packer.width = this.shiftPacker.width = width;
  this.packer.height = this.shiftPacker.height = height;
  this.packer.sortDirection = this.shiftPacker.sortDirection = sortDirection;

  this.packer.reset();

  // layout
  this.maxY = 0;
  this.maxX = 0;
};

/**
 * update columnWidth, rowHeight, & gutter
 * @private
 */
proto._getMeasurements = function() {
  this._getMeasurement( 'columnWidth', 'width' );
  this._getMeasurement( 'rowHeight', 'height' );
  this._getMeasurement( 'gutter', 'width' );
};

proto._getItemLayoutPosition = function( item ) {
  this._setRectSize( item.element, item.rect );
  if ( this.isShifting || this.dragItemCount > 0 ) {
    var packMethod = this._getPackMethod();
    this.packer[ packMethod ]( item.rect );
  } else {
    this.packer.pack( item.rect );
  }

  this._setMaxXY( item.rect );
  return item.rect;
};

proto.shiftLayout = function() {
  this.isShifting = true;
  this.layout();
  delete this.isShifting;
};

proto._getPackMethod = function() {
  return this._getOption('horizontal') ? 'rowPack' : 'columnPack';
};


/**
 * set max X and Y value, for size of container
 * @param {Packery.Rect} rect
 * @private
 */
proto._setMaxXY = function( rect ) {
  this.maxX = Math.max( rect.x + rect.width, this.maxX );
  this.maxY = Math.max( rect.y + rect.height, this.maxY );
};

/**
 * set the width and height of a rect, applying columnWidth and rowHeight
 * @param {Element} elem
 * @param {Packery.Rect} rect
 */
proto._setRectSize = function( elem, rect ) {
  var size = getSize( elem );
  var w = size.outerWidth;
  var h = size.outerHeight;
  // size for columnWidth and rowHeight, if available
  // only check if size is non-zero, #177
  if ( w || h ) {
    w = this._applyGridGutter( w, this.columnWidth );
    h = this._applyGridGutter( h, this.rowHeight );
  }
  // rect must fit in packer
  rect.width = Math.min( w, this.packer.width );
  rect.height = Math.min( h, this.packer.height );
};

/**
 * fits item to columnWidth/rowHeight and adds gutter
 * @param {Number} measurement - item width or height
 * @param {Number} gridSize - columnWidth or rowHeight
 * @returns measurement
 */
proto._applyGridGutter = function( measurement, gridSize ) {
  // just add gutter if no gridSize
  if ( !gridSize ) {
    return measurement + this.gutter;
  }
  gridSize += this.gutter;
  // fit item to columnWidth/rowHeight
  var remainder = measurement % gridSize;
  var mathMethod = remainder && remainder < 1 ? 'round' : 'ceil';
  measurement = Math[ mathMethod ]( measurement / gridSize ) * gridSize;
  return measurement;
};

proto._getContainerSize = function() {
  if ( this._getOption('horizontal') ) {
    return {
      width: this.maxX - this.gutter
    };
  } else {
    return {
      height: this.maxY - this.gutter
    };
  }
};


// -------------------------- stamp -------------------------- //

/**
 * makes space for element
 * @param {Element} elem
 */
proto._manageStamp = function( elem ) {

  var item = this.getItem( elem );
  var rect;
  if ( item && item.isPlacing ) {
    rect = item.rect;
  } else {
    var offset = this._getElementOffset( elem );
    rect = new Rect({
      x: this._getOption('originLeft') ? offset.left : offset.right,
      y: this._getOption('originTop') ? offset.top : offset.bottom
    });
  }

  this._setRectSize( elem, rect );
  // save its space in the packer
  this.packer.placed( rect );
  this._setMaxXY( rect );
};

// -------------------------- methods -------------------------- //

function verticalSorter( a, b ) {
  return a.position.y - b.position.y || a.position.x - b.position.x;
}

function horizontalSorter( a, b ) {
  return a.position.x - b.position.x || a.position.y - b.position.y;
}

proto.sortItemsByPosition = function() {
  var sorter = this._getOption('horizontal') ? horizontalSorter : verticalSorter;
  this.items.sort( sorter );
};

/**
 * Fit item element in its current position
 * Packery will position elements around it
 * useful for expanding elements
 *
 * @param {Element} elem
 * @param {Number} x - horizontal destination position, optional
 * @param {Number} y - vertical destination position, optional
 */
proto.fit = function( elem, x, y ) {
  var item = this.getItem( elem );
  if ( !item ) {
    return;
  }

  // stamp item to get it out of layout
  this.stamp( item.element );
  // set placing flag
  item.enablePlacing();
  this.updateShiftTargets( item );
  // fall back to current position for fitting
  x = x === undefined ? item.rect.x: x;
  y = y === undefined ? item.rect.y: y;
  // position it best at its destination
  this.shift( item, x, y );
  this._bindFitEvents( item );
  item.moveTo( item.rect.x, item.rect.y );
  // layout everything else
  this.shiftLayout();
  // return back to regularly scheduled programming
  this.unstamp( item.element );
  this.sortItemsByPosition();
  item.disablePlacing();
};

/**
 * emit event when item is fit and other items are laid out
 * @param {Packery.Item} item
 * @private
 */
proto._bindFitEvents = function( item ) {
  var _this = this;
  var ticks = 0;
  function onLayout() {
    ticks++;
    if ( ticks != 2 ) {
      return;
    }
    _this.dispatchEvent( 'fitComplete', null, [ item ] );
  }
  // when item is laid out
  item.once( 'layout', onLayout );
  // when all items are laid out
  this.once( 'layoutComplete', onLayout );
};

// -------------------------- resize -------------------------- //

// debounced, layout on resize
proto.resize = function() {
  // don't trigger if size did not change
  // or if resize was unbound. See #285, outlayer#9
  if ( !this.isResizeBound || !this.needsResizeLayout() ) {
    return;
  }

  if ( this.options.shiftPercentResize ) {
    this.resizeShiftPercentLayout();
  } else {
    this.layout();
  }
};

/**
 * check if layout is needed post layout
 * @returns Boolean
 */
proto.needsResizeLayout = function() {
  var size = getSize( this.element );
  var innerSize = this._getOption('horizontal') ? 'innerHeight' : 'innerWidth';
  return size[ innerSize ] != this.size[ innerSize ];
};

proto.resizeShiftPercentLayout = function() {
  var items = this._getItemsForLayout( this.items );

  var isHorizontal = this._getOption('horizontal');
  var coord = isHorizontal ? 'y' : 'x';
  var measure = isHorizontal ? 'height' : 'width';
  var segmentName = isHorizontal ? 'rowHeight' : 'columnWidth';
  var innerSize = isHorizontal ? 'innerHeight' : 'innerWidth';

  // proportional re-align items
  var previousSegment = this[ segmentName ];
  previousSegment = previousSegment && previousSegment + this.gutter;

  if ( previousSegment ) {
    this._getMeasurements();
    var currentSegment = this[ segmentName ] + this.gutter;
    items.forEach( function( item ) {
      var seg = Math.round( item.rect[ coord ] / previousSegment );
      item.rect[ coord ] = seg * currentSegment;
    });
  } else {
    var currentSize = getSize( this.element )[ innerSize ] + this.gutter;
    var previousSize = this.packer[ measure ];
    items.forEach( function( item ) {
      item.rect[ coord ] = ( item.rect[ coord ] / previousSize ) * currentSize;
    });
  }

  this.shiftLayout();
};

// -------------------------- drag -------------------------- //

/**
 * handle an item drag start event
 * @param {Element} elem
 */
proto.itemDragStart = function( elem ) {
  if ( !this.isEnabled ) {
    return;
  }
  this.stamp( elem );
  // this.ignore( elem );
  var item = this.getItem( elem );
  if ( !item ) {
    return;
  }

  item.enablePlacing();
  item.showDropPlaceholder();
  this.dragItemCount++;
  this.updateShiftTargets( item );
};

proto.updateShiftTargets = function( dropItem ) {
  this.shiftPacker.reset();

  // pack stamps
  this._getBoundingRect();
  var isOriginLeft = this._getOption('originLeft');
  var isOriginTop = this._getOption('originTop');
  this.stamps.forEach( function( stamp ) {
    // ignore dragged item
    var item = this.getItem( stamp );
    if ( item && item.isPlacing ) {
      return;
    }
    var offset = this._getElementOffset( stamp );
    var rect = new Rect({
      x: isOriginLeft ? offset.left : offset.right,
      y: isOriginTop ? offset.top : offset.bottom
    });
    this._setRectSize( stamp, rect );
    // save its space in the packer
    this.shiftPacker.placed( rect );
  }, this );

  // reset shiftTargets
  var isHorizontal = this._getOption('horizontal');
  var segmentName = isHorizontal ? 'rowHeight' : 'columnWidth';
  var measure = isHorizontal ? 'height' : 'width';

  this.shiftTargetKeys = [];
  this.shiftTargets = [];
  var boundsSize;
  var segment = this[ segmentName ];
  segment = segment && segment + this.gutter;

  if ( segment ) {
    var segmentSpan = Math.ceil( dropItem.rect[ measure ] / segment );
    var segs = Math.floor( ( this.shiftPacker[ measure ] + this.gutter ) / segment );
    boundsSize = ( segs - segmentSpan ) * segment;
    // add targets on top
    for ( var i=0; i < segs; i++ ) {
      this._addShiftTarget( i * segment, 0, boundsSize );
    }
  } else {
    boundsSize = ( this.shiftPacker[ measure ] + this.gutter ) - dropItem.rect[ measure ];
    this._addShiftTarget( 0, 0, boundsSize );
  }

  // pack each item to measure where shiftTargets are
  var items = this._getItemsForLayout( this.items );
  var packMethod = this._getPackMethod();
  items.forEach( function( item ) {
    var rect = item.rect;
    this._setRectSize( item.element, rect );
    this.shiftPacker[ packMethod ]( rect );

    // add top left corner
    this._addShiftTarget( rect.x, rect.y, boundsSize );
    // add bottom left / top right corner
    var cornerX = isHorizontal ? rect.x + rect.width : rect.x;
    var cornerY = isHorizontal ? rect.y : rect.y + rect.height;
    this._addShiftTarget( cornerX, cornerY, boundsSize );

    if ( segment ) {
      // add targets for each column on bottom / row on right
      var segSpan = Math.round( rect[ measure ] / segment );
      for ( var i=1; i < segSpan; i++ ) {
        var segX = isHorizontal ? cornerX : rect.x + segment * i;
        var segY = isHorizontal ? rect.y + segment * i : cornerY;
        this._addShiftTarget( segX, segY, boundsSize );
      }
    }
  }, this );

};

proto._addShiftTarget = function( x, y, boundsSize ) {
  var checkCoord = this._getOption('horizontal') ? y : x;
  if ( checkCoord !== 0 && checkCoord > boundsSize ) {
    return;
  }
  // create string for a key, easier to keep track of what targets
  var key = x + ',' + y;
  var hasKey = this.shiftTargetKeys.indexOf( key ) != -1;
  if ( hasKey ) {
    return;
  }
  this.shiftTargetKeys.push( key );
  this.shiftTargets.push({ x: x, y: y });
};

// -------------------------- drop -------------------------- //

proto.shift = function( item, x, y ) {
  var shiftPosition;
  var minDistance = Infinity;
  var position = { x: x, y: y };
  this.shiftTargets.forEach( function( target ) {
    var distance = getDistance( target, position );
    if ( distance < minDistance ) {
      shiftPosition = target;
      minDistance = distance;
    }
  });
  item.rect.x = shiftPosition.x;
  item.rect.y = shiftPosition.y;
};

function getDistance( a, b ) {
  var dx = b.x - a.x;
  var dy = b.y - a.y;
  return Math.sqrt( dx * dx + dy * dy );
}

// -------------------------- drag move -------------------------- //

var DRAG_THROTTLE_TIME = 120;

/**
 * handle an item drag move event
 * @param {Element} elem
 * @param {Number} x - horizontal change in position
 * @param {Number} y - vertical change in position
 */
proto.itemDragMove = function( elem, x, y ) {
  var item = this.isEnabled && this.getItem( elem );
  if ( !item ) {
    return;
  }

  x -= this.size.paddingLeft;
  y -= this.size.paddingTop;

  var _this = this;
  function onDrag() {
    _this.shift( item, x, y );
    item.positionDropPlaceholder();
    _this.layout();
  }

  // throttle
  var now = new Date();
  if ( this._itemDragTime && now - this._itemDragTime < DRAG_THROTTLE_TIME ) {
    clearTimeout( this.dragTimeout );
    this.dragTimeout = setTimeout( onDrag, DRAG_THROTTLE_TIME );
  } else {
    onDrag();
    this._itemDragTime = now;
  }
};

// -------------------------- drag end -------------------------- //

/**
 * handle an item drag end event
 * @param {Element} elem
 */
proto.itemDragEnd = function( elem ) {
  var item = this.isEnabled && this.getItem( elem );
  if ( !item ) {
    return;
  }

  clearTimeout( this.dragTimeout );
  item.element.classList.add('is-positioning-post-drag');

  var completeCount = 0;
  var _this = this;
  function onDragEndLayoutComplete() {
    completeCount++;
    if ( completeCount != 2 ) {
      return;
    }
    // reset drag item
    item.element.classList.remove('is-positioning-post-drag');
    item.hideDropPlaceholder();
    _this.dispatchEvent( 'dragItemPositioned', null, [ item ] );
  }

  item.once( 'layout', onDragEndLayoutComplete );
  this.once( 'layoutComplete', onDragEndLayoutComplete );
  item.moveTo( item.rect.x, item.rect.y );
  this.layout();
  this.dragItemCount = Math.max( 0, this.dragItemCount - 1 );
  this.sortItemsByPosition();
  item.disablePlacing();
  this.unstamp( item.element );
};

/**
 * binds Draggabilly events
 * @param {Draggabilly} draggie
 */
proto.bindDraggabillyEvents = function( draggie ) {
  this._bindDraggabillyEvents( draggie, 'on' );
};

proto.unbindDraggabillyEvents = function( draggie ) {
  this._bindDraggabillyEvents( draggie, 'off' );
};

proto._bindDraggabillyEvents = function( draggie, method ) {
  var handlers = this.handleDraggabilly;
  draggie[ method ]( 'dragStart', handlers.dragStart );
  draggie[ method ]( 'dragMove', handlers.dragMove );
  draggie[ method ]( 'dragEnd', handlers.dragEnd );
};

/**
 * binds jQuery UI Draggable events
 * @param {jQuery} $elems
 */
proto.bindUIDraggableEvents = function( $elems ) {
  this._bindUIDraggableEvents( $elems, 'on' );
};

proto.unbindUIDraggableEvents = function( $elems ) {
  this._bindUIDraggableEvents( $elems, 'off' );
};

proto._bindUIDraggableEvents = function( $elems, method ) {
  var handlers = this.handleUIDraggable;
  $elems
    [ method ]( 'dragstart', handlers.start )
    [ method ]( 'drag', handlers.drag )
    [ method ]( 'dragstop', handlers.stop );
};

// ----- destroy ----- //

var _destroy = proto.destroy;
proto.destroy = function() {
  _destroy.apply( this, arguments );
  // disable flag; prevent drag events from triggering. #72
  this.isEnabled = false;
};

// -----  ----- //

Packery.Rect = Rect;
Packery.Packer = Packer;

return Packery;

}));

/*!
 * Packery layout mode v2.0.0
 * sub-classes Packery
 */

/*jshint browser: true, strict: true, undef: true, unused: true */

( function( window, factory ) {
  
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( [
        'isotope/js/layout-mode',
        'packery/js/packery'
      ],
      factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('isotope-layout/js/layout-mode'),
      require('packery')
    );
  } else {
    // browser global
    factory(
      window.Isotope.LayoutMode,
      window.Packery
    );
  }

}( window, function factor( LayoutMode, Packery ) {


  // create an Outlayer layout class
  var PackeryMode = LayoutMode.create('packery');
  var proto = PackeryMode.prototype;

  var keepModeMethods = {
    _getElementOffset: true,
    _getMeasurement: true
  };

  // inherit Packery prototype
  for ( var method in Packery.prototype ) {
    // do not inherit mode methods
    if ( !keepModeMethods[ method ] ) {
      proto[ method ] = Packery.prototype[ method ];
    }
  }

  // set packer in _resetLayout
  var _resetLayout = proto._resetLayout;
  proto._resetLayout = function() {
    this.packer = this.packer || new Packery.Packer();
    this.shiftPacker = this.shiftPacker || new Packery.Packer();
    _resetLayout.apply( this, arguments );
  };

  var _getItemLayoutPosition = proto._getItemLayoutPosition;
  proto._getItemLayoutPosition = function( item ) {
    // set packery rect
    item.rect = item.rect || new Packery.Rect();
    return _getItemLayoutPosition.call( this, item );
  };

  // needsResizeLayout for vertical or horizontal
  var _needsResizeLayout = proto.needsResizeLayout;
  proto.needsResizeLayout = function() {
    if ( this._getOption('horizontal') ) {
      return this.needsVerticalResizeLayout();
    } else {
      return _needsResizeLayout.call( this );
    }
  };

  // point to mode options for horizontal
  var _getOption = proto._getOption;
  proto._getOption = function( option ) {
    if ( option == 'horizontal' ) {
      return this.options.isHorizontal !== undefined ?
        this.options.isHorizontal : this.options.horizontal;
    }
    return _getOption.apply( this.isotope, arguments );
  };

  return PackeryMode;

}));


/*! 
 * 
 * ================== js/libs/plugins/photoswipe.js =================== 
 **/ 

/*! PhotoSwipe - v4.1.1 - 2015-12-24
* http://photoswipe.com
* Copyright (c) 2015 Dmitry Semenov; */
(function (root, factory) { 
	if (typeof define === 'function' && define.amd) {
		define(factory);
	} else if (typeof exports === 'object') {
		module.exports = factory();
	} else {
		root.PhotoSwipe = factory();
	}
})(this, function () {

	'use strict';
	var PhotoSwipe = function(template, UiClass, items, options){

/*>>framework-bridge*/
/**
 *
 * Set of generic functions used by gallery.
 * 
 * You're free to modify anything here as long as functionality is kept.
 * 
 */
var framework = {
	features: null,
	bind: function(target, type, listener, unbind) {
		var methodName = (unbind ? 'remove' : 'add') + 'EventListener';
		type = type.split(' ');
		for(var i = 0; i < type.length; i++) {
			if(type[i]) {
				target[methodName]( type[i], listener, false);
			}
		}
	},
	isArray: function(obj) {
		return (obj instanceof Array);
	},
	createEl: function(classes, tag) {
		var el = document.createElement(tag || 'div');
		if(classes) {
			el.className = classes;
		}
		return el;
	},
	getScrollY: function() {
		var yOffset = window.pageYOffset;
		return yOffset !== undefined ? yOffset : document.documentElement.scrollTop;
	},
	unbind: function(target, type, listener) {
		framework.bind(target,type,listener,true);
	},
	removeClass: function(el, className) {
		var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
		el.className = el.className.replace(reg, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 
	},
	addClass: function(el, className) {
		if( !framework.hasClass(el,className) ) {
			el.className += (el.className ? ' ' : '') + className;
		}
	},
	hasClass: function(el, className) {
		return el.className && new RegExp('(^|\\s)' + className + '(\\s|$)').test(el.className);
	},
	getChildByClass: function(parentEl, childClassName) {
		var node = parentEl.firstChild;
		while(node) {
			if( framework.hasClass(node, childClassName) ) {
				return node;
			}
			node = node.nextSibling;
		}
	},
	arraySearch: function(array, value, key) {
		var i = array.length;
		while(i--) {
			if(array[i][key] === value) {
				return i;
			} 
		}
		return -1;
	},
	extend: function(o1, o2, preventOverwrite) {
		for (var prop in o2) {
			if (o2.hasOwnProperty(prop)) {
				if(preventOverwrite && o1.hasOwnProperty(prop)) {
					continue;
				}
				o1[prop] = o2[prop];
			}
		}
	},
	easing: {
		sine: {
			out: function(k) {
				return Math.sin(k * (Math.PI / 2));
			},
			inOut: function(k) {
				return - (Math.cos(Math.PI * k) - 1) / 2;
			}
		},
		cubic: {
			out: function(k) {
				return --k * k * k + 1;
			}
		}
		/*
			elastic: {
				out: function ( k ) {

					var s, a = 0.1, p = 0.4;
					if ( k === 0 ) return 0;
					if ( k === 1 ) return 1;
					if ( !a || a < 1 ) { a = 1; s = p / 4; }
					else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
					return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );

				},
			},
			back: {
				out: function ( k ) {
					var s = 1.70158;
					return --k * k * ( ( s + 1 ) * k + s ) + 1;
				}
			}
		*/
	},

	/**
	 * 
	 * @return {object}
	 * 
	 * {
	 *  raf : request animation frame function
	 *  caf : cancel animation frame function
	 *  transfrom : transform property key (with vendor), or null if not supported
	 *  oldIE : IE8 or below
	 * }
	 * 
	 */
	detectFeatures: function() {
		if(framework.features) {
			return framework.features;
		}
		var helperEl = framework.createEl(),
			helperStyle = helperEl.style,
			vendor = '',
			features = {};

		// IE8 and below
		features.oldIE = document.all && !document.addEventListener;

		features.touch = 'ontouchstart' in window;

		if(window.requestAnimationFrame) {
			features.raf = window.requestAnimationFrame;
			features.caf = window.cancelAnimationFrame;
		}

		features.pointerEvent = navigator.pointerEnabled || navigator.msPointerEnabled;

		// fix false-positive detection of old Android in new IE
		// (IE11 ua string contains "Android 4.0")
		
		if(!features.pointerEvent) { 

			var ua = navigator.userAgent;

			// Detect if device is iPhone or iPod and if it's older than iOS 8
			// http://stackoverflow.com/a/14223920
			// 
			// This detection is made because of buggy top/bottom toolbars
			// that don't trigger window.resize event.
			// For more info refer to _isFixedPosition variable in core.js

			if (/iP(hone|od)/.test(navigator.platform)) {
				var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
				if(v && v.length > 0) {
					v = parseInt(v[1], 10);
					if(v >= 1 && v < 8 ) {
						features.isOldIOSPhone = true;
					}
				}
			}

			// Detect old Android (before KitKat)
			// due to bugs related to position:fixed
			// http://stackoverflow.com/questions/7184573/pick-up-the-android-version-in-the-browser-by-javascript
			
			var match = ua.match(/Android\s([0-9\.]*)/);
			var androidversion =  match ? match[1] : 0;
			androidversion = parseFloat(androidversion);
			if(androidversion >= 1 ) {
				if(androidversion < 4.4) {
					features.isOldAndroid = true; // for fixed position bug & performance
				}
				features.androidVersion = androidversion; // for touchend bug
			}	
			features.isMobileOpera = /opera mini|opera mobi/i.test(ua);

			// p.s. yes, yes, UA sniffing is bad, propose your solution for above bugs.
		}
		
		var styleChecks = ['transform', 'perspective', 'animationName'],
			vendors = ['', 'webkit','Moz','ms','O'],
			styleCheckItem,
			styleName;

		for(var i = 0; i < 4; i++) {
			vendor = vendors[i];

			for(var a = 0; a < 3; a++) {
				styleCheckItem = styleChecks[a];

				// uppercase first letter of property name, if vendor is present
				styleName = vendor + (vendor ? 
										styleCheckItem.charAt(0).toUpperCase() + styleCheckItem.slice(1) : 
										styleCheckItem);
			
				if(!features[styleCheckItem] && styleName in helperStyle ) {
					features[styleCheckItem] = styleName;
				}
			}

			if(vendor && !features.raf) {
				vendor = vendor.toLowerCase();
				features.raf = window[vendor+'RequestAnimationFrame'];
				if(features.raf) {
					features.caf = window[vendor+'CancelAnimationFrame'] || 
									window[vendor+'CancelRequestAnimationFrame'];
				}
			}
		}
			
		if(!features.raf) {
			var lastTime = 0;
			features.raf = function(fn) {
				var currTime = new Date().getTime();
				var timeToCall = Math.max(0, 16 - (currTime - lastTime));
				var id = window.setTimeout(function() { fn(currTime + timeToCall); }, timeToCall);
				lastTime = currTime + timeToCall;
				return id;
			};
			features.caf = function(id) { clearTimeout(id); };
		}

		// Detect SVG support
		features.svg = !!document.createElementNS && 
						!!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;

		framework.features = features;

		return features;
	}
};

framework.detectFeatures();

// Override addEventListener for old versions of IE
if(framework.features.oldIE) {

	framework.bind = function(target, type, listener, unbind) {
		
		type = type.split(' ');

		var methodName = (unbind ? 'detach' : 'attach') + 'Event',
			evName,
			_handleEv = function() {
				listener.handleEvent.call(listener);
			};

		for(var i = 0; i < type.length; i++) {
			evName = type[i];
			if(evName) {

				if(typeof listener === 'object' && listener.handleEvent) {
					if(!unbind) {
						listener['oldIE' + evName] = _handleEv;
					} else {
						if(!listener['oldIE' + evName]) {
							return false;
						}
					}

					target[methodName]( 'on' + evName, listener['oldIE' + evName]);
				} else {
					target[methodName]( 'on' + evName, listener);
				}

			}
		}
	};
	
}

/*>>framework-bridge*/

/*>>core*/
//function(template, UiClass, items, options)

var self = this;

/**
 * Static vars, don't change unless you know what you're doing.
 */
var DOUBLE_TAP_RADIUS = 25, 
	NUM_HOLDERS = 3;

/**
 * Options
 */
var _options = {
	allowPanToNext:true,
	spacing: 0.12,
	bgOpacity: 1,
	mouseUsed: false,
	loop: true,
	pinchToClose: true,
	closeOnScroll: true,
	closeOnVerticalDrag: true,
	verticalDragRange: 0.75,
	hideAnimationDuration: 333,
	showAnimationDuration: 333,
	showHideOpacity: false,
	focus: true,
	escKey: true,
	arrowKeys: true,
	mainScrollEndFriction: 0.35,
	panEndFriction: 0.35,
	isClickableElement: function(el) {
        return el.tagName === 'A';
    },
    getDoubleTapZoom: function(isMouseClick, item) {
    	if(isMouseClick) {
    		return 1;
    	} else {
    		return item.initialZoomLevel < 0.7 ? 1 : 1.33;
    	}
    },
    maxSpreadZoom: 1.33,
	modal: true,

	// not fully implemented yet
	scaleMode: 'fit' // TODO
};
framework.extend(_options, options);


/**
 * Private helper variables & functions
 */

var _getEmptyPoint = function() { 
		return {x:0,y:0}; 
	};

var _isOpen,
	_isDestroying,
	_closedByScroll,
	_currentItemIndex,
	_containerStyle,
	_containerShiftIndex,
	_currPanDist = _getEmptyPoint(),
	_startPanOffset = _getEmptyPoint(),
	_panOffset = _getEmptyPoint(),
	_upMoveEvents, // drag move, drag end & drag cancel events array
	_downEvents, // drag start events array
	_globalEventHandlers,
	_viewportSize = {},
	_currZoomLevel,
	_startZoomLevel,
	_translatePrefix,
	_translateSufix,
	_updateSizeInterval,
	_itemsNeedUpdate,
	_currPositionIndex = 0,
	_offset = {},
	_slideSize = _getEmptyPoint(), // size of slide area, including spacing
	_itemHolders,
	_prevItemIndex,
	_indexDiff = 0, // difference of indexes since last content update
	_dragStartEvent,
	_dragMoveEvent,
	_dragEndEvent,
	_dragCancelEvent,
	_transformKey,
	_pointerEventEnabled,
	_isFixedPosition = true,
	_likelyTouchDevice,
	_modules = [],
	_requestAF,
	_cancelAF,
	_initalClassName,
	_initalWindowScrollY,
	_oldIE,
	_currentWindowScrollY,
	_features,
	_windowVisibleSize = {},
	_renderMaxResolution = false,

	// Registers PhotoSWipe module (History, Controller ...)
	_registerModule = function(name, module) {
		framework.extend(self, module.publicMethods);
		_modules.push(name);
	},

	_getLoopedId = function(index) {
		var numSlides = _getNumItems();
		if(index > numSlides - 1) {
			return index - numSlides;
		} else  if(index < 0) {
			return numSlides + index;
		}
		return index;
	},
	
	// Micro bind/trigger
	_listeners = {},
	_listen = function(name, fn) {
		if(!_listeners[name]) {
			_listeners[name] = [];
		}
		return _listeners[name].push(fn);
	},
	_shout = function(name) {
		var listeners = _listeners[name];

		if(listeners) {
			var args = Array.prototype.slice.call(arguments);
			args.shift();

			for(var i = 0; i < listeners.length; i++) {
				listeners[i].apply(self, args);
			}
		}
	},

	_getCurrentTime = function() {
		return new Date().getTime();
	},
	_applyBgOpacity = function(opacity) {
		_bgOpacity = opacity;
		self.bg.style.opacity = opacity * _options.bgOpacity;
	},

	_applyZoomTransform = function(styleObj,x,y,zoom,item) {
		if(!_renderMaxResolution || (item && item !== self.currItem) ) {
			zoom = zoom / (item ? item.fitRatio : self.currItem.fitRatio);	
		}
			
		styleObj[_transformKey] = _translatePrefix + x + 'px, ' + y + 'px' + _translateSufix + ' scale(' + zoom + ')';
	},
	_applyCurrentZoomPan = function( allowRenderResolution ) {
		if(_currZoomElementStyle) {

			if(allowRenderResolution) {
				if(_currZoomLevel > self.currItem.fitRatio) {
					if(!_renderMaxResolution) {
						_setImageSize(self.currItem, false, true);
						_renderMaxResolution = true;
					}
				} else {
					if(_renderMaxResolution) {
						_setImageSize(self.currItem);
						_renderMaxResolution = false;
					}
				}
			}
			

			_applyZoomTransform(_currZoomElementStyle, _panOffset.x, _panOffset.y, _currZoomLevel);
		}
	},
	_applyZoomPanToItem = function(item) {
		if(item.container) {

			_applyZoomTransform(item.container.style, 
								item.initialPosition.x, 
								item.initialPosition.y, 
								item.initialZoomLevel,
								item);
		}
	},
	_setTranslateX = function(x, elStyle) {
		elStyle[_transformKey] = _translatePrefix + x + 'px, 0px' + _translateSufix;
	},
	_moveMainScroll = function(x, dragging) {

		if(!_options.loop && dragging) {
			var newSlideIndexOffset = _currentItemIndex + (_slideSize.x * _currPositionIndex - x) / _slideSize.x,
				delta = Math.round(x - _mainScrollPos.x);

			if( (newSlideIndexOffset < 0 && delta > 0) || 
				(newSlideIndexOffset >= _getNumItems() - 1 && delta < 0) ) {
				x = _mainScrollPos.x + delta * _options.mainScrollEndFriction;
			} 
		}
		
		_mainScrollPos.x = x;
		_setTranslateX(x, _containerStyle);
	},
	_calculatePanOffset = function(axis, zoomLevel) {
		var m = _midZoomPoint[axis] - _offset[axis];
		return _startPanOffset[axis] + _currPanDist[axis] + m - m * ( zoomLevel / _startZoomLevel );
	},
	
	_equalizePoints = function(p1, p2) {
		p1.x = p2.x;
		p1.y = p2.y;
		if(p2.id) {
			p1.id = p2.id;
		}
	},
	_roundPoint = function(p) {
		p.x = Math.round(p.x);
		p.y = Math.round(p.y);
	},

	_mouseMoveTimeout = null,
	_onFirstMouseMove = function() {
		// Wait until mouse move event is fired at least twice during 100ms
		// We do this, because some mobile browsers trigger it on touchstart
		if(_mouseMoveTimeout ) { 
			framework.unbind(document, 'mousemove', _onFirstMouseMove);
			framework.addClass(template, 'pswp--has_mouse');
			_options.mouseUsed = true;
			_shout('mouseUsed');
		}
		_mouseMoveTimeout = setTimeout(function() {
			_mouseMoveTimeout = null;
		}, 100);
	},

	_bindEvents = function() {
		framework.bind(document, 'keydown', self);

		if(_features.transform) {
			// don't bind click event in browsers that don't support transform (mostly IE8)
			framework.bind(self.scrollWrap, 'click', self);
		}
		

		if(!_options.mouseUsed) {
			framework.bind(document, 'mousemove', _onFirstMouseMove);
		}

		framework.bind(window, 'resize scroll', self);

		_shout('bindEvents');
	},

	_unbindEvents = function() {
		framework.unbind(window, 'resize', self);
		framework.unbind(window, 'scroll', _globalEventHandlers.scroll);
		framework.unbind(document, 'keydown', self);
		framework.unbind(document, 'mousemove', _onFirstMouseMove);

		if(_features.transform) {
			framework.unbind(self.scrollWrap, 'click', self);
		}

		if(_isDragging) {
			framework.unbind(window, _upMoveEvents, self);
		}

		_shout('unbindEvents');
	},
	
	_calculatePanBounds = function(zoomLevel, update) {
		var bounds = _calculateItemSize( self.currItem, _viewportSize, zoomLevel );
		if(update) {
			_currPanBounds = bounds;
		}
		return bounds;
	},
	
	_getMinZoomLevel = function(item) {
		if(!item) {
			item = self.currItem;
		}
		return item.initialZoomLevel;
	},
	_getMaxZoomLevel = function(item) {
		if(!item) {
			item = self.currItem;
		}
		return item.w > 0 ? _options.maxSpreadZoom : 1;
	},

	// Return true if offset is out of the bounds
	_modifyDestPanOffset = function(axis, destPanBounds, destPanOffset, destZoomLevel) {
		if(destZoomLevel === self.currItem.initialZoomLevel) {
			destPanOffset[axis] = self.currItem.initialPosition[axis];
			return true;
		} else {
			destPanOffset[axis] = _calculatePanOffset(axis, destZoomLevel); 

			if(destPanOffset[axis] > destPanBounds.min[axis]) {
				destPanOffset[axis] = destPanBounds.min[axis];
				return true;
			} else if(destPanOffset[axis] < destPanBounds.max[axis] ) {
				destPanOffset[axis] = destPanBounds.max[axis];
				return true;
			}
		}
		return false;
	},

	_setupTransforms = function() {

		if(_transformKey) {
			// setup 3d transforms
			var allow3dTransform = _features.perspective && !_likelyTouchDevice;
			_translatePrefix = 'translate' + (allow3dTransform ? '3d(' : '(');
			_translateSufix = _features.perspective ? ', 0px)' : ')';	
			return;
		}

		// Override zoom/pan/move functions in case old browser is used (most likely IE)
		// (so they use left/top/width/height, instead of CSS transform)
	
		_transformKey = 'left';
		framework.addClass(template, 'pswp--ie');

		_setTranslateX = function(x, elStyle) {
			elStyle.left = x + 'px';
		};
		_applyZoomPanToItem = function(item) {

			var zoomRatio = item.fitRatio > 1 ? 1 : item.fitRatio,
				s = item.container.style,
				w = zoomRatio * item.w,
				h = zoomRatio * item.h;

			s.width = w + 'px';
			s.height = h + 'px';
			s.left = item.initialPosition.x + 'px';
			s.top = item.initialPosition.y + 'px';

		};
		_applyCurrentZoomPan = function() {
			if(_currZoomElementStyle) {

				var s = _currZoomElementStyle,
					item = self.currItem,
					zoomRatio = item.fitRatio > 1 ? 1 : item.fitRatio,
					w = zoomRatio * item.w,
					h = zoomRatio * item.h;

				s.width = w + 'px';
				s.height = h + 'px';


				s.left = _panOffset.x + 'px';
				s.top = _panOffset.y + 'px';
			}
			
		};
	},

	_onKeyDown = function(e) {
		var keydownAction = '';
		if(_options.escKey && e.keyCode === 27) { 
			keydownAction = 'close';
		} else if(_options.arrowKeys) {
			if(e.keyCode === 37) {
				keydownAction = 'prev';
			} else if(e.keyCode === 39) { 
				keydownAction = 'next';
			}
		}

		if(keydownAction) {
			// don't do anything if special key pressed to prevent from overriding default browser actions
			// e.g. in Chrome on Mac cmd+arrow-left returns to previous page
			if( !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey ) {
				if(e.preventDefault) {
					e.preventDefault();
				} else {
					e.returnValue = false;
				} 
				self[keydownAction]();
			}
		}
	},

	_onGlobalClick = function(e) {
		if(!e) {
			return;
		}

		// don't allow click event to pass through when triggering after drag or some other gesture
		if(_moved || _zoomStarted || _mainScrollAnimating || _verticalDragInitiated) {
			e.preventDefault();
			e.stopPropagation();
		}
	},

	_updatePageScrollOffset = function() {
		self.setScrollOffset(0, framework.getScrollY());		
	};
	


	



// Micro animation engine
var _animations = {},
	_numAnimations = 0,
	_stopAnimation = function(name) {
		if(_animations[name]) {
			if(_animations[name].raf) {
				_cancelAF( _animations[name].raf );
			}
			_numAnimations--;
			delete _animations[name];
		}
	},
	_registerStartAnimation = function(name) {
		if(_animations[name]) {
			_stopAnimation(name);
		}
		if(!_animations[name]) {
			_numAnimations++;
			_animations[name] = {};
		}
	},
	_stopAllAnimations = function() {
		for (var prop in _animations) {

			if( _animations.hasOwnProperty( prop ) ) {
				_stopAnimation(prop);
			} 
			
		}
	},
	_animateProp = function(name, b, endProp, d, easingFn, onUpdate, onComplete) {
		var startAnimTime = _getCurrentTime(), t;
		_registerStartAnimation(name);

		var animloop = function(){
			if ( _animations[name] ) {
				
				t = _getCurrentTime() - startAnimTime; // time diff
				//b - beginning (start prop)
				//d - anim duration

				if ( t >= d ) {
					_stopAnimation(name);
					onUpdate(endProp);
					if(onComplete) {
						onComplete();
					}
					return;
				}
				onUpdate( (endProp - b) * easingFn(t/d) + b );

				_animations[name].raf = _requestAF(animloop);
			}
		};
		animloop();
	};
	


var publicMethods = {

	// make a few local variables and functions public
	shout: _shout,
	listen: _listen,
	viewportSize: _viewportSize,
	options: _options,

	isMainScrollAnimating: function() {
		return _mainScrollAnimating;
	},
	getZoomLevel: function() {
		return _currZoomLevel;
	},
	getCurrentIndex: function() {
		return _currentItemIndex;
	},
	isDragging: function() {
		return _isDragging;
	},	
	isZooming: function() {
		return _isZooming;
	},
	setScrollOffset: function(x,y) {
		_offset.x = x;
		_currentWindowScrollY = _offset.y = y;
		_shout('updateScrollOffset', _offset);
	},
	applyZoomPan: function(zoomLevel,panX,panY,allowRenderResolution) {
		_panOffset.x = panX;
		_panOffset.y = panY;
		_currZoomLevel = zoomLevel;
		_applyCurrentZoomPan( allowRenderResolution );
	},

	init: function() {

		if(_isOpen || _isDestroying) {
			return;
		}

		var i;

		self.framework = framework; // basic functionality
		self.template = template; // root DOM element of PhotoSwipe
		self.bg = framework.getChildByClass(template, 'pswp__bg');

		_initalClassName = template.className;
		_isOpen = true;
				
		_features = framework.detectFeatures();
		_requestAF = _features.raf;
		_cancelAF = _features.caf;
		_transformKey = _features.transform;
		_oldIE = _features.oldIE;
		
		self.scrollWrap = framework.getChildByClass(template, 'pswp__scroll-wrap');
		self.container = framework.getChildByClass(self.scrollWrap, 'pswp__container');

		_containerStyle = self.container.style; // for fast access

		// Objects that hold slides (there are only 3 in DOM)
		self.itemHolders = _itemHolders = [
			{el:self.container.children[0] , wrap:0, index: -1},
			{el:self.container.children[1] , wrap:0, index: -1},
			{el:self.container.children[2] , wrap:0, index: -1}
		];

		// hide nearby item holders until initial zoom animation finishes (to avoid extra Paints)
		_itemHolders[0].el.style.display = _itemHolders[2].el.style.display = 'none';

		_setupTransforms();

		// Setup global events
		_globalEventHandlers = {
			resize: self.updateSize,
			scroll: _updatePageScrollOffset,
			keydown: _onKeyDown,
			click: _onGlobalClick
		};

		// disable show/hide effects on old browsers that don't support CSS animations or transforms, 
		// old IOS, Android and Opera mobile. Blackberry seems to work fine, even older models.
		var oldPhone = _features.isOldIOSPhone || _features.isOldAndroid || _features.isMobileOpera;
		if(!_features.animationName || !_features.transform || oldPhone) {
			_options.showAnimationDuration = _options.hideAnimationDuration = 0;
		}

		// init modules
		for(i = 0; i < _modules.length; i++) {
			self['init' + _modules[i]]();
		}
		
		// init
		if(UiClass) {
			var ui = self.ui = new UiClass(self, framework);
			ui.init();
		}

		_shout('firstUpdate');
		_currentItemIndex = _currentItemIndex || _options.index || 0;
		// validate index
		if( isNaN(_currentItemIndex) || _currentItemIndex < 0 || _currentItemIndex >= _getNumItems() ) {
			_currentItemIndex = 0;
		}
		self.currItem = _getItemAt( _currentItemIndex );

		
		if(_features.isOldIOSPhone || _features.isOldAndroid) {
			_isFixedPosition = false;
		}
		
		template.setAttribute('aria-hidden', 'false');
		if(_options.modal) {
			if(!_isFixedPosition) {
				template.style.position = 'absolute';
				template.style.top = framework.getScrollY() + 'px';
			} else {
				template.style.position = 'fixed';
			}
		}

		if(_currentWindowScrollY === undefined) {
			_shout('initialLayout');
			_currentWindowScrollY = _initalWindowScrollY = framework.getScrollY();
		}
		
		// add classes to root element of PhotoSwipe
		var rootClasses = 'pswp--open ';
		if(_options.mainClass) {
			rootClasses += _options.mainClass + ' ';
		}
		if(_options.showHideOpacity) {
			rootClasses += 'pswp--animate_opacity ';
		}
		rootClasses += _likelyTouchDevice ? 'pswp--touch' : 'pswp--notouch';
		rootClasses += _features.animationName ? ' pswp--css_animation' : '';
		rootClasses += _features.svg ? ' pswp--svg' : '';
		framework.addClass(template, rootClasses);

		self.updateSize();

		// initial update
		_containerShiftIndex = -1;
		_indexDiff = null;
		for(i = 0; i < NUM_HOLDERS; i++) {
			_setTranslateX( (i+_containerShiftIndex) * _slideSize.x, _itemHolders[i].el.style);
		}

		if(!_oldIE) {
			framework.bind(self.scrollWrap, _downEvents, self); // no dragging for old IE
		}	

		_listen('initialZoomInEnd', function() {
			self.setContent(_itemHolders[0], _currentItemIndex-1);
			self.setContent(_itemHolders[2], _currentItemIndex+1);

			_itemHolders[0].el.style.display = _itemHolders[2].el.style.display = 'block';

			if(_options.focus) {
				// focus causes layout, 
				// which causes lag during the animation, 
				// that's why we delay it untill the initial zoom transition ends
				template.focus();
			}
			 

			_bindEvents();
		});

		// set content for center slide (first time)
		self.setContent(_itemHolders[1], _currentItemIndex);
		
		self.updateCurrItem();

		_shout('afterInit');

		if(!_isFixedPosition) {

			// On all versions of iOS lower than 8.0, we check size of viewport every second.
			// 
			// This is done to detect when Safari top & bottom bars appear, 
			// as this action doesn't trigger any events (like resize). 
			// 
			// On iOS8 they fixed this.
			// 
			// 10 Nov 2014: iOS 7 usage ~40%. iOS 8 usage 56%.
			
			_updateSizeInterval = setInterval(function() {
				if(!_numAnimations && !_isDragging && !_isZooming && (_currZoomLevel === self.currItem.initialZoomLevel)  ) {
					self.updateSize();
				}
			}, 1000);
		}

		framework.addClass(template, 'pswp--visible');
	},

	// Close the gallery, then destroy it
	close: function() {
		if(!_isOpen) {
			return;
		}

		_isOpen = false;
		_isDestroying = true;
		_shout('close');
		_unbindEvents();

		_showOrHide(self.currItem, null, true, self.destroy);
	},

	// destroys the gallery (unbinds events, cleans up intervals and timeouts to avoid memory leaks)
	destroy: function() {
		_shout('destroy');

		if(_showOrHideTimeout) {
			clearTimeout(_showOrHideTimeout);
		}
		
		template.setAttribute('aria-hidden', 'true');
		template.className = _initalClassName;

		if(_updateSizeInterval) {
			clearInterval(_updateSizeInterval);
		}

		framework.unbind(self.scrollWrap, _downEvents, self);

		// we unbind scroll event at the end, as closing animation may depend on it
		framework.unbind(window, 'scroll', self);

		_stopDragUpdateLoop();

		_stopAllAnimations();

		_listeners = null;
	},

	/**
	 * Pan image to position
	 * @param {Number} x     
	 * @param {Number} y     
	 * @param {Boolean} force Will ignore bounds if set to true.
	 */
	panTo: function(x,y,force) {
		if(!force) {
			if(x > _currPanBounds.min.x) {
				x = _currPanBounds.min.x;
			} else if(x < _currPanBounds.max.x) {
				x = _currPanBounds.max.x;
			}

			if(y > _currPanBounds.min.y) {
				y = _currPanBounds.min.y;
			} else if(y < _currPanBounds.max.y) {
				y = _currPanBounds.max.y;
			}
		}
		
		_panOffset.x = x;
		_panOffset.y = y;
		_applyCurrentZoomPan();
	},
	
	handleEvent: function (e) {
		e = e || window.event;
		if(_globalEventHandlers[e.type]) {
			_globalEventHandlers[e.type](e);
		}
	},


	goTo: function(index) {

		index = _getLoopedId(index);

		var diff = index - _currentItemIndex;
		_indexDiff = diff;

		_currentItemIndex = index;
		self.currItem = _getItemAt( _currentItemIndex );
		_currPositionIndex -= diff;
		
		_moveMainScroll(_slideSize.x * _currPositionIndex);
		

		_stopAllAnimations();
		_mainScrollAnimating = false;

		self.updateCurrItem();
	},
	next: function() {
		self.goTo( _currentItemIndex + 1);
	},
	prev: function() {
		self.goTo( _currentItemIndex - 1);
	},

	// update current zoom/pan objects
	updateCurrZoomItem: function(emulateSetContent) {
		if(emulateSetContent) {
			_shout('beforeChange', 0);
		}

		// itemHolder[1] is middle (current) item
		if(_itemHolders[1].el.children.length) {
			var zoomElement = _itemHolders[1].el.children[0];
			if( framework.hasClass(zoomElement, 'pswp__zoom-wrap') ) {
				_currZoomElementStyle = zoomElement.style;
			} else {
				_currZoomElementStyle = null;
			}
		} else {
			_currZoomElementStyle = null;
		}
		
		_currPanBounds = self.currItem.bounds;	
		_startZoomLevel = _currZoomLevel = self.currItem.initialZoomLevel;

		_panOffset.x = _currPanBounds.center.x;
		_panOffset.y = _currPanBounds.center.y;

		if(emulateSetContent) {
			_shout('afterChange');
		}
	},


	invalidateCurrItems: function() {
		_itemsNeedUpdate = true;
		for(var i = 0; i < NUM_HOLDERS; i++) {
			if( _itemHolders[i].item ) {
				_itemHolders[i].item.needsUpdate = true;
			}
		}
	},

	updateCurrItem: function(beforeAnimation) {

		if(_indexDiff === 0) {
			return;
		}

		var diffAbs = Math.abs(_indexDiff),
			tempHolder;

		if(beforeAnimation && diffAbs < 2) {
			return;
		}


		self.currItem = _getItemAt( _currentItemIndex );
		_renderMaxResolution = false;
		
		_shout('beforeChange', _indexDiff);

		if(diffAbs >= NUM_HOLDERS) {
			_containerShiftIndex += _indexDiff + (_indexDiff > 0 ? -NUM_HOLDERS : NUM_HOLDERS);
			diffAbs = NUM_HOLDERS;
		}
		for(var i = 0; i < diffAbs; i++) {
			if(_indexDiff > 0) {
				tempHolder = _itemHolders.shift();
				_itemHolders[NUM_HOLDERS-1] = tempHolder; // move first to last

				_containerShiftIndex++;
				_setTranslateX( (_containerShiftIndex+2) * _slideSize.x, tempHolder.el.style);
				self.setContent(tempHolder, _currentItemIndex - diffAbs + i + 1 + 1);
			} else {
				tempHolder = _itemHolders.pop();
				_itemHolders.unshift( tempHolder ); // move last to first

				_containerShiftIndex--;
				_setTranslateX( _containerShiftIndex * _slideSize.x, tempHolder.el.style);
				self.setContent(tempHolder, _currentItemIndex + diffAbs - i - 1 - 1);
			}
			
		}

		// reset zoom/pan on previous item
		if(_currZoomElementStyle && Math.abs(_indexDiff) === 1) {

			var prevItem = _getItemAt(_prevItemIndex);
			if(prevItem.initialZoomLevel !== _currZoomLevel) {
				_calculateItemSize(prevItem , _viewportSize );
				_setImageSize(prevItem);
				_applyZoomPanToItem( prevItem ); 				
			}

		}

		// reset diff after update
		_indexDiff = 0;

		self.updateCurrZoomItem();

		_prevItemIndex = _currentItemIndex;

		_shout('afterChange');
		
	},



	updateSize: function(force) {
		
		if(!_isFixedPosition && _options.modal) {
			var windowScrollY = framework.getScrollY();
			if(_currentWindowScrollY !== windowScrollY) {
				template.style.top = windowScrollY + 'px';
				_currentWindowScrollY = windowScrollY;
			}
			if(!force && _windowVisibleSize.x === window.innerWidth && _windowVisibleSize.y === window.innerHeight) {
				return;
			}
			_windowVisibleSize.x = window.innerWidth;
			_windowVisibleSize.y = window.innerHeight;

			//template.style.width = _windowVisibleSize.x + 'px';
			template.style.height = _windowVisibleSize.y + 'px';
		}



		_viewportSize.x = self.scrollWrap.clientWidth;
		_viewportSize.y = self.scrollWrap.clientHeight;

		_updatePageScrollOffset();

		_slideSize.x = _viewportSize.x + Math.round(_viewportSize.x * _options.spacing);
		_slideSize.y = _viewportSize.y;

		_moveMainScroll(_slideSize.x * _currPositionIndex);

		_shout('beforeResize'); // even may be used for example to switch image sources


		// don't re-calculate size on inital size update
		if(_containerShiftIndex !== undefined) {

			var holder,
				item,
				hIndex;

			for(var i = 0; i < NUM_HOLDERS; i++) {
				holder = _itemHolders[i];
				_setTranslateX( (i+_containerShiftIndex) * _slideSize.x, holder.el.style);

				hIndex = _currentItemIndex+i-1;

				if(_options.loop && _getNumItems() > 2) {
					hIndex = _getLoopedId(hIndex);
				}

				// update zoom level on items and refresh source (if needsUpdate)
				item = _getItemAt( hIndex );

				// re-render gallery item if `needsUpdate`,
				// or doesn't have `bounds` (entirely new slide object)
				if( item && (_itemsNeedUpdate || item.needsUpdate || !item.bounds) ) {

					self.cleanSlide( item );
					
					self.setContent( holder, hIndex );

					// if "center" slide
					if(i === 1) {
						self.currItem = item;
						self.updateCurrZoomItem(true);
					}

					item.needsUpdate = false;

				} else if(holder.index === -1 && hIndex >= 0) {
					// add content first time
					self.setContent( holder, hIndex );
				}
				if(item && item.container) {
					_calculateItemSize(item, _viewportSize);
					_setImageSize(item);
					_applyZoomPanToItem( item );
				}
				
			}
			_itemsNeedUpdate = false;
		}	

		_startZoomLevel = _currZoomLevel = self.currItem.initialZoomLevel;
		_currPanBounds = self.currItem.bounds;

		if(_currPanBounds) {
			_panOffset.x = _currPanBounds.center.x;
			_panOffset.y = _currPanBounds.center.y;
			_applyCurrentZoomPan( true );
		}
		
		_shout('resize');
	},
	
	// Zoom current item to
	zoomTo: function(destZoomLevel, centerPoint, speed, easingFn, updateFn) {
		/*
			if(destZoomLevel === 'fit') {
				destZoomLevel = self.currItem.fitRatio;
			} else if(destZoomLevel === 'fill') {
				destZoomLevel = self.currItem.fillRatio;
			}
		*/

		if(centerPoint) {
			_startZoomLevel = _currZoomLevel;
			_midZoomPoint.x = Math.abs(centerPoint.x) - _panOffset.x ;
			_midZoomPoint.y = Math.abs(centerPoint.y) - _panOffset.y ;
			_equalizePoints(_startPanOffset, _panOffset);
		}

		var destPanBounds = _calculatePanBounds(destZoomLevel, false),
			destPanOffset = {};

		_modifyDestPanOffset('x', destPanBounds, destPanOffset, destZoomLevel);
		_modifyDestPanOffset('y', destPanBounds, destPanOffset, destZoomLevel);

		var initialZoomLevel = _currZoomLevel;
		var initialPanOffset = {
			x: _panOffset.x,
			y: _panOffset.y
		};

		_roundPoint(destPanOffset);

		var onUpdate = function(now) {
			if(now === 1) {
				_currZoomLevel = destZoomLevel;
				_panOffset.x = destPanOffset.x;
				_panOffset.y = destPanOffset.y;
			} else {
				_currZoomLevel = (destZoomLevel - initialZoomLevel) * now + initialZoomLevel;
				_panOffset.x = (destPanOffset.x - initialPanOffset.x) * now + initialPanOffset.x;
				_panOffset.y = (destPanOffset.y - initialPanOffset.y) * now + initialPanOffset.y;
			}

			if(updateFn) {
				updateFn(now);
			}

			_applyCurrentZoomPan( now === 1 );
		};

		if(speed) {
			_animateProp('customZoomTo', 0, 1, speed, easingFn || framework.easing.sine.inOut, onUpdate);
		} else {
			onUpdate(1);
		}
	}


};


/*>>core*/

/*>>gestures*/
/**
 * Mouse/touch/pointer event handlers.
 * 
 * separated from @core.js for readability
 */

var MIN_SWIPE_DISTANCE = 30,
	DIRECTION_CHECK_OFFSET = 10; // amount of pixels to drag to determine direction of swipe

var _gestureStartTime,
	_gestureCheckSpeedTime,

	// pool of objects that are used during dragging of zooming
	p = {}, // first point
	p2 = {}, // second point (for zoom gesture)
	delta = {},
	_currPoint = {},
	_startPoint = {},
	_currPointers = [],
	_startMainScrollPos = {},
	_releaseAnimData,
	_posPoints = [], // array of points during dragging, used to determine type of gesture
	_tempPoint = {},

	_isZoomingIn,
	_verticalDragInitiated,
	_oldAndroidTouchEndTimeout,
	_currZoomedItemIndex = 0,
	_centerPoint = _getEmptyPoint(),
	_lastReleaseTime = 0,
	_isDragging, // at least one pointer is down
	_isMultitouch, // at least two _pointers are down
	_zoomStarted, // zoom level changed during zoom gesture
	_moved,
	_dragAnimFrame,
	_mainScrollShifted,
	_currentPoints, // array of current touch points
	_isZooming,
	_currPointsDistance,
	_startPointsDistance,
	_currPanBounds,
	_mainScrollPos = _getEmptyPoint(),
	_currZoomElementStyle,
	_mainScrollAnimating, // true, if animation after swipe gesture is running
	_midZoomPoint = _getEmptyPoint(),
	_currCenterPoint = _getEmptyPoint(),
	_direction,
	_isFirstMove,
	_opacityChanged,
	_bgOpacity,
	_wasOverInitialZoom,

	_isEqualPoints = function(p1, p2) {
		return p1.x === p2.x && p1.y === p2.y;
	},
	_isNearbyPoints = function(touch0, touch1) {
		return Math.abs(touch0.x - touch1.x) < DOUBLE_TAP_RADIUS && Math.abs(touch0.y - touch1.y) < DOUBLE_TAP_RADIUS;
	},
	_calculatePointsDistance = function(p1, p2) {
		_tempPoint.x = Math.abs( p1.x - p2.x );
		_tempPoint.y = Math.abs( p1.y - p2.y );
		return Math.sqrt(_tempPoint.x * _tempPoint.x + _tempPoint.y * _tempPoint.y);
	},
	_stopDragUpdateLoop = function() {
		if(_dragAnimFrame) {
			_cancelAF(_dragAnimFrame);
			_dragAnimFrame = null;
		}
	},
	_dragUpdateLoop = function() {
		if(_isDragging) {
			_dragAnimFrame = _requestAF(_dragUpdateLoop);
			_renderMovement();
		}
	},
	_canPan = function() {
		return !(_options.scaleMode === 'fit' && _currZoomLevel ===  self.currItem.initialZoomLevel);
	},
	
	// find the closest parent DOM element
	_closestElement = function(el, fn) {
	  	if(!el || el === document) {
	  		return false;
	  	}

	  	// don't search elements above pswp__scroll-wrap
	  	if(el.getAttribute('class') && el.getAttribute('class').indexOf('pswp__scroll-wrap') > -1 ) {
	  		return false;
	  	}

	  	if( fn(el) ) {
	  		return el;
	  	}

	  	return _closestElement(el.parentNode, fn);
	},

	_preventObj = {},
	_preventDefaultEventBehaviour = function(e, isDown) {
	    _preventObj.prevent = !_closestElement(e.target, _options.isClickableElement);

		_shout('preventDragEvent', e, isDown, _preventObj);
		return _preventObj.prevent;

	},
	_convertTouchToPoint = function(touch, p) {
		p.x = touch.pageX;
		p.y = touch.pageY;
		p.id = touch.identifier;
		return p;
	},
	_findCenterOfPoints = function(p1, p2, pCenter) {
		pCenter.x = (p1.x + p2.x) * 0.5;
		pCenter.y = (p1.y + p2.y) * 0.5;
	},
	_pushPosPoint = function(time, x, y) {
		if(time - _gestureCheckSpeedTime > 50) {
			var o = _posPoints.length > 2 ? _posPoints.shift() : {};
			o.x = x;
			o.y = y; 
			_posPoints.push(o);
			_gestureCheckSpeedTime = time;
		}
	},

	_calculateVerticalDragOpacityRatio = function() {
		var yOffset = _panOffset.y - self.currItem.initialPosition.y; // difference between initial and current position
		return 1 -  Math.abs( yOffset / (_viewportSize.y / 2)  );
	},

	
	// points pool, reused during touch events
	_ePoint1 = {},
	_ePoint2 = {},
	_tempPointsArr = [],
	_tempCounter,
	_getTouchPoints = function(e) {
		// clean up previous points, without recreating array
		while(_tempPointsArr.length > 0) {
			_tempPointsArr.pop();
		}

		if(!_pointerEventEnabled) {
			if(e.type.indexOf('touch') > -1) {

				if(e.touches && e.touches.length > 0) {
					_tempPointsArr[0] = _convertTouchToPoint(e.touches[0], _ePoint1);
					if(e.touches.length > 1) {
						_tempPointsArr[1] = _convertTouchToPoint(e.touches[1], _ePoint2);
					}
				}
				
			} else {
				_ePoint1.x = e.pageX;
				_ePoint1.y = e.pageY;
				_ePoint1.id = '';
				_tempPointsArr[0] = _ePoint1;//_ePoint1;
			}
		} else {
			_tempCounter = 0;
			// we can use forEach, as pointer events are supported only in modern browsers
			_currPointers.forEach(function(p) {
				if(_tempCounter === 0) {
					_tempPointsArr[0] = p;
				} else if(_tempCounter === 1) {
					_tempPointsArr[1] = p;
				}
				_tempCounter++;

			});
		}
		return _tempPointsArr;
	},

	_panOrMoveMainScroll = function(axis, delta) {

		var panFriction,
			overDiff = 0,
			newOffset = _panOffset[axis] + delta[axis],
			startOverDiff,
			dir = delta[axis] > 0,
			newMainScrollPosition = _mainScrollPos.x + delta.x,
			mainScrollDiff = _mainScrollPos.x - _startMainScrollPos.x,
			newPanPos,
			newMainScrollPos;

		// calculate fdistance over the bounds and friction
		if(newOffset > _currPanBounds.min[axis] || newOffset < _currPanBounds.max[axis]) {
			panFriction = _options.panEndFriction;
			// Linear increasing of friction, so at 1/4 of viewport it's at max value. 
			// Looks not as nice as was expected. Left for history.
			// panFriction = (1 - (_panOffset[axis] + delta[axis] + panBounds.min[axis]) / (_viewportSize[axis] / 4) );
		} else {
			panFriction = 1;
		}
		
		newOffset = _panOffset[axis] + delta[axis] * panFriction;

		// move main scroll or start panning
		if(_options.allowPanToNext || _currZoomLevel === self.currItem.initialZoomLevel) {


			if(!_currZoomElementStyle) {
				
				newMainScrollPos = newMainScrollPosition;

			} else if(_direction === 'h' && axis === 'x' && !_zoomStarted ) {
				
				if(dir) {
					if(newOffset > _currPanBounds.min[axis]) {
						panFriction = _options.panEndFriction;
						overDiff = _currPanBounds.min[axis] - newOffset;
						startOverDiff = _currPanBounds.min[axis] - _startPanOffset[axis];
					}
					
					// drag right
					if( (startOverDiff <= 0 || mainScrollDiff < 0) && _getNumItems() > 1 ) {
						newMainScrollPos = newMainScrollPosition;
						if(mainScrollDiff < 0 && newMainScrollPosition > _startMainScrollPos.x) {
							newMainScrollPos = _startMainScrollPos.x;
						}
					} else {
						if(_currPanBounds.min.x !== _currPanBounds.max.x) {
							newPanPos = newOffset;
						}
						
					}

				} else {

					if(newOffset < _currPanBounds.max[axis] ) {
						panFriction =_options.panEndFriction;
						overDiff = newOffset - _currPanBounds.max[axis];
						startOverDiff = _startPanOffset[axis] - _currPanBounds.max[axis];
					}

					if( (startOverDiff <= 0 || mainScrollDiff > 0) && _getNumItems() > 1 ) {
						newMainScrollPos = newMainScrollPosition;

						if(mainScrollDiff > 0 && newMainScrollPosition < _startMainScrollPos.x) {
							newMainScrollPos = _startMainScrollPos.x;
						}

					} else {
						if(_currPanBounds.min.x !== _currPanBounds.max.x) {
							newPanPos = newOffset;
						}
					}

				}


				//
			}

			if(axis === 'x') {

				if(newMainScrollPos !== undefined) {
					_moveMainScroll(newMainScrollPos, true);
					if(newMainScrollPos === _startMainScrollPos.x) {
						_mainScrollShifted = false;
					} else {
						_mainScrollShifted = true;
					}
				}

				if(_currPanBounds.min.x !== _currPanBounds.max.x) {
					if(newPanPos !== undefined) {
						_panOffset.x = newPanPos;
					} else if(!_mainScrollShifted) {
						_panOffset.x += delta.x * panFriction;
					}
				}

				return newMainScrollPos !== undefined;
			}

		}

		if(!_mainScrollAnimating) {
			
			if(!_mainScrollShifted) {
				if(_currZoomLevel > self.currItem.fitRatio) {
					_panOffset[axis] += delta[axis] * panFriction;
				
				}
			}

			
		}
		
	},

	// Pointerdown/touchstart/mousedown handler
	_onDragStart = function(e) {

		// Allow dragging only via left mouse button.
		// As this handler is not added in IE8 - we ignore e.which
		// 
		// http://www.quirksmode.org/js/events_properties.html
		// https://developer.mozilla.org/en-US/docs/Web/API/event.button
		if(e.type === 'mousedown' && e.button > 0  ) {
			return;
		}

		if(_initialZoomRunning) {
			e.preventDefault();
			return;
		}

		if(_oldAndroidTouchEndTimeout && e.type === 'mousedown') {
			return;
		}

		if(_preventDefaultEventBehaviour(e, true)) {
			e.preventDefault();
		}



		_shout('pointerDown');

		if(_pointerEventEnabled) {
			var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id');
			if(pointerIndex < 0) {
				pointerIndex = _currPointers.length;
			}
			_currPointers[pointerIndex] = {x:e.pageX, y:e.pageY, id: e.pointerId};
		}
		


		var startPointsList = _getTouchPoints(e),
			numPoints = startPointsList.length;

		_currentPoints = null;

		_stopAllAnimations();

		// init drag
		if(!_isDragging || numPoints === 1) {

			

			_isDragging = _isFirstMove = true;
			framework.bind(window, _upMoveEvents, self);

			_isZoomingIn = 
				_wasOverInitialZoom = 
				_opacityChanged = 
				_verticalDragInitiated = 
				_mainScrollShifted = 
				_moved = 
				_isMultitouch = 
				_zoomStarted = false;

			_direction = null;

			_shout('firstTouchStart', startPointsList);

			_equalizePoints(_startPanOffset, _panOffset);

			_currPanDist.x = _currPanDist.y = 0;
			_equalizePoints(_currPoint, startPointsList[0]);
			_equalizePoints(_startPoint, _currPoint);

			//_equalizePoints(_startMainScrollPos, _mainScrollPos);
			_startMainScrollPos.x = _slideSize.x * _currPositionIndex;

			_posPoints = [{
				x: _currPoint.x,
				y: _currPoint.y
			}];

			_gestureCheckSpeedTime = _gestureStartTime = _getCurrentTime();

			//_mainScrollAnimationEnd(true);
			_calculatePanBounds( _currZoomLevel, true );
			
			// Start rendering
			_stopDragUpdateLoop();
			_dragUpdateLoop();
			
		}

		// init zoom
		if(!_isZooming && numPoints > 1 && !_mainScrollAnimating && !_mainScrollShifted) {
			_startZoomLevel = _currZoomLevel;
			_zoomStarted = false; // true if zoom changed at least once

			_isZooming = _isMultitouch = true;
			_currPanDist.y = _currPanDist.x = 0;

			_equalizePoints(_startPanOffset, _panOffset);

			_equalizePoints(p, startPointsList[0]);
			_equalizePoints(p2, startPointsList[1]);

			_findCenterOfPoints(p, p2, _currCenterPoint);

			_midZoomPoint.x = Math.abs(_currCenterPoint.x) - _panOffset.x;
			_midZoomPoint.y = Math.abs(_currCenterPoint.y) - _panOffset.y;
			_currPointsDistance = _startPointsDistance = _calculatePointsDistance(p, p2);
		}


	},

	// Pointermove/touchmove/mousemove handler
	_onDragMove = function(e) {

		e.preventDefault();

		if(_pointerEventEnabled) {
			var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id');
			if(pointerIndex > -1) {
				var p = _currPointers[pointerIndex];
				p.x = e.pageX;
				p.y = e.pageY; 
			}
		}

		if(_isDragging) {
			var touchesList = _getTouchPoints(e);
			if(!_direction && !_moved && !_isZooming) {

				if(_mainScrollPos.x !== _slideSize.x * _currPositionIndex) {
					// if main scroll position is shifted – direction is always horizontal
					_direction = 'h';
				} else {
					var diff = Math.abs(touchesList[0].x - _currPoint.x) - Math.abs(touchesList[0].y - _currPoint.y);
					// check the direction of movement
					if(Math.abs(diff) >= DIRECTION_CHECK_OFFSET) {
						_direction = diff > 0 ? 'h' : 'v';
						_currentPoints = touchesList;
					}
				}
				
			} else {
				_currentPoints = touchesList;
			}
		}	
	},
	// 
	_renderMovement =  function() {

		if(!_currentPoints) {
			return;
		}

		var numPoints = _currentPoints.length;

		if(numPoints === 0) {
			return;
		}

		_equalizePoints(p, _currentPoints[0]);

		delta.x = p.x - _currPoint.x;
		delta.y = p.y - _currPoint.y;

		if(_isZooming && numPoints > 1) {
			// Handle behaviour for more than 1 point

			_currPoint.x = p.x;
			_currPoint.y = p.y;
		
			// check if one of two points changed
			if( !delta.x && !delta.y && _isEqualPoints(_currentPoints[1], p2) ) {
				return;
			}

			_equalizePoints(p2, _currentPoints[1]);


			if(!_zoomStarted) {
				_zoomStarted = true;
				_shout('zoomGestureStarted');
			}
			
			// Distance between two points
			var pointsDistance = _calculatePointsDistance(p,p2);

			var zoomLevel = _calculateZoomLevel(pointsDistance);

			// slightly over the of initial zoom level
			if(zoomLevel > self.currItem.initialZoomLevel + self.currItem.initialZoomLevel / 15) {
				_wasOverInitialZoom = true;
			}

			// Apply the friction if zoom level is out of the bounds
			var zoomFriction = 1,
				minZoomLevel = _getMinZoomLevel(),
				maxZoomLevel = _getMaxZoomLevel();

			if ( zoomLevel < minZoomLevel ) {
				
				if(_options.pinchToClose && !_wasOverInitialZoom && _startZoomLevel <= self.currItem.initialZoomLevel) {
					// fade out background if zooming out
					var minusDiff = minZoomLevel - zoomLevel;
					var percent = 1 - minusDiff / (minZoomLevel / 1.2);

					_applyBgOpacity(percent);
					_shout('onPinchClose', percent);
					_opacityChanged = true;
				} else {
					zoomFriction = (minZoomLevel - zoomLevel) / minZoomLevel;
					if(zoomFriction > 1) {
						zoomFriction = 1;
					}
					zoomLevel = minZoomLevel - zoomFriction * (minZoomLevel / 3);
				}
				
			} else if ( zoomLevel > maxZoomLevel ) {
				// 1.5 - extra zoom level above the max. E.g. if max is x6, real max 6 + 1.5 = 7.5
				zoomFriction = (zoomLevel - maxZoomLevel) / ( minZoomLevel * 6 );
				if(zoomFriction > 1) {
					zoomFriction = 1;
				}
				zoomLevel = maxZoomLevel + zoomFriction * minZoomLevel;
			}

			if(zoomFriction < 0) {
				zoomFriction = 0;
			}

			// distance between touch points after friction is applied
			_currPointsDistance = pointsDistance;

			// _centerPoint - The point in the middle of two pointers
			_findCenterOfPoints(p, p2, _centerPoint);
		
			// paning with two pointers pressed
			_currPanDist.x += _centerPoint.x - _currCenterPoint.x;
			_currPanDist.y += _centerPoint.y - _currCenterPoint.y;
			_equalizePoints(_currCenterPoint, _centerPoint);

			_panOffset.x = _calculatePanOffset('x', zoomLevel);
			_panOffset.y = _calculatePanOffset('y', zoomLevel);

			_isZoomingIn = zoomLevel > _currZoomLevel;
			_currZoomLevel = zoomLevel;
			_applyCurrentZoomPan();

		} else {

			// handle behaviour for one point (dragging or panning)

			if(!_direction) {
				return;
			}

			if(_isFirstMove) {
				_isFirstMove = false;

				// subtract drag distance that was used during the detection direction  

				if( Math.abs(delta.x) >= DIRECTION_CHECK_OFFSET) {
					delta.x -= _currentPoints[0].x - _startPoint.x;
				}
				
				if( Math.abs(delta.y) >= DIRECTION_CHECK_OFFSET) {
					delta.y -= _currentPoints[0].y - _startPoint.y;
				}
			}

			_currPoint.x = p.x;
			_currPoint.y = p.y;

			// do nothing if pointers position hasn't changed
			if(delta.x === 0 && delta.y === 0) {
				return;
			}

			if(_direction === 'v' && _options.closeOnVerticalDrag) {
				if(!_canPan()) {
					_currPanDist.y += delta.y;
					_panOffset.y += delta.y;

					var opacityRatio = _calculateVerticalDragOpacityRatio();

					_verticalDragInitiated = true;
					_shout('onVerticalDrag', opacityRatio);

					_applyBgOpacity(opacityRatio);
					_applyCurrentZoomPan();
					return ;
				}
			}

			_pushPosPoint(_getCurrentTime(), p.x, p.y);

			_moved = true;
			_currPanBounds = self.currItem.bounds;
			
			var mainScrollChanged = _panOrMoveMainScroll('x', delta);
			if(!mainScrollChanged) {
				_panOrMoveMainScroll('y', delta);

				_roundPoint(_panOffset);
				_applyCurrentZoomPan();
			}

		}

	},
	
	// Pointerup/pointercancel/touchend/touchcancel/mouseup event handler
	_onDragRelease = function(e) {

		if(_features.isOldAndroid ) {

			if(_oldAndroidTouchEndTimeout && e.type === 'mouseup') {
				return;
			}

			// on Android (v4.1, 4.2, 4.3 & possibly older) 
			// ghost mousedown/up event isn't preventable via e.preventDefault,
			// which causes fake mousedown event
			// so we block mousedown/up for 600ms
			if( e.type.indexOf('touch') > -1 ) {
				clearTimeout(_oldAndroidTouchEndTimeout);
				_oldAndroidTouchEndTimeout = setTimeout(function() {
					_oldAndroidTouchEndTimeout = 0;
				}, 600);
			}
			
		}

		_shout('pointerUp');

		if(_preventDefaultEventBehaviour(e, false)) {
			e.preventDefault();
		}

		var releasePoint;

		if(_pointerEventEnabled) {
			var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id');
			
			if(pointerIndex > -1) {
				releasePoint = _currPointers.splice(pointerIndex, 1)[0];

				if(navigator.pointerEnabled) {
					releasePoint.type = e.pointerType || 'mouse';
				} else {
					var MSPOINTER_TYPES = {
						4: 'mouse', // event.MSPOINTER_TYPE_MOUSE
						2: 'touch', // event.MSPOINTER_TYPE_TOUCH 
						3: 'pen' // event.MSPOINTER_TYPE_PEN
					};
					releasePoint.type = MSPOINTER_TYPES[e.pointerType];

					if(!releasePoint.type) {
						releasePoint.type = e.pointerType || 'mouse';
					}
				}

			}
		}

		var touchList = _getTouchPoints(e),
			gestureType,
			numPoints = touchList.length;

		if(e.type === 'mouseup') {
			numPoints = 0;
		}

		// Do nothing if there were 3 touch points or more
		if(numPoints === 2) {
			_currentPoints = null;
			return true;
		}

		// if second pointer released
		if(numPoints === 1) {
			_equalizePoints(_startPoint, touchList[0]);
		}				


		// pointer hasn't moved, send "tap release" point
		if(numPoints === 0 && !_direction && !_mainScrollAnimating) {
			if(!releasePoint) {
				if(e.type === 'mouseup') {
					releasePoint = {x: e.pageX, y: e.pageY, type:'mouse'};
				} else if(e.changedTouches && e.changedTouches[0]) {
					releasePoint = {x: e.changedTouches[0].pageX, y: e.changedTouches[0].pageY, type:'touch'};
				}		
			}

			_shout('touchRelease', e, releasePoint);
		}

		// Difference in time between releasing of two last touch points (zoom gesture)
		var releaseTimeDiff = -1;

		// Gesture completed, no pointers left
		if(numPoints === 0) {
			_isDragging = false;
			framework.unbind(window, _upMoveEvents, self);

			_stopDragUpdateLoop();

			if(_isZooming) {
				// Two points released at the same time
				releaseTimeDiff = 0;
			} else if(_lastReleaseTime !== -1) {
				releaseTimeDiff = _getCurrentTime() - _lastReleaseTime;
			}
		}
		_lastReleaseTime = numPoints === 1 ? _getCurrentTime() : -1;
		
		if(releaseTimeDiff !== -1 && releaseTimeDiff < 150) {
			gestureType = 'zoom';
		} else {
			gestureType = 'swipe';
		}

		if(_isZooming && numPoints < 2) {
			_isZooming = false;

			// Only second point released
			if(numPoints === 1) {
				gestureType = 'zoomPointerUp';
			}
			_shout('zoomGestureEnded');
		}

		_currentPoints = null;
		if(!_moved && !_zoomStarted && !_mainScrollAnimating && !_verticalDragInitiated) {
			// nothing to animate
			return;
		}
	
		_stopAllAnimations();

		
		if(!_releaseAnimData) {
			_releaseAnimData = _initDragReleaseAnimationData();
		}
		
		_releaseAnimData.calculateSwipeSpeed('x');


		if(_verticalDragInitiated) {

			var opacityRatio = _calculateVerticalDragOpacityRatio();

			if(opacityRatio < _options.verticalDragRange) {
				self.close();
			} else {
				var initalPanY = _panOffset.y,
					initialBgOpacity = _bgOpacity;

				_animateProp('verticalDrag', 0, 1, 300, framework.easing.cubic.out, function(now) {
					
					_panOffset.y = (self.currItem.initialPosition.y - initalPanY) * now + initalPanY;

					_applyBgOpacity(  (1 - initialBgOpacity) * now + initialBgOpacity );
					_applyCurrentZoomPan();
				});

				_shout('onVerticalDrag', 1);
			}

			return;
		}


		// main scroll 
		if(  (_mainScrollShifted || _mainScrollAnimating) && numPoints === 0) {
			var itemChanged = _finishSwipeMainScrollGesture(gestureType, _releaseAnimData);
			if(itemChanged) {
				return;
			}
			gestureType = 'zoomPointerUp';
		}

		// prevent zoom/pan animation when main scroll animation runs
		if(_mainScrollAnimating) {
			return;
		}
		
		// Complete simple zoom gesture (reset zoom level if it's out of the bounds)  
		if(gestureType !== 'swipe') {
			_completeZoomGesture();
			return;
		}
	
		// Complete pan gesture if main scroll is not shifted, and it's possible to pan current image
		if(!_mainScrollShifted && _currZoomLevel > self.currItem.fitRatio) {
			_completePanGesture(_releaseAnimData);
		}
	},


	// Returns object with data about gesture
	// It's created only once and then reused
	_initDragReleaseAnimationData  = function() {
		// temp local vars
		var lastFlickDuration,
			tempReleasePos;

		// s = this
		var s = {
			lastFlickOffset: {},
			lastFlickDist: {},
			lastFlickSpeed: {},
			slowDownRatio:  {},
			slowDownRatioReverse:  {},
			speedDecelerationRatio:  {},
			speedDecelerationRatioAbs:  {},
			distanceOffset:  {},
			backAnimDestination: {},
			backAnimStarted: {},
			calculateSwipeSpeed: function(axis) {
				

				if( _posPoints.length > 1) {
					lastFlickDuration = _getCurrentTime() - _gestureCheckSpeedTime + 50;
					tempReleasePos = _posPoints[_posPoints.length-2][axis];
				} else {
					lastFlickDuration = _getCurrentTime() - _gestureStartTime; // total gesture duration
					tempReleasePos = _startPoint[axis];
				}
				s.lastFlickOffset[axis] = _currPoint[axis] - tempReleasePos;
				s.lastFlickDist[axis] = Math.abs(s.lastFlickOffset[axis]);
				if(s.lastFlickDist[axis] > 20) {
					s.lastFlickSpeed[axis] = s.lastFlickOffset[axis] / lastFlickDuration;
				} else {
					s.lastFlickSpeed[axis] = 0;
				}
				if( Math.abs(s.lastFlickSpeed[axis]) < 0.1 ) {
					s.lastFlickSpeed[axis] = 0;
				}
				
				s.slowDownRatio[axis] = 0.95;
				s.slowDownRatioReverse[axis] = 1 - s.slowDownRatio[axis];
				s.speedDecelerationRatio[axis] = 1;
			},

			calculateOverBoundsAnimOffset: function(axis, speed) {
				if(!s.backAnimStarted[axis]) {

					if(_panOffset[axis] > _currPanBounds.min[axis]) {
						s.backAnimDestination[axis] = _currPanBounds.min[axis];
						
					} else if(_panOffset[axis] < _currPanBounds.max[axis]) {
						s.backAnimDestination[axis] = _currPanBounds.max[axis];
					}

					if(s.backAnimDestination[axis] !== undefined) {
						s.slowDownRatio[axis] = 0.7;
						s.slowDownRatioReverse[axis] = 1 - s.slowDownRatio[axis];
						if(s.speedDecelerationRatioAbs[axis] < 0.05) {

							s.lastFlickSpeed[axis] = 0;
							s.backAnimStarted[axis] = true;

							_animateProp('bounceZoomPan'+axis,_panOffset[axis], 
								s.backAnimDestination[axis], 
								speed || 300, 
								framework.easing.sine.out, 
								function(pos) {
									_panOffset[axis] = pos;
									_applyCurrentZoomPan();
								}
							);

						}
					}
				}
			},

			// Reduces the speed by slowDownRatio (per 10ms)
			calculateAnimOffset: function(axis) {
				if(!s.backAnimStarted[axis]) {
					s.speedDecelerationRatio[axis] = s.speedDecelerationRatio[axis] * (s.slowDownRatio[axis] + 
												s.slowDownRatioReverse[axis] - 
												s.slowDownRatioReverse[axis] * s.timeDiff / 10);

					s.speedDecelerationRatioAbs[axis] = Math.abs(s.lastFlickSpeed[axis] * s.speedDecelerationRatio[axis]);
					s.distanceOffset[axis] = s.lastFlickSpeed[axis] * s.speedDecelerationRatio[axis] * s.timeDiff;
					_panOffset[axis] += s.distanceOffset[axis];

				}
			},

			panAnimLoop: function() {
				if ( _animations.zoomPan ) {
					_animations.zoomPan.raf = _requestAF(s.panAnimLoop);

					s.now = _getCurrentTime();
					s.timeDiff = s.now - s.lastNow;
					s.lastNow = s.now;
					
					s.calculateAnimOffset('x');
					s.calculateAnimOffset('y');

					_applyCurrentZoomPan();
					
					s.calculateOverBoundsAnimOffset('x');
					s.calculateOverBoundsAnimOffset('y');


					if (s.speedDecelerationRatioAbs.x < 0.05 && s.speedDecelerationRatioAbs.y < 0.05) {

						// round pan position
						_panOffset.x = Math.round(_panOffset.x);
						_panOffset.y = Math.round(_panOffset.y);
						_applyCurrentZoomPan();
						
						_stopAnimation('zoomPan');
						return;
					}
				}

			}
		};
		return s;
	},

	_completePanGesture = function(animData) {
		// calculate swipe speed for Y axis (paanning)
		animData.calculateSwipeSpeed('y');

		_currPanBounds = self.currItem.bounds;
		
		animData.backAnimDestination = {};
		animData.backAnimStarted = {};

		// Avoid acceleration animation if speed is too low
		if(Math.abs(animData.lastFlickSpeed.x) <= 0.05 && Math.abs(animData.lastFlickSpeed.y) <= 0.05 ) {
			animData.speedDecelerationRatioAbs.x = animData.speedDecelerationRatioAbs.y = 0;

			// Run pan drag release animation. E.g. if you drag image and release finger without momentum.
			animData.calculateOverBoundsAnimOffset('x');
			animData.calculateOverBoundsAnimOffset('y');
			return true;
		}

		// Animation loop that controls the acceleration after pan gesture ends
		_registerStartAnimation('zoomPan');
		animData.lastNow = _getCurrentTime();
		animData.panAnimLoop();
	},


	_finishSwipeMainScrollGesture = function(gestureType, _releaseAnimData) {
		var itemChanged;
		if(!_mainScrollAnimating) {
			_currZoomedItemIndex = _currentItemIndex;
		}


		
		var itemsDiff;

		if(gestureType === 'swipe') {
			var totalShiftDist = _currPoint.x - _startPoint.x,
				isFastLastFlick = _releaseAnimData.lastFlickDist.x < 10;

			// if container is shifted for more than MIN_SWIPE_DISTANCE, 
			// and last flick gesture was in right direction
			if(totalShiftDist > MIN_SWIPE_DISTANCE && 
				(isFastLastFlick || _releaseAnimData.lastFlickOffset.x > 20) ) {
				// go to prev item
				itemsDiff = -1;
			} else if(totalShiftDist < -MIN_SWIPE_DISTANCE && 
				(isFastLastFlick || _releaseAnimData.lastFlickOffset.x < -20) ) {
				// go to next item
				itemsDiff = 1;
			}
		}

		var nextCircle;

		if(itemsDiff) {
			
			_currentItemIndex += itemsDiff;

			if(_currentItemIndex < 0) {
				_currentItemIndex = _options.loop ? _getNumItems()-1 : 0;
				nextCircle = true;
			} else if(_currentItemIndex >= _getNumItems()) {
				_currentItemIndex = _options.loop ? 0 : _getNumItems()-1;
				nextCircle = true;
			}

			if(!nextCircle || _options.loop) {
				_indexDiff += itemsDiff;
				_currPositionIndex -= itemsDiff;
				itemChanged = true;
			}
			

			
		}

		var animateToX = _slideSize.x * _currPositionIndex;
		var animateToDist = Math.abs( animateToX - _mainScrollPos.x );
		var finishAnimDuration;


		if(!itemChanged && animateToX > _mainScrollPos.x !== _releaseAnimData.lastFlickSpeed.x > 0) {
			// "return to current" duration, e.g. when dragging from slide 0 to -1
			finishAnimDuration = 333; 
		} else {
			finishAnimDuration = Math.abs(_releaseAnimData.lastFlickSpeed.x) > 0 ? 
									animateToDist / Math.abs(_releaseAnimData.lastFlickSpeed.x) : 
									333;

			finishAnimDuration = Math.min(finishAnimDuration, 400);
			finishAnimDuration = Math.max(finishAnimDuration, 250);
		}

		if(_currZoomedItemIndex === _currentItemIndex) {
			itemChanged = false;
		}
		
		_mainScrollAnimating = true;
		
		_shout('mainScrollAnimStart');

		_animateProp('mainScroll', _mainScrollPos.x, animateToX, finishAnimDuration, framework.easing.cubic.out, 
			_moveMainScroll,
			function() {
				_stopAllAnimations();
				_mainScrollAnimating = false;
				_currZoomedItemIndex = -1;
				
				if(itemChanged || _currZoomedItemIndex !== _currentItemIndex) {
					self.updateCurrItem();
				}
				
				_shout('mainScrollAnimComplete');
			}
		);

		if(itemChanged) {
			self.updateCurrItem(true);
		}

		return itemChanged;
	},

	_calculateZoomLevel = function(touchesDistance) {
		return  1 / _startPointsDistance * touchesDistance * _startZoomLevel;
	},

	// Resets zoom if it's out of bounds
	_completeZoomGesture = function() {
		var destZoomLevel = _currZoomLevel,
			minZoomLevel = _getMinZoomLevel(),
			maxZoomLevel = _getMaxZoomLevel();

		if ( _currZoomLevel < minZoomLevel ) {
			destZoomLevel = minZoomLevel;
		} else if ( _currZoomLevel > maxZoomLevel ) {
			destZoomLevel = maxZoomLevel;
		}

		var destOpacity = 1,
			onUpdate,
			initialOpacity = _bgOpacity;

		if(_opacityChanged && !_isZoomingIn && !_wasOverInitialZoom && _currZoomLevel < minZoomLevel) {
			//_closedByScroll = true;
			self.close();
			return true;
		}

		if(_opacityChanged) {
			onUpdate = function(now) {
				_applyBgOpacity(  (destOpacity - initialOpacity) * now + initialOpacity );
			};
		}

		self.zoomTo(destZoomLevel, 0, 200,  framework.easing.cubic.out, onUpdate);
		return true;
	};


_registerModule('Gestures', {
	publicMethods: {

		initGestures: function() {

			// helper function that builds touch/pointer/mouse events
			var addEventNames = function(pref, down, move, up, cancel) {
				_dragStartEvent = pref + down;
				_dragMoveEvent = pref + move;
				_dragEndEvent = pref + up;
				if(cancel) {
					_dragCancelEvent = pref + cancel;
				} else {
					_dragCancelEvent = '';
				}
			};

			_pointerEventEnabled = _features.pointerEvent;
			if(_pointerEventEnabled && _features.touch) {
				// we don't need touch events, if browser supports pointer events
				_features.touch = false;
			}

			if(_pointerEventEnabled) {
				if(navigator.pointerEnabled) {
					addEventNames('pointer', 'down', 'move', 'up', 'cancel');
				} else {
					// IE10 pointer events are case-sensitive
					addEventNames('MSPointer', 'Down', 'Move', 'Up', 'Cancel');
				}
			} else if(_features.touch) {
				addEventNames('touch', 'start', 'move', 'end', 'cancel');
				_likelyTouchDevice = true;
			} else {
				addEventNames('mouse', 'down', 'move', 'up');	
			}

			_upMoveEvents = _dragMoveEvent + ' ' + _dragEndEvent  + ' ' +  _dragCancelEvent;
			_downEvents = _dragStartEvent;

			if(_pointerEventEnabled && !_likelyTouchDevice) {
				_likelyTouchDevice = (navigator.maxTouchPoints > 1) || (navigator.msMaxTouchPoints > 1);
			}
			// make variable public
			self.likelyTouchDevice = _likelyTouchDevice; 
			
			_globalEventHandlers[_dragStartEvent] = _onDragStart;
			_globalEventHandlers[_dragMoveEvent] = _onDragMove;
			_globalEventHandlers[_dragEndEvent] = _onDragRelease; // the Kraken

			if(_dragCancelEvent) {
				_globalEventHandlers[_dragCancelEvent] = _globalEventHandlers[_dragEndEvent];
			}

			// Bind mouse events on device with detected hardware touch support, in case it supports multiple types of input.
			if(_features.touch) {
				_downEvents += ' mousedown';
				_upMoveEvents += ' mousemove mouseup';
				_globalEventHandlers.mousedown = _globalEventHandlers[_dragStartEvent];
				_globalEventHandlers.mousemove = _globalEventHandlers[_dragMoveEvent];
				_globalEventHandlers.mouseup = _globalEventHandlers[_dragEndEvent];
			}

			if(!_likelyTouchDevice) {
				// don't allow pan to next slide from zoomed state on Desktop
				_options.allowPanToNext = false;
			}
		}

	}
});


/*>>gestures*/

/*>>show-hide-transition*/
/**
 * show-hide-transition.js:
 *
 * Manages initial opening or closing transition.
 *
 * If you're not planning to use transition for gallery at all,
 * you may set options hideAnimationDuration and showAnimationDuration to 0,
 * and just delete startAnimation function.
 * 
 */


var _showOrHideTimeout,
	_showOrHide = function(item, img, out, completeFn) {

		if(_showOrHideTimeout) {
			clearTimeout(_showOrHideTimeout);
		}

		_initialZoomRunning = true;
		_initialContentSet = true;
		
		// dimensions of small thumbnail {x:,y:,w:}.
		// Height is optional, as calculated based on large image.
		var thumbBounds; 
		if(item.initialLayout) {
			thumbBounds = item.initialLayout;
			item.initialLayout = null;
		} else {
			thumbBounds = _options.getThumbBoundsFn && _options.getThumbBoundsFn(_currentItemIndex);
		}

		var duration = out ? _options.hideAnimationDuration : _options.showAnimationDuration;

		var onComplete = function() {
			_stopAnimation('initialZoom');
			if(!out) {
				_applyBgOpacity(1);
				if(img) {
					img.style.display = 'block';
				}
				framework.addClass(template, 'pswp--animated-in');
				_shout('initialZoom' + (out ? 'OutEnd' : 'InEnd'));
			} else {
				self.template.removeAttribute('style');
				self.bg.removeAttribute('style');
			}

			if(completeFn) {
				completeFn();
			}
			_initialZoomRunning = false;
		};

		// if bounds aren't provided, just open gallery without animation
		if(!duration || !thumbBounds || thumbBounds.x === undefined) {

			_shout('initialZoom' + (out ? 'Out' : 'In') );

			_currZoomLevel = item.initialZoomLevel;
			_equalizePoints(_panOffset,  item.initialPosition );
			_applyCurrentZoomPan();

			template.style.opacity = out ? 0 : 1;
			_applyBgOpacity(1);

			if(duration) {
				setTimeout(function() {
					onComplete();
				}, duration);
			} else {
				onComplete();
			}

			return;
		}

		var startAnimation = function() {
			var closeWithRaf = _closedByScroll,
				fadeEverything = !self.currItem.src || self.currItem.loadError || _options.showHideOpacity;
			
			// apply hw-acceleration to image
			if(item.miniImg) {
				item.miniImg.style.webkitBackfaceVisibility = 'hidden';
			}

			if(!out) {
				_currZoomLevel = thumbBounds.w / item.w;
				_panOffset.x = thumbBounds.x;
				_panOffset.y = thumbBounds.y - _initalWindowScrollY;

				self[fadeEverything ? 'template' : 'bg'].style.opacity = 0.001;
				_applyCurrentZoomPan();
			}

			_registerStartAnimation('initialZoom');
			
			if(out && !closeWithRaf) {
				framework.removeClass(template, 'pswp--animated-in');
			}

			if(fadeEverything) {
				if(out) {
					framework[ (closeWithRaf ? 'remove' : 'add') + 'Class' ](template, 'pswp--animate_opacity');
				} else {
					setTimeout(function() {
						framework.addClass(template, 'pswp--animate_opacity');
					}, 30);
				}
			}

			_showOrHideTimeout = setTimeout(function() {

				_shout('initialZoom' + (out ? 'Out' : 'In') );
				

				if(!out) {

					// "in" animation always uses CSS transitions (instead of rAF).
					// CSS transition work faster here, 
					// as developer may also want to animate other things, 
					// like ui on top of sliding area, which can be animated just via CSS
					
					_currZoomLevel = item.initialZoomLevel;
					_equalizePoints(_panOffset,  item.initialPosition );
					_applyCurrentZoomPan();
					_applyBgOpacity(1);

					if(fadeEverything) {
						template.style.opacity = 1;
					} else {
						_applyBgOpacity(1);
					}

					_showOrHideTimeout = setTimeout(onComplete, duration + 20);
				} else {

					// "out" animation uses rAF only when PhotoSwipe is closed by browser scroll, to recalculate position
					var destZoomLevel = thumbBounds.w / item.w,
						initialPanOffset = {
							x: _panOffset.x,
							y: _panOffset.y
						},
						initialZoomLevel = _currZoomLevel,
						initalBgOpacity = _bgOpacity,
						onUpdate = function(now) {
							
							if(now === 1) {
								_currZoomLevel = destZoomLevel;
								_panOffset.x = thumbBounds.x;
								_panOffset.y = thumbBounds.y  - _currentWindowScrollY;
							} else {
								_currZoomLevel = (destZoomLevel - initialZoomLevel) * now + initialZoomLevel;
								_panOffset.x = (thumbBounds.x - initialPanOffset.x) * now + initialPanOffset.x;
								_panOffset.y = (thumbBounds.y - _currentWindowScrollY - initialPanOffset.y) * now + initialPanOffset.y;
							}
							
							_applyCurrentZoomPan();
							if(fadeEverything) {
								template.style.opacity = 1 - now;
							} else {
								_applyBgOpacity( initalBgOpacity - now * initalBgOpacity );
							}
						};

					if(closeWithRaf) {
						_animateProp('initialZoom', 0, 1, duration, framework.easing.cubic.out, onUpdate, onComplete);
					} else {
						onUpdate(1);
						_showOrHideTimeout = setTimeout(onComplete, duration + 20);
					}
				}
			
			}, out ? 25 : 90); // Main purpose of this delay is to give browser time to paint and
					// create composite layers of PhotoSwipe UI parts (background, controls, caption, arrows).
					// Which avoids lag at the beginning of scale transition.
		};
		startAnimation();

		
	};

/*>>show-hide-transition*/

/*>>items-controller*/
/**
*
* Controller manages gallery items, their dimensions, and their content.
* 
*/

var _items,
	_tempPanAreaSize = {},
	_imagesToAppendPool = [],
	_initialContentSet,
	_initialZoomRunning,
	_controllerDefaultOptions = {
		index: 0,
		errorMsg: '<div class="pswp__error-msg"><a href="%url%" target="_blank">The image</a> could not be loaded.</div>',
		forceProgressiveLoading: false, // TODO
		preload: [1,1],
		getNumItemsFn: function() {
			return _items.length;
		}
	};


var _getItemAt,
	_getNumItems,
	_initialIsLoop,
	_getZeroBounds = function() {
		return {
			center:{x:0,y:0}, 
			max:{x:0,y:0}, 
			min:{x:0,y:0}
		};
	},
	_calculateSingleItemPanBounds = function(item, realPanElementW, realPanElementH ) {
		var bounds = item.bounds;

		// position of element when it's centered
		bounds.center.x = Math.round((_tempPanAreaSize.x - realPanElementW) / 2);
		bounds.center.y = Math.round((_tempPanAreaSize.y - realPanElementH) / 2) + item.vGap.top;

		// maximum pan position
		bounds.max.x = (realPanElementW > _tempPanAreaSize.x) ? 
							Math.round(_tempPanAreaSize.x - realPanElementW) : 
							bounds.center.x;
		
		bounds.max.y = (realPanElementH > _tempPanAreaSize.y) ? 
							Math.round(_tempPanAreaSize.y - realPanElementH) + item.vGap.top : 
							bounds.center.y;
		
		// minimum pan position
		bounds.min.x = (realPanElementW > _tempPanAreaSize.x) ? 0 : bounds.center.x;
		bounds.min.y = (realPanElementH > _tempPanAreaSize.y) ? item.vGap.top : bounds.center.y;
	},
	_calculateItemSize = function(item, viewportSize, zoomLevel) {

		if (item.src && !item.loadError) {
			var isInitial = !zoomLevel;
			
			if(isInitial) {
				if(!item.vGap) {
					item.vGap = {top:0,bottom:0};
				}
				// allows overriding vertical margin for individual items
				_shout('parseVerticalMargin', item);
			}


			_tempPanAreaSize.x = viewportSize.x;
			_tempPanAreaSize.y = viewportSize.y - item.vGap.top - item.vGap.bottom;

			if (isInitial) {
				var hRatio = _tempPanAreaSize.x / item.w;
				var vRatio = _tempPanAreaSize.y / item.h;

				item.fitRatio = hRatio < vRatio ? hRatio : vRatio;
				//item.fillRatio = hRatio > vRatio ? hRatio : vRatio;

				var scaleMode = _options.scaleMode;

				if (scaleMode === 'orig') {
					zoomLevel = 1;
				} else if (scaleMode === 'fit') {
					zoomLevel = item.fitRatio;
				}

				if (zoomLevel > 1) {
					zoomLevel = 1;
				}

				item.initialZoomLevel = zoomLevel;
				
				if(!item.bounds) {
					// reuse bounds object
					item.bounds = _getZeroBounds(); 
				}
			}

			if(!zoomLevel) {
				return;
			}

			_calculateSingleItemPanBounds(item, item.w * zoomLevel, item.h * zoomLevel);

			if (isInitial && zoomLevel === item.initialZoomLevel) {
				item.initialPosition = item.bounds.center;
			}

			return item.bounds;
		} else {
			item.w = item.h = 0;
			item.initialZoomLevel = item.fitRatio = 1;
			item.bounds = _getZeroBounds();
			item.initialPosition = item.bounds.center;

			// if it's not image, we return zero bounds (content is not zoomable)
			return item.bounds;
		}
		
	},

	


	_appendImage = function(index, item, baseDiv, img, preventAnimation, keepPlaceholder) {
		

		if(item.loadError) {
			return;
		}

		if(img) {

			item.imageAppended = true;
			_setImageSize(item, img, (item === self.currItem && _renderMaxResolution) );
			
			baseDiv.appendChild(img);

			if(keepPlaceholder) {
				setTimeout(function() {
					if(item && item.loaded && item.placeholder) {
						item.placeholder.style.display = 'none';
						item.placeholder = null;
					}
				}, 500);
			}
		}
	},
	


	_preloadImage = function(item) {
		item.loading = true;
		item.loaded = false;
		var img = item.img = framework.createEl('pswp__img', 'img');
		var onComplete = function() {
			item.loading = false;
			item.loaded = true;

			if(item.loadComplete) {
				item.loadComplete(item);
			} else {
				item.img = null; // no need to store image object
			}
			img.onload = img.onerror = null;
			img = null;
		};
		img.onload = onComplete;
		img.onerror = function() {
			item.loadError = true;
			onComplete();
		};		

		img.src = item.src;// + '?a=' + Math.random();

		return img;
	},
	_checkForError = function(item, cleanUp) {
		if(item.src && item.loadError && item.container) {

			if(cleanUp) {
				item.container.innerHTML = '';
			}

			item.container.innerHTML = _options.errorMsg.replace('%url%',  item.src );
			return true;
			
		}
	},
	_setImageSize = function(item, img, maxRes) {
		if(!item.src) {
			return;
		}

		if(!img) {
			img = item.container.lastChild;
		}

		var w = maxRes ? item.w : Math.round(item.w * item.fitRatio),
			h = maxRes ? item.h : Math.round(item.h * item.fitRatio);
		
		if(item.placeholder && !item.loaded) {
			item.placeholder.style.width = w + 'px';
			item.placeholder.style.height = h + 'px';
		}

		img.style.width = w + 'px';
		img.style.height = h + 'px';
	},
	_appendImagesPool = function() {

		if(_imagesToAppendPool.length) {
			var poolItem;

			for(var i = 0; i < _imagesToAppendPool.length; i++) {
				poolItem = _imagesToAppendPool[i];
				if( poolItem.holder.index === poolItem.index ) {
					_appendImage(poolItem.index, poolItem.item, poolItem.baseDiv, poolItem.img, false, poolItem.clearPlaceholder);
				}
			}
			_imagesToAppendPool = [];
		}
	};
	


_registerModule('Controller', {

	publicMethods: {

		lazyLoadItem: function(index) {
			index = _getLoopedId(index);
			var item = _getItemAt(index);

			if(!item || ((item.loaded || item.loading) && !_itemsNeedUpdate)) {
				return;
			}

			_shout('gettingData', index, item);

			if (!item.src) {
				return;
			}

			_preloadImage(item);
		},
		initController: function() {
			framework.extend(_options, _controllerDefaultOptions, true);
			self.items = _items = items;
			_getItemAt = self.getItemAt;
			_getNumItems = _options.getNumItemsFn; //self.getNumItems;



			_initialIsLoop = _options.loop;
			if(_getNumItems() < 3) {
				_options.loop = false; // disable loop if less then 3 items
			}

			_listen('beforeChange', function(diff) {

				var p = _options.preload,
					isNext = diff === null ? true : (diff >= 0),
					preloadBefore = Math.min(p[0], _getNumItems() ),
					preloadAfter = Math.min(p[1], _getNumItems() ),
					i;


				for(i = 1; i <= (isNext ? preloadAfter : preloadBefore); i++) {
					self.lazyLoadItem(_currentItemIndex+i);
				}
				for(i = 1; i <= (isNext ? preloadBefore : preloadAfter); i++) {
					self.lazyLoadItem(_currentItemIndex-i);
				}
			});

			_listen('initialLayout', function() {
				self.currItem.initialLayout = _options.getThumbBoundsFn && _options.getThumbBoundsFn(_currentItemIndex);
			});

			_listen('mainScrollAnimComplete', _appendImagesPool);
			_listen('initialZoomInEnd', _appendImagesPool);



			_listen('destroy', function() {
				var item;
				for(var i = 0; i < _items.length; i++) {
					item = _items[i];
					// remove reference to DOM elements, for GC
					if(item.container) {
						item.container = null; 
					}
					if(item.placeholder) {
						item.placeholder = null;
					}
					if(item.img) {
						item.img = null;
					}
					if(item.preloader) {
						item.preloader = null;
					}
					if(item.loadError) {
						item.loaded = item.loadError = false;
					}
				}
				_imagesToAppendPool = null;
			});
		},


		getItemAt: function(index) {
			if (index >= 0) {
				return _items[index] !== undefined ? _items[index] : false;
			}
			return false;
		},

		allowProgressiveImg: function() {
			// 1. Progressive image loading isn't working on webkit/blink 
			//    when hw-acceleration (e.g. translateZ) is applied to IMG element.
			//    That's why in PhotoSwipe parent element gets zoom transform, not image itself.
			//    
			// 2. Progressive image loading sometimes blinks in webkit/blink when applying animation to parent element.
			//    That's why it's disabled on touch devices (mainly because of swipe transition)
			//    
			// 3. Progressive image loading sometimes doesn't work in IE (up to 11).

			// Don't allow progressive loading on non-large touch devices
			return _options.forceProgressiveLoading || !_likelyTouchDevice || _options.mouseUsed || screen.width > 1200; 
			// 1200 - to eliminate touch devices with large screen (like Chromebook Pixel)
		},

		setContent: function(holder, index) {

			if(_options.loop) {
				index = _getLoopedId(index);
			}

			var prevItem = self.getItemAt(holder.index);
			if(prevItem) {
				prevItem.container = null;
			}
	
			var item = self.getItemAt(index),
				img;
			
			if(!item) {
				holder.el.innerHTML = '';
				return;
			}

			// allow to override data
			_shout('gettingData', index, item);

			holder.index = index;
			holder.item = item;

			// base container DIV is created only once for each of 3 holders
			var baseDiv = item.container = framework.createEl('pswp__zoom-wrap'); 

			

			if(!item.src && item.html) {
				if(item.html.tagName) {
					baseDiv.appendChild(item.html);
				} else {
					baseDiv.innerHTML = item.html;
				}
			}

			_checkForError(item);

			_calculateItemSize(item, _viewportSize);
			
			if(item.src && !item.loadError && !item.loaded) {

				item.loadComplete = function(item) {

					// gallery closed before image finished loading
					if(!_isOpen) {
						return;
					}

					// check if holder hasn't changed while image was loading
					if(holder && holder.index === index ) {
						if( _checkForError(item, true) ) {
							item.loadComplete = item.img = null;
							_calculateItemSize(item, _viewportSize);
							_applyZoomPanToItem(item);

							if(holder.index === _currentItemIndex) {
								// recalculate dimensions
								self.updateCurrZoomItem();
							}
							return;
						}
						if( !item.imageAppended ) {
							if(_features.transform && (_mainScrollAnimating || _initialZoomRunning) ) {
								_imagesToAppendPool.push({
									item:item,
									baseDiv:baseDiv,
									img:item.img,
									index:index,
									holder:holder,
									clearPlaceholder:true
								});
							} else {
								_appendImage(index, item, baseDiv, item.img, _mainScrollAnimating || _initialZoomRunning, true);
							}
						} else {
							// remove preloader & mini-img
							if(!_initialZoomRunning && item.placeholder) {
								item.placeholder.style.display = 'none';
								item.placeholder = null;
							}
						}
					}

					item.loadComplete = null;
					item.img = null; // no need to store image element after it's added

					_shout('imageLoadComplete', index, item);
				};

				if(framework.features.transform) {
					
					var placeholderClassName = 'pswp__img pswp__img--placeholder'; 
					placeholderClassName += (item.msrc ? '' : ' pswp__img--placeholder--blank');

					var placeholder = framework.createEl(placeholderClassName, item.msrc ? 'img' : '');
					if(item.msrc) {
						placeholder.src = item.msrc;
					}
					
					_setImageSize(item, placeholder);

					baseDiv.appendChild(placeholder);
					item.placeholder = placeholder;

				}
				

				

				if(!item.loading) {
					_preloadImage(item);
				}


				if( self.allowProgressiveImg() ) {
					// just append image
					if(!_initialContentSet && _features.transform) {
						_imagesToAppendPool.push({
							item:item, 
							baseDiv:baseDiv, 
							img:item.img, 
							index:index, 
							holder:holder
						});
					} else {
						_appendImage(index, item, baseDiv, item.img, true, true);
					}
				}
				
			} else if(item.src && !item.loadError) {
				// image object is created every time, due to bugs of image loading & delay when switching images
				img = framework.createEl('pswp__img', 'img');
				img.style.opacity = 1;
				img.src = item.src;
				_setImageSize(item, img);
				_appendImage(index, item, baseDiv, img, true);
			}
			

			if(!_initialContentSet && index === _currentItemIndex) {
				_currZoomElementStyle = baseDiv.style;
				_showOrHide(item, (img ||item.img) );
			} else {
				_applyZoomPanToItem(item);
			}

			holder.el.innerHTML = '';
			holder.el.appendChild(baseDiv);
		},

		cleanSlide: function( item ) {
			if(item.img ) {
				item.img.onload = item.img.onerror = null;
			}
			item.loaded = item.loading = item.img = item.imageAppended = false;
		}

	}
});

/*>>items-controller*/

/*>>tap*/
/**
 * tap.js:
 *
 * Displatches tap and double-tap events.
 * 
 */

var tapTimer,
	tapReleasePoint = {},
	_dispatchTapEvent = function(origEvent, releasePoint, pointerType) {		
		var e = document.createEvent( 'CustomEvent' ),
			eDetail = {
				origEvent:origEvent, 
				target:origEvent.target, 
				releasePoint: releasePoint, 
				pointerType:pointerType || 'touch'
			};

		e.initCustomEvent( 'pswpTap', true, true, eDetail );
		origEvent.target.dispatchEvent(e);
	};

_registerModule('Tap', {
	publicMethods: {
		initTap: function() {
			_listen('firstTouchStart', self.onTapStart);
			_listen('touchRelease', self.onTapRelease);
			_listen('destroy', function() {
				tapReleasePoint = {};
				tapTimer = null;
			});
		},
		onTapStart: function(touchList) {
			if(touchList.length > 1) {
				clearTimeout(tapTimer);
				tapTimer = null;
			}
		},
		onTapRelease: function(e, releasePoint) {
			if(!releasePoint) {
				return;
			}

			if(!_moved && !_isMultitouch && !_numAnimations) {
				var p0 = releasePoint;
				if(tapTimer) {
					clearTimeout(tapTimer);
					tapTimer = null;

					// Check if taped on the same place
					if ( _isNearbyPoints(p0, tapReleasePoint) ) {
						_shout('doubleTap', p0);
						return;
					}
				}

				if(releasePoint.type === 'mouse') {
					_dispatchTapEvent(e, releasePoint, 'mouse');
					return;
				}

				var clickedTagName = e.target.tagName.toUpperCase();
				// avoid double tap delay on buttons and elements that have class pswp__single-tap
				if(clickedTagName === 'BUTTON' || framework.hasClass(e.target, 'pswp__single-tap') ) {
					_dispatchTapEvent(e, releasePoint);
					return;
				}

				_equalizePoints(tapReleasePoint, p0);

				tapTimer = setTimeout(function() {
					_dispatchTapEvent(e, releasePoint);
					tapTimer = null;
				}, 300);
			}
		}
	}
});

/*>>tap*/

/*>>desktop-zoom*/
/**
 *
 * desktop-zoom.js:
 *
 * - Binds mousewheel event for paning zoomed image.
 * - Manages "dragging", "zoomed-in", "zoom-out" classes.
 *   (which are used for cursors and zoom icon)
 * - Adds toggleDesktopZoom function.
 * 
 */

var _wheelDelta;
	
_registerModule('DesktopZoom', {

	publicMethods: {

		initDesktopZoom: function() {

			if(_oldIE) {
				// no zoom for old IE (<=8)
				return;
			}

			if(_likelyTouchDevice) {
				// if detected hardware touch support, we wait until mouse is used,
				// and only then apply desktop-zoom features
				_listen('mouseUsed', function() {
					self.setupDesktopZoom();
				});
			} else {
				self.setupDesktopZoom(true);
			}

		},

		setupDesktopZoom: function(onInit) {

			_wheelDelta = {};

			var events = 'wheel mousewheel DOMMouseScroll';
			
			_listen('bindEvents', function() {
				framework.bind(template, events,  self.handleMouseWheel);
			});

			_listen('unbindEvents', function() {
				if(_wheelDelta) {
					framework.unbind(template, events, self.handleMouseWheel);
				}
			});

			self.mouseZoomedIn = false;

			var hasDraggingClass,
				updateZoomable = function() {
					if(self.mouseZoomedIn) {
						framework.removeClass(template, 'pswp--zoomed-in');
						self.mouseZoomedIn = false;
					}
					if(_currZoomLevel < 1) {
						framework.addClass(template, 'pswp--zoom-allowed');
					} else {
						framework.removeClass(template, 'pswp--zoom-allowed');
					}
					removeDraggingClass();
				},
				removeDraggingClass = function() {
					if(hasDraggingClass) {
						framework.removeClass(template, 'pswp--dragging');
						hasDraggingClass = false;
					}
				};

			_listen('resize' , updateZoomable);
			_listen('afterChange' , updateZoomable);
			_listen('pointerDown', function() {
				if(self.mouseZoomedIn) {
					hasDraggingClass = true;
					framework.addClass(template, 'pswp--dragging');
				}
			});
			_listen('pointerUp', removeDraggingClass);

			if(!onInit) {
				updateZoomable();
			}
			
		},

		handleMouseWheel: function(e) {

			if(_currZoomLevel <= self.currItem.fitRatio) {
				if( _options.modal ) {

					if (!_options.closeOnScroll || _numAnimations || _isDragging) {
						e.preventDefault();
					} else if(_transformKey && Math.abs(e.deltaY) > 2) {
						// close PhotoSwipe
						// if browser supports transforms & scroll changed enough
						_closedByScroll = true;
						self.close();
					}

				}
				return true;
			}

			// allow just one event to fire
			e.stopPropagation();

			// https://developer.mozilla.org/en-US/docs/Web/Events/wheel
			_wheelDelta.x = 0;

			if('deltaX' in e) {
				if(e.deltaMode === 1 /* DOM_DELTA_LINE */) {
					// 18 - average line height
					_wheelDelta.x = e.deltaX * 18;
					_wheelDelta.y = e.deltaY * 18;
				} else {
					_wheelDelta.x = e.deltaX;
					_wheelDelta.y = e.deltaY;
				}
			} else if('wheelDelta' in e) {
				if(e.wheelDeltaX) {
					_wheelDelta.x = -0.16 * e.wheelDeltaX;
				}
				if(e.wheelDeltaY) {
					_wheelDelta.y = -0.16 * e.wheelDeltaY;
				} else {
					_wheelDelta.y = -0.16 * e.wheelDelta;
				}
			} else if('detail' in e) {
				_wheelDelta.y = e.detail;
			} else {
				return;
			}

			_calculatePanBounds(_currZoomLevel, true);

			var newPanX = _panOffset.x - _wheelDelta.x,
				newPanY = _panOffset.y - _wheelDelta.y;

			// only prevent scrolling in nonmodal mode when not at edges
			if (_options.modal ||
				(
				newPanX <= _currPanBounds.min.x && newPanX >= _currPanBounds.max.x &&
				newPanY <= _currPanBounds.min.y && newPanY >= _currPanBounds.max.y
				) ) {
				e.preventDefault();
			}

			// TODO: use rAF instead of mousewheel?
			self.panTo(newPanX, newPanY);
		},

		toggleDesktopZoom: function(centerPoint) {
			centerPoint = centerPoint || {x:_viewportSize.x/2 + _offset.x, y:_viewportSize.y/2 + _offset.y };

			var doubleTapZoomLevel = _options.getDoubleTapZoom(true, self.currItem);
			var zoomOut = _currZoomLevel === doubleTapZoomLevel;
			
			self.mouseZoomedIn = !zoomOut;

			self.zoomTo(zoomOut ? self.currItem.initialZoomLevel : doubleTapZoomLevel, centerPoint, 333);
			framework[ (!zoomOut ? 'add' : 'remove') + 'Class'](template, 'pswp--zoomed-in');
		}

	}
});


/*>>desktop-zoom*/

/*>>history*/
/**
 *
 * history.js:
 *
 * - Back button to close gallery.
 * 
 * - Unique URL for each slide: example.com/&pid=1&gid=3
 *   (where PID is picture index, and GID and gallery index)
 *   
 * - Switch URL when slides change.
 * 
 */


var _historyDefaultOptions = {
	history: true,
	galleryUID: 1
};

var _historyUpdateTimeout,
	_hashChangeTimeout,
	_hashAnimCheckTimeout,
	_hashChangedByScript,
	_hashChangedByHistory,
	_hashReseted,
	_initialHash,
	_historyChanged,
	_closedFromURL,
	_urlChangedOnce,
	_windowLoc,

	_supportsPushState,

	_getHash = function() {
		return _windowLoc.hash.substring(1);
	},
	_cleanHistoryTimeouts = function() {

		if(_historyUpdateTimeout) {
			clearTimeout(_historyUpdateTimeout);
		}

		if(_hashAnimCheckTimeout) {
			clearTimeout(_hashAnimCheckTimeout);
		}
	},

	// pid - Picture index
	// gid - Gallery index
	_parseItemIndexFromURL = function() {
		var hash = _getHash(),
			params = {};

		if(hash.length < 5) { // pid=1
			return params;
		}

		var i, vars = hash.split('&');
		for (i = 0; i < vars.length; i++) {
			if(!vars[i]) {
				continue;
			}
			var pair = vars[i].split('=');	
			if(pair.length < 2) {
				continue;
			}
			params[pair[0]] = pair[1];
		}
		if(_options.galleryPIDs) {
			// detect custom pid in hash and search for it among the items collection
			var searchfor = params.pid;
			params.pid = 0; // if custom pid cannot be found, fallback to the first item
			for(i = 0; i < _items.length; i++) {
				if(_items[i].pid === searchfor) {
					params.pid = i;
					break;
				}
			}
		} else {
			params.pid = parseInt(params.pid,10)-1;
		}
		if( params.pid < 0 ) {
			params.pid = 0;
		}
		return params;
	},
	_updateHash = function() {

		if(_hashAnimCheckTimeout) {
			clearTimeout(_hashAnimCheckTimeout);
		}


		if(_numAnimations || _isDragging) {
			// changing browser URL forces layout/paint in some browsers, which causes noticable lag during animation
			// that's why we update hash only when no animations running
			_hashAnimCheckTimeout = setTimeout(_updateHash, 500);
			return;
		}
		
		if(_hashChangedByScript) {
			clearTimeout(_hashChangeTimeout);
		} else {
			_hashChangedByScript = true;
		}


		var pid = (_currentItemIndex + 1);
		var item = _getItemAt( _currentItemIndex );
		if(item.hasOwnProperty('pid')) {
			// carry forward any custom pid assigned to the item
			pid = item.pid;
		}
		var newHash = _initialHash + '&'  +  'gid=' + _options.galleryUID + '&' + 'pid=' + pid;

		if(!_historyChanged) {
			if(_windowLoc.hash.indexOf(newHash) === -1) {
				_urlChangedOnce = true;
			}
			// first time - add new hisory record, then just replace
		}

		var newURL = _windowLoc.href.split('#')[0] + '#' +  newHash;

		if( _supportsPushState ) {

			if('#' + newHash !== window.location.hash) {
				history[_historyChanged ? 'replaceState' : 'pushState']('', document.title, newURL);
			}

		} else {
			if(_historyChanged) {
				_windowLoc.replace( newURL );
			} else {
				_windowLoc.hash = newHash;
			}
		}
		
		

		_historyChanged = true;
		_hashChangeTimeout = setTimeout(function() {
			_hashChangedByScript = false;
		}, 60);
	};



	

_registerModule('History', {

	

	publicMethods: {
		initHistory: function() {

			framework.extend(_options, _historyDefaultOptions, true);

			if( !_options.history ) {
				return;
			}


			_windowLoc = window.location;
			_urlChangedOnce = false;
			_closedFromURL = false;
			_historyChanged = false;
			_initialHash = _getHash();
			_supportsPushState = ('pushState' in history);


			if(_initialHash.indexOf('gid=') > -1) {
				_initialHash = _initialHash.split('&gid=')[0];
				_initialHash = _initialHash.split('?gid=')[0];
			}
			

			_listen('afterChange', self.updateURL);
			_listen('unbindEvents', function() {
				framework.unbind(window, 'hashchange', self.onHashChange);
			});


			var returnToOriginal = function() {
				_hashReseted = true;
				if(!_closedFromURL) {

					if(_urlChangedOnce) {
						history.back();
					} else {

						if(_initialHash) {
							_windowLoc.hash = _initialHash;
						} else {
							if (_supportsPushState) {

								// remove hash from url without refreshing it or scrolling to top
								history.pushState('', document.title,  _windowLoc.pathname + _windowLoc.search );
							} else {
								_windowLoc.hash = '';
							}
						}
					}
					
				}

				_cleanHistoryTimeouts();
			};


			_listen('unbindEvents', function() {
				if(_closedByScroll) {
					// if PhotoSwipe is closed by scroll, we go "back" before the closing animation starts
					// this is done to keep the scroll position
					returnToOriginal();
				}
			});
			_listen('destroy', function() {
				if(!_hashReseted) {
					returnToOriginal();
				}
			});
			_listen('firstUpdate', function() {
				_currentItemIndex = _parseItemIndexFromURL().pid;
			});

			

			
			var index = _initialHash.indexOf('pid=');
			if(index > -1) {
				_initialHash = _initialHash.substring(0, index);
				if(_initialHash.slice(-1) === '&') {
					_initialHash = _initialHash.slice(0, -1);
				}
			}
			

			setTimeout(function() {
				if(_isOpen) { // hasn't destroyed yet
					framework.bind(window, 'hashchange', self.onHashChange);
				}
			}, 40);
			
		},
		onHashChange: function() {

			if(_getHash() === _initialHash) {

				_closedFromURL = true;
				self.close();
				return;
			}
			if(!_hashChangedByScript) {

				_hashChangedByHistory = true;
				self.goTo( _parseItemIndexFromURL().pid );
				_hashChangedByHistory = false;
			}
			
		},
		updateURL: function() {

			// Delay the update of URL, to avoid lag during transition, 
			// and to not to trigger actions like "refresh page sound" or "blinking favicon" to often
			
			_cleanHistoryTimeouts();
			

			if(_hashChangedByHistory) {
				return;
			}

			if(!_historyChanged) {
				_updateHash(); // first time
			} else {
				_historyUpdateTimeout = setTimeout(_updateHash, 800);
			}
		}
	
	}
});


/*>>history*/
	framework.extend(self, publicMethods); };
	return PhotoSwipe;
});


/*! 
 * 
 * ================== js/libs/plugins/photoswipe-ui-default.js =================== 
 **/ 

/*! PhotoSwipe Default UI - 4.1.1 - 2015-12-24
* http://photoswipe.com
* Copyright (c) 2015 Dmitry Semenov; */
/**
*
* UI on top of main sliding area (caption, arrows, close button, etc.).
* Built just using public methods/properties of PhotoSwipe.
* 
*/
(function (root, factory) { 
	if (typeof define === 'function' && define.amd) {
		define(factory);
	} else if (typeof exports === 'object') {
		module.exports = factory();
	} else {
		root.PhotoSwipeUI_Default = factory();
	}
})(this, function () {

	'use strict';



var PhotoSwipeUI_Default =
 function(pswp, framework) {

	var ui = this;
	var _overlayUIUpdated = false,
		_controlsVisible = true,
		_fullscrenAPI,
		_controls,
		_captionContainer,
		_fakeCaptionContainer,
		_indexIndicator,
		_shareButton,
		_shareModal,
		_shareModalHidden = true,
		_initalCloseOnScrollValue,
		_isIdle,
		_listen,

		_loadingIndicator,
		_loadingIndicatorHidden,
		_loadingIndicatorTimeout,

		_galleryHasOneSlide,

		_options,
		_defaultUIOptions = {
			barsSize: {top:44, bottom:'auto'},
			closeElClasses: ['item', 'caption', 'zoom-wrap', 'ui', 'top-bar'], 
			timeToIdle: 4000, 
			timeToIdleOutside: 1000,
			loadingIndicatorDelay: 1000, // 2s
			
			addCaptionHTMLFn: function(item, captionEl /*, isFake */) {
				if(!item.title) {
					captionEl.children[0].innerHTML = '';
					return false;
				}
				captionEl.children[0].innerHTML = item.title;
				return true;
			},

			closeEl:true,
			captionEl: true,
			fullscreenEl: true,
			zoomEl: true,
			shareEl: true,
			counterEl: true,
			arrowEl: true,
			preloaderEl: true,

			tapToClose: false,
			tapToToggleControls: true,

			clickToCloseNonZoomable: true,

			shareButtons: [
				{id:'facebook', label:'Share on Facebook', url:'https://www.facebook.com/sharer/sharer.php?u={{url}}'},
				{id:'twitter', label:'Tweet', url:'https://twitter.com/intent/tweet?text={{text}}&url={{url}}'},
				{id:'pinterest', label:'Pin it', url:'http://www.pinterest.com/pin/create/button/'+
													'?url={{url}}&media={{image_url}}&description={{text}}'},
				{id:'download', label:'Download image', url:'{{raw_image_url}}', download:true}
			],
			getImageURLForShare: function( /* shareButtonData */ ) {
				return pswp.currItem.src || '';
			},
			getPageURLForShare: function( /* shareButtonData */ ) {
				return window.location.href;
			},
			getTextForShare: function( /* shareButtonData */ ) {
				return pswp.currItem.title || '';
			},
				
			indexIndicatorSep: ' / ',
			fitControlsWidth: 1200

		},
		_blockControlsTap,
		_blockControlsTapTimeout;



	var _onControlsTap = function(e) {
			if(_blockControlsTap) {
				return true;
			}


			e = e || window.event;

			if(_options.timeToIdle && _options.mouseUsed && !_isIdle) {
				// reset idle timer
				_onIdleMouseMove();
			}


			var target = e.target || e.srcElement,
				uiElement,
				clickedClass = target.getAttribute('class') || '',
				found;

			for(var i = 0; i < _uiElements.length; i++) {
				uiElement = _uiElements[i];
				if(uiElement.onTap && clickedClass.indexOf('pswp__' + uiElement.name ) > -1 ) {
					uiElement.onTap();
					found = true;

				}
			}

			if(found) {
				if(e.stopPropagation) {
					e.stopPropagation();
				}
				_blockControlsTap = true;

				// Some versions of Android don't prevent ghost click event 
				// when preventDefault() was called on touchstart and/or touchend.
				// 
				// This happens on v4.3, 4.2, 4.1, 
				// older versions strangely work correctly, 
				// but just in case we add delay on all of them)	
				var tapDelay = framework.features.isOldAndroid ? 600 : 30;
				_blockControlsTapTimeout = setTimeout(function() {
					_blockControlsTap = false;
				}, tapDelay);
			}

		},
		_fitControlsInViewport = function() {
			return !pswp.likelyTouchDevice || _options.mouseUsed || screen.width > _options.fitControlsWidth;
		},
		_togglePswpClass = function(el, cName, add) {
			framework[ (add ? 'add' : 'remove') + 'Class' ](el, 'pswp__' + cName);
		},

		// add class when there is just one item in the gallery
		// (by default it hides left/right arrows and 1ofX counter)
		_countNumItems = function() {
			var hasOneSlide = (_options.getNumItemsFn() === 1);

			if(hasOneSlide !== _galleryHasOneSlide) {
				_togglePswpClass(_controls, 'ui--one-slide', hasOneSlide);
				_galleryHasOneSlide = hasOneSlide;
			}
		},
		_toggleShareModalClass = function() {
			_togglePswpClass(_shareModal, 'share-modal--hidden', _shareModalHidden);
		},
		_toggleShareModal = function() {

			_shareModalHidden = !_shareModalHidden;
			
			
			if(!_shareModalHidden) {
				_toggleShareModalClass();
				setTimeout(function() {
					if(!_shareModalHidden) {
						framework.addClass(_shareModal, 'pswp__share-modal--fade-in');
					}
				}, 30);
			} else {
				framework.removeClass(_shareModal, 'pswp__share-modal--fade-in');
				setTimeout(function() {
					if(_shareModalHidden) {
						_toggleShareModalClass();
					}
				}, 300);
			}
			
			if(!_shareModalHidden) {
				_updateShareURLs();
			}
			return false;
		},

		_openWindowPopup = function(e) {
			e = e || window.event;
			var target = e.target || e.srcElement;

			pswp.shout('shareLinkClick', e, target);

			if(!target.href) {
				return false;
			}

			if( target.hasAttribute('download') ) {
				return true;
			}

			window.open(target.href, 'pswp_share', 'scrollbars=yes,resizable=yes,toolbar=no,'+
										'location=yes,width=550,height=420,top=100,left=' + 
										(window.screen ? Math.round(screen.width / 2 - 275) : 100)  );

			if(!_shareModalHidden) {
				_toggleShareModal();
			}
			
			return false;
		},
		_updateShareURLs = function() {
			var shareButtonOut = '',
				shareButtonData,
				shareURL,
				image_url,
				page_url,
				share_text;

			for(var i = 0; i < _options.shareButtons.length; i++) {
				shareButtonData = _options.shareButtons[i];

				image_url = _options.getImageURLForShare(shareButtonData);
				page_url = _options.getPageURLForShare(shareButtonData);
				share_text = _options.getTextForShare(shareButtonData);

				shareURL = shareButtonData.url.replace('{{url}}', encodeURIComponent(page_url) )
									.replace('{{image_url}}', encodeURIComponent(image_url) )
									.replace('{{raw_image_url}}', image_url )
									.replace('{{text}}', encodeURIComponent(share_text) );

				shareButtonOut += '<a href="' + shareURL + '" target="_blank" '+
									'class="pswp__share--' + shareButtonData.id + '"' +
									(shareButtonData.download ? 'download' : '') + '>' + 
									shareButtonData.label + '</a>';

				if(_options.parseShareButtonOut) {
					shareButtonOut = _options.parseShareButtonOut(shareButtonData, shareButtonOut);
				}
			}
			_shareModal.children[0].innerHTML = shareButtonOut;
			_shareModal.children[0].onclick = _openWindowPopup;

		},
		_hasCloseClass = function(target) {
			for(var  i = 0; i < _options.closeElClasses.length; i++) {
				if( framework.hasClass(target, 'pswp__' + _options.closeElClasses[i]) ) {
					return true;
				}
			}
		},
		_idleInterval,
		_idleTimer,
		_idleIncrement = 0,
		_onIdleMouseMove = function() {
			clearTimeout(_idleTimer);
			_idleIncrement = 0;
			if(_isIdle) {
				ui.setIdle(false);
			}
		},
		_onMouseLeaveWindow = function(e) {
			e = e ? e : window.event;
			var from = e.relatedTarget || e.toElement;
			if (!from || from.nodeName === 'HTML') {
				clearTimeout(_idleTimer);
				_idleTimer = setTimeout(function() {
					ui.setIdle(true);
				}, _options.timeToIdleOutside);
			}
		},
		_setupFullscreenAPI = function() {
			if(_options.fullscreenEl && !framework.features.isOldAndroid) {
				if(!_fullscrenAPI) {
					_fullscrenAPI = ui.getFullscreenAPI();
				}
				if(_fullscrenAPI) {
					framework.bind(document, _fullscrenAPI.eventK, ui.updateFullscreen);
					ui.updateFullscreen();
					framework.addClass(pswp.template, 'pswp--supports-fs');
				} else {
					framework.removeClass(pswp.template, 'pswp--supports-fs');
				}
			}
		},
		_setupLoadingIndicator = function() {
			// Setup loading indicator
			if(_options.preloaderEl) {
			
				_toggleLoadingIndicator(true);

				_listen('beforeChange', function() {

					clearTimeout(_loadingIndicatorTimeout);

					// display loading indicator with delay
					_loadingIndicatorTimeout = setTimeout(function() {

						if(pswp.currItem && pswp.currItem.loading) {

							if( !pswp.allowProgressiveImg() || (pswp.currItem.img && !pswp.currItem.img.naturalWidth)  ) {
								// show preloader if progressive loading is not enabled, 
								// or image width is not defined yet (because of slow connection)
								_toggleLoadingIndicator(false); 
								// items-controller.js function allowProgressiveImg
							}
							
						} else {
							_toggleLoadingIndicator(true); // hide preloader
						}

					}, _options.loadingIndicatorDelay);
					
				});
				_listen('imageLoadComplete', function(index, item) {
					if(pswp.currItem === item) {
						_toggleLoadingIndicator(true);
					}
				});

			}
		},
		_toggleLoadingIndicator = function(hide) {
			if( _loadingIndicatorHidden !== hide ) {
				_togglePswpClass(_loadingIndicator, 'preloader--active', !hide);
				_loadingIndicatorHidden = hide;
			}
		},
		_applyNavBarGaps = function(item) {
			var gap = item.vGap;

			if( _fitControlsInViewport() ) {
				
				var bars = _options.barsSize; 
				if(_options.captionEl && bars.bottom === 'auto') {
					if(!_fakeCaptionContainer) {
						_fakeCaptionContainer = framework.createEl('pswp__caption pswp__caption--fake');
						_fakeCaptionContainer.appendChild( framework.createEl('pswp__caption__center') );
						_controls.insertBefore(_fakeCaptionContainer, _captionContainer);
						framework.addClass(_controls, 'pswp__ui--fit');
					}
					if( _options.addCaptionHTMLFn(item, _fakeCaptionContainer, true) ) {

						var captionSize = _fakeCaptionContainer.clientHeight;
						gap.bottom = parseInt(captionSize,10) || 44;
					} else {
						gap.bottom = bars.top; // if no caption, set size of bottom gap to size of top
					}
				} else {
					gap.bottom = bars.bottom === 'auto' ? 0 : bars.bottom;
				}
				
				// height of top bar is static, no need to calculate it
				gap.top = bars.top;
			} else {
				gap.top = gap.bottom = 0;
			}
		},
		_setupIdle = function() {
			// Hide controls when mouse is used
			if(_options.timeToIdle) {
				_listen('mouseUsed', function() {
					
					framework.bind(document, 'mousemove', _onIdleMouseMove);
					framework.bind(document, 'mouseout', _onMouseLeaveWindow);

					_idleInterval = setInterval(function() {
						_idleIncrement++;
						if(_idleIncrement === 2) {
							ui.setIdle(true);
						}
					}, _options.timeToIdle / 2);
				});
			}
		},
		_setupHidingControlsDuringGestures = function() {

			// Hide controls on vertical drag
			_listen('onVerticalDrag', function(now) {
				if(_controlsVisible && now < 0.95) {
					ui.hideControls();
				} else if(!_controlsVisible && now >= 0.95) {
					ui.showControls();
				}
			});

			// Hide controls when pinching to close
			var pinchControlsHidden;
			_listen('onPinchClose' , function(now) {
				if(_controlsVisible && now < 0.9) {
					ui.hideControls();
					pinchControlsHidden = true;
				} else if(pinchControlsHidden && !_controlsVisible && now > 0.9) {
					ui.showControls();
				}
			});

			_listen('zoomGestureEnded', function() {
				pinchControlsHidden = false;
				if(pinchControlsHidden && !_controlsVisible) {
					ui.showControls();
				}
			});

		};



	var _uiElements = [
		{ 
			name: 'caption', 
			option: 'captionEl',
			onInit: function(el) {  
				_captionContainer = el; 
			} 
		},
		{ 
			name: 'share-modal', 
			option: 'shareEl',
			onInit: function(el) {  
				_shareModal = el;
			},
			onTap: function() {
				_toggleShareModal();
			} 
		},
		{ 
			name: 'button--share', 
			option: 'shareEl',
			onInit: function(el) { 
				_shareButton = el;
			},
			onTap: function() {
				_toggleShareModal();
			} 
		},
		{ 
			name: 'button--zoom', 
			option: 'zoomEl',
			onTap: pswp.toggleDesktopZoom
		},
		{ 
			name: 'counter', 
			option: 'counterEl',
			onInit: function(el) {  
				_indexIndicator = el;
			} 
		},
		{ 
			name: 'button--close', 
			option: 'closeEl',
			onTap: pswp.close
		},
		{ 
			name: 'button--arrow--left', 
			option: 'arrowEl',
			onTap: pswp.prev
		},
		{ 
			name: 'button--arrow--right', 
			option: 'arrowEl',
			onTap: pswp.next
		},
		{ 
			name: 'button--fs', 
			option: 'fullscreenEl',
			onTap: function() {  
				if(_fullscrenAPI.isFullscreen()) {
					_fullscrenAPI.exit();
				} else {
					_fullscrenAPI.enter();
				}
			} 
		},
		{ 
			name: 'preloader', 
			option: 'preloaderEl',
			onInit: function(el) {  
				_loadingIndicator = el;
			} 
		}

	];

	var _setupUIElements = function() {
		var item,
			classAttr,
			uiElement;

		var loopThroughChildElements = function(sChildren) {
			if(!sChildren) {
				return;
			}

			var l = sChildren.length;
			for(var i = 0; i < l; i++) {
				item = sChildren[i];
				classAttr = item.className;

				for(var a = 0; a < _uiElements.length; a++) {
					uiElement = _uiElements[a];

					if(classAttr.indexOf('pswp__' + uiElement.name) > -1  ) {

						if( _options[uiElement.option] ) { // if element is not disabled from options
							
							framework.removeClass(item, 'pswp__element--disabled');
							if(uiElement.onInit) {
								uiElement.onInit(item);
							}
							
							//item.style.display = 'block';
						} else {
							framework.addClass(item, 'pswp__element--disabled');
							//item.style.display = 'none';
						}
					}
				}
			}
		};
		loopThroughChildElements(_controls.children);

		var topBar =  framework.getChildByClass(_controls, 'pswp__top-bar');
		if(topBar) {
			loopThroughChildElements( topBar.children );
		}
	};


	

	ui.init = function() {

		// extend options
		framework.extend(pswp.options, _defaultUIOptions, true);

		// create local link for fast access
		_options = pswp.options;

		// find pswp__ui element
		_controls = framework.getChildByClass(pswp.scrollWrap, 'pswp__ui');

		// create local link
		_listen = pswp.listen;


		_setupHidingControlsDuringGestures();

		// update controls when slides change
		_listen('beforeChange', ui.update);

		// toggle zoom on double-tap
		_listen('doubleTap', function(point) {
			var initialZoomLevel = pswp.currItem.initialZoomLevel;
			if(pswp.getZoomLevel() !== initialZoomLevel) {
				pswp.zoomTo(initialZoomLevel, point, 333);
			} else {
				pswp.zoomTo(_options.getDoubleTapZoom(false, pswp.currItem), point, 333);
			}
		});

		// Allow text selection in caption
		_listen('preventDragEvent', function(e, isDown, preventObj) {
			var t = e.target || e.srcElement;
			if(
				t && 
				t.getAttribute('class') && e.type.indexOf('mouse') > -1 && 
				( t.getAttribute('class').indexOf('__caption') > 0 || (/(SMALL|STRONG|EM)/i).test(t.tagName) ) 
			) {
				preventObj.prevent = false;
			}
		});

		// bind events for UI
		_listen('bindEvents', function() {
			framework.bind(_controls, 'pswpTap click', _onControlsTap);
			framework.bind(pswp.scrollWrap, 'pswpTap', ui.onGlobalTap);

			if(!pswp.likelyTouchDevice) {
				framework.bind(pswp.scrollWrap, 'mouseover', ui.onMouseOver);
			}
		});

		// unbind events for UI
		_listen('unbindEvents', function() {
			if(!_shareModalHidden) {
				_toggleShareModal();
			}

			if(_idleInterval) {
				clearInterval(_idleInterval);
			}
			framework.unbind(document, 'mouseout', _onMouseLeaveWindow);
			framework.unbind(document, 'mousemove', _onIdleMouseMove);
			framework.unbind(_controls, 'pswpTap click', _onControlsTap);
			framework.unbind(pswp.scrollWrap, 'pswpTap', ui.onGlobalTap);
			framework.unbind(pswp.scrollWrap, 'mouseover', ui.onMouseOver);

			if(_fullscrenAPI) {
				framework.unbind(document, _fullscrenAPI.eventK, ui.updateFullscreen);
				if(_fullscrenAPI.isFullscreen()) {
					_options.hideAnimationDuration = 0;
					_fullscrenAPI.exit();
				}
				_fullscrenAPI = null;
			}
		});


		// clean up things when gallery is destroyed
		_listen('destroy', function() {
			if(_options.captionEl) {
				if(_fakeCaptionContainer) {
					_controls.removeChild(_fakeCaptionContainer);
				}
				framework.removeClass(_captionContainer, 'pswp__caption--empty');
			}

			if(_shareModal) {
				_shareModal.children[0].onclick = null;
			}
			framework.removeClass(_controls, 'pswp__ui--over-close');
			framework.addClass( _controls, 'pswp__ui--hidden');
			ui.setIdle(false);
		});
		

		if(!_options.showAnimationDuration) {
			framework.removeClass( _controls, 'pswp__ui--hidden');
		}
		_listen('initialZoomIn', function() {
			if(_options.showAnimationDuration) {
				framework.removeClass( _controls, 'pswp__ui--hidden');
			}
		});
		_listen('initialZoomOut', function() {
			framework.addClass( _controls, 'pswp__ui--hidden');
		});

		_listen('parseVerticalMargin', _applyNavBarGaps);
		
		_setupUIElements();

		if(_options.shareEl && _shareButton && _shareModal) {
			_shareModalHidden = true;
		}

		_countNumItems();

		_setupIdle();

		_setupFullscreenAPI();

		_setupLoadingIndicator();
	};

	ui.setIdle = function(isIdle) {
		_isIdle = isIdle;
		_togglePswpClass(_controls, 'ui--idle', isIdle);
	};

	ui.update = function() {
		// Don't update UI if it's hidden
		if(_controlsVisible && pswp.currItem) {
			
			ui.updateIndexIndicator();

			if(_options.captionEl) {
				_options.addCaptionHTMLFn(pswp.currItem, _captionContainer);

				_togglePswpClass(_captionContainer, 'caption--empty', !pswp.currItem.title);
			}

			_overlayUIUpdated = true;

		} else {
			_overlayUIUpdated = false;
		}

		if(!_shareModalHidden) {
			_toggleShareModal();
		}

		_countNumItems();
	};

	ui.updateFullscreen = function(e) {

		if(e) {
			// some browsers change window scroll position during the fullscreen
			// so PhotoSwipe updates it just in case
			setTimeout(function() {
				pswp.setScrollOffset( 0, framework.getScrollY() );
			}, 50);
		}
		
		// toogle pswp--fs class on root element
		framework[ (_fullscrenAPI.isFullscreen() ? 'add' : 'remove') + 'Class' ](pswp.template, 'pswp--fs');
	};

	ui.updateIndexIndicator = function() {
		if(_options.counterEl) {
			_indexIndicator.innerHTML = (pswp.getCurrentIndex()+1) + 
										_options.indexIndicatorSep + 
										_options.getNumItemsFn();
		}
	};
	
	ui.onGlobalTap = function(e) {
		e = e || window.event;
		var target = e.target || e.srcElement;

		if(_blockControlsTap) {
			return;
		}

		if(e.detail && e.detail.pointerType === 'mouse') {

			// close gallery if clicked outside of the image
			if(_hasCloseClass(target)) {
				pswp.close();
				return;
			}

			if(framework.hasClass(target, 'pswp__img')) {
				if(pswp.getZoomLevel() === 1 && pswp.getZoomLevel() <= pswp.currItem.fitRatio) {
					if(_options.clickToCloseNonZoomable) {
						pswp.close();
					}
				} else {
					pswp.toggleDesktopZoom(e.detail.releasePoint);
				}
			}
			
		} else {

			// tap anywhere (except buttons) to toggle visibility of controls
			if(_options.tapToToggleControls) {
				if(_controlsVisible) {
					ui.hideControls();
				} else {
					ui.showControls();
				}
			}

			// tap to close gallery
			if(_options.tapToClose && (framework.hasClass(target, 'pswp__img') || _hasCloseClass(target)) ) {
				pswp.close();
				return;
			}
			
		}
	};
	ui.onMouseOver = function(e) {
		e = e || window.event;
		var target = e.target || e.srcElement;

		// add class when mouse is over an element that should close the gallery
		_togglePswpClass(_controls, 'ui--over-close', _hasCloseClass(target));
	};

	ui.hideControls = function() {
		framework.addClass(_controls,'pswp__ui--hidden');
		_controlsVisible = false;
	};

	ui.showControls = function() {
		_controlsVisible = true;
		if(!_overlayUIUpdated) {
			ui.update();
		}
		framework.removeClass(_controls,'pswp__ui--hidden');
	};

	ui.supportsFullscreen = function() {
		var d = document;
		return !!(d.exitFullscreen || d.mozCancelFullScreen || d.webkitExitFullscreen || d.msExitFullscreen);
	};

	ui.getFullscreenAPI = function() {
		var dE = document.documentElement,
			api,
			tF = 'fullscreenchange';

		if (dE.requestFullscreen) {
			api = {
				enterK: 'requestFullscreen',
				exitK: 'exitFullscreen',
				elementK: 'fullscreenElement',
				eventK: tF
			};

		} else if(dE.mozRequestFullScreen ) {
			api = {
				enterK: 'mozRequestFullScreen',
				exitK: 'mozCancelFullScreen',
				elementK: 'mozFullScreenElement',
				eventK: 'moz' + tF
			};

			

		} else if(dE.webkitRequestFullscreen) {
			api = {
				enterK: 'webkitRequestFullscreen',
				exitK: 'webkitExitFullscreen',
				elementK: 'webkitFullscreenElement',
				eventK: 'webkit' + tF
			};

		} else if(dE.msRequestFullscreen) {
			api = {
				enterK: 'msRequestFullscreen',
				exitK: 'msExitFullscreen',
				elementK: 'msFullscreenElement',
				eventK: 'MSFullscreenChange'
			};
		}

		if(api) {
			api.enter = function() { 
				// disable close-on-scroll in fullscreen
				_initalCloseOnScrollValue = _options.closeOnScroll; 
				_options.closeOnScroll = false; 

				if(this.enterK === 'webkitRequestFullscreen') {
					pswp.template[this.enterK]( Element.ALLOW_KEYBOARD_INPUT );
				} else {
					return pswp.template[this.enterK](); 
				}
			};
			api.exit = function() { 
				_options.closeOnScroll = _initalCloseOnScrollValue;

				return document[this.exitK](); 

			};
			api.isFullscreen = function() { return document[this.elementK]; };
		}

		return api;
	};



};
return PhotoSwipeUI_Default;


});


/*! 
 * 
 * ================== js/libs/plugins/jquery.scrollTo.js =================== 
 **/ 

/*!
 * jQuery.scrollTo
 * Copyright (c) 2007-2015 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
 * Licensed under MIT
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * @projectDescription Lightweight, cross-browser and highly customizable animated scrolling with jQuery
 * @author Ariel Flesler
 * @version 2.1.2
 */
;(function(factory) {
	'use strict';
	if (typeof define === 'function' && define.amd) {
		// AMD
		define(['jquery'], factory);
	} else if (typeof module !== 'undefined' && module.exports) {
		// CommonJS
		module.exports = factory(require('jquery'));
	} else {
		// Global
		factory(jQuery);
	}
})(function($) {
	'use strict';

	var $scrollTo = $.scrollTo = function(target, duration, settings) {
		return $(window).scrollTo(target, duration, settings);
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: 0,
		limit:true
	};

	function isWin(elem) {
		return !elem.nodeName ||
			$.inArray(elem.nodeName.toLowerCase(), ['iframe','#document','html','body']) !== -1;
	}		

	$.fn.scrollTo = function(target, duration, settings) {
		if (typeof duration === 'object') {
			settings = duration;
			duration = 0;
		}
		if (typeof settings === 'function') {
			settings = { onAfter:settings };
		}
		if (target === 'max') {
			target = 9e9;
		}

		settings = $.extend({}, $scrollTo.defaults, settings);
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.duration;
		// Make sure the settings are given right
		var queue = settings.queue && settings.axis.length > 1;
		if (queue) {
			// Let's keep the overall duration
			duration /= 2;
		}
		settings.offset = both(settings.offset);
		settings.over = both(settings.over);

		return this.each(function() {
			// Null target yields nothing, just like jQuery does
			if (target === null) return;

			var win = isWin(this),
				elem = win ? this.contentWindow || window : this,
				$elem = $(elem),
				targ = target, 
				attr = {},
				toff;

			switch (typeof targ) {
				// A number will pass the regex
				case 'number':
				case 'string':
					if (/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(targ)) {
						targ = both(targ);
						// We are done
						break;
					}
					// Relative/Absolute selector
					targ = win ? $(targ) : $(targ, elem);
					/* falls through */
				case 'object':
					if (targ.length === 0) return;
					// DOMElement / jQuery
					if (targ.is || targ.style) {
						// Get the real position of the target
						toff = (targ = $(targ)).offset();
					}
			}

			var offset = $.isFunction(settings.offset) && settings.offset(elem, targ) || settings.offset;

			$.each(settings.axis.split(''), function(i, axis) {
				var Pos	= axis === 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					prev = $elem[key](),
					max = $scrollTo.max(elem, axis);

				if (toff) {// jQuery / DOMElement
					attr[key] = toff[pos] + (win ? 0 : prev - $elem.offset()[pos]);

					// If it's a dom element, reduce the margin
					if (settings.margin) {
						attr[key] -= parseInt(targ.css('margin'+Pos), 10) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width'), 10) || 0;
					}

					attr[key] += offset[pos] || 0;

					if (settings.over[pos]) {
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis === 'x'?'width':'height']() * settings.over[pos];
					}
				} else {
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) === '%' ?
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if (settings.limit && /^\d+$/.test(attr[key])) {
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min(attr[key], max);
				}

				// Don't waste time animating, if there's no need.
				if (!i && settings.axis.length > 1) {
					if (prev === attr[key]) {
						// No animation needed
						attr = {};
					} else if (queue) {
						// Intermediate animation
						animate(settings.onAfterFirst);
						// Don't animate this axis again in the next iteration.
						attr = {};
					}
				}
			});

			animate(settings.onAfter);

			function animate(callback) {
				var opts = $.extend({}, settings, {
					// The queue setting conflicts with animate()
					// Force it to always be true
					queue: true,
					duration: duration,
					complete: callback && function() {
						callback.call(elem, targ, settings);
					}
				});
				$elem.animate(attr, opts);
			}
		});
	};

	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function(elem, axis) {
		var Dim = axis === 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;

		if (!isWin(elem))
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();

		var size = 'client' + Dim,
			doc = elem.ownerDocument || elem.document,
			html = doc.documentElement,
			body = doc.body;

		return Math.max(html[scroll], body[scroll]) - Math.min(html[size], body[size]);
	};

	function both(val) {
		return $.isFunction(val) || $.isPlainObject(val) ? val : { top:val, left:val };
	}

	// Add special hooks so that window scroll properties can be animated
	$.Tween.propHooks.scrollLeft = 
	$.Tween.propHooks.scrollTop = {
		get: function(t) {
			return $(t.elem)[t.prop]();
		},
		set: function(t) {
			var curr = this.get(t);
			// If interrupt is true and user scrolled, stop animating
			if (t.options.interrupt && t._last && t._last !== curr) {
				return $(t.elem).stop();
			}
			var next = Math.round(t.now);
			// Don't waste CPU
			// Browsers don't render floating point scroll
			if (curr !== next) {
				$(t.elem)[t.prop](next);
				t._last = this.get(t);
			}
		}
	};

	// AMD requirement
	return $scrollTo;
});


/*! 
 * 
 * ================== js/libs/plugins/lazysizes.js =================== 
 **/ 

(function(window, factory) {
	var lazySizes = factory(window, window.document);
	window.lazySizes = lazySizes;
	if(typeof module == 'object' && module.exports){
		module.exports = lazySizes;
	}
}(window, function l(window, document) {
	'use strict';
	/*jshint eqnull:true */
	if(!document.getElementsByClassName){return;}

	var lazysizes, lazySizesConfig;

	var docElem = document.documentElement;

	var Date = window.Date;

	var supportPicture = window.HTMLPictureElement;

	var _addEventListener = 'addEventListener';

	var _getAttribute = 'getAttribute';

	var addEventListener = window[_addEventListener];

	var setTimeout = window.setTimeout;

	var requestAnimationFrame = window.requestAnimationFrame || setTimeout;

	var requestIdleCallback = window.requestIdleCallback;

	var regPicture = /^picture$/i;

	var loadEvents = ['load', 'error', 'lazyincluded', '_lazyloaded'];

	var regClassCache = {};

	var forEach = Array.prototype.forEach;

	var hasClass = function(ele, cls) {
		if(!regClassCache[cls]){
			regClassCache[cls] = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		}
		return regClassCache[cls].test(ele[_getAttribute]('class') || '') && regClassCache[cls];
	};

	var addClass = function(ele, cls) {
		if (!hasClass(ele, cls)){
			ele.setAttribute('class', (ele[_getAttribute]('class') || '').trim() + ' ' + cls);
		}
	};

	var removeClass = function(ele, cls) {
		var reg;
		if ((reg = hasClass(ele,cls))) {
			ele.setAttribute('class', (ele[_getAttribute]('class') || '').replace(reg, ' '));
		}
	};

	var addRemoveLoadEvents = function(dom, fn, add){
		var action = add ? _addEventListener : 'removeEventListener';
		if(add){
			addRemoveLoadEvents(dom, fn);
		}
		loadEvents.forEach(function(evt){
			dom[action](evt, fn);
		});
	};

	var triggerEvent = function(elem, name, detail, noBubbles, noCancelable){
		var event = document.createEvent('CustomEvent');

		if(!detail){
			detail = {};
		}

		detail.instance = lazysizes;

		event.initCustomEvent(name, !noBubbles, !noCancelable, detail);

		elem.dispatchEvent(event);
		return event;
	};

	var updatePolyfill = function (el, full){
		var polyfill;
		if( !supportPicture && ( polyfill = (window.picturefill || lazySizesConfig.pf) ) ){
			polyfill({reevaluate: true, elements: [el]});
		} else if(full && full.src){
			el.src = full.src;
		}
	};

	var getCSS = function (elem, style){
		return (getComputedStyle(elem, null) || {})[style];
	};

	var getWidth = function(elem, parent, width){
		width = width || elem.offsetWidth;

		while(width < lazySizesConfig.minSize && parent && !elem._lazysizesWidth){
			width =  parent.offsetWidth;
			parent = parent.parentNode;
		}

		return width;
	};

	var rAF = (function(){
		var running, waiting;
		var firstFns = [];
		var secondFns = [];
		var fns = firstFns;

		var run = function(){
			var runFns = fns;

			fns = firstFns.length ? secondFns : firstFns;

			running = true;
			waiting = false;

			while(runFns.length){
				runFns.shift()();
			}

			running = false;
		};

		var rafBatch = function(fn, queue){
			if(running && !queue){
				fn.apply(this, arguments);
			} else {
				fns.push(fn);

				if(!waiting){
					waiting = true;
					(document.hidden ? setTimeout : requestAnimationFrame)(run);
				}
			}
		};

		rafBatch._lsFlush = run;

		return rafBatch;
	})();

	var rAFIt = function(fn, simple){
		return simple ?
			function() {
				rAF(fn);
			} :
			function(){
				var that = this;
				var args = arguments;
				rAF(function(){
					fn.apply(that, args);
				});
			}
		;
	};

	var throttle = function(fn){
		var running;
		var lastTime = 0;
		var gDelay = 125;
		var rICTimeout = lazySizesConfig.ricTimeout;
		var run = function(){
			running = false;
			lastTime = Date.now();
			fn();
		};
		var idleCallback = requestIdleCallback && lazySizesConfig.ricTimeout ?
			function(){
				requestIdleCallback(run, {timeout: rICTimeout});

				if(rICTimeout !== lazySizesConfig.ricTimeout){
					rICTimeout = lazySizesConfig.ricTimeout;
				}
			} :
			rAFIt(function(){
				setTimeout(run);
			}, true)
		;

		return function(isPriority){
			var delay;

			if((isPriority = isPriority === true)){
				rICTimeout = 33;
			}

			if(running){
				return;
			}

			running =  true;

			delay = gDelay - (Date.now() - lastTime);

			if(delay < 0){
				delay = 0;
			}

			if(isPriority || (delay < 9 && requestIdleCallback)){
				idleCallback();
			} else {
				setTimeout(idleCallback, delay);
			}
		};
	};

	//based on http://modernjavascript.blogspot.de/2013/08/building-better-debounce.html
	var debounce = function(func) {
		var timeout, timestamp;
		var wait = 99;
		var run = function(){
			timeout = null;
			func();
		};
		var later = function() {
			var last = Date.now() - timestamp;

			if (last < wait) {
				setTimeout(later, wait - last);
			} else {
				(requestIdleCallback || run)(run);
			}
		};

		return function() {
			timestamp = Date.now();

			if (!timeout) {
				timeout = setTimeout(later, wait);
			}
		};
	};

	(function(){
		var prop;

		var lazySizesDefaults = {
			lazyClass: 'lazyload',
			loadedClass: 'lazyloaded',
			loadingClass: 'lazyloading',
			preloadClass: 'lazypreload',
			errorClass: 'lazyerror',
			//strictClass: 'lazystrict',
			autosizesClass: 'lazyautosizes',
			srcAttr: 'data-src',
			srcsetAttr: 'data-srcset',
			sizesAttr: 'data-sizes',
			//preloadAfterLoad: false,
			minSize: 40,
			customMedia: {},
			init: true,
			expFactor: 1.5,
			hFac: 0.8,
			loadMode: 2,
			loadHidden: true,
			ricTimeout: 300,
		};

		lazySizesConfig = window.lazySizesConfig || window.lazysizesConfig || {};

		for(prop in lazySizesDefaults){
			if(!(prop in lazySizesConfig)){
				lazySizesConfig[prop] = lazySizesDefaults[prop];
			}
		}

		window.lazySizesConfig = lazySizesConfig;

		setTimeout(function(){
			if(lazySizesConfig.init){
				init();
			}
		});
	})();

	var loader = (function(){
		var preloadElems, isCompleted, resetPreloadingTimer, loadMode, started;

		var eLvW, elvH, eLtop, eLleft, eLright, eLbottom;

		var defaultExpand, preloadExpand, hFac;

		var regImg = /^img$/i;
		var regIframe = /^iframe$/i;

		var supportScroll = ('onscroll' in window) && !(/glebot/.test(navigator.userAgent));

		var shrinkExpand = 0;
		var currentExpand = 0;

		var isLoading = 0;
		var lowRuns = -1;

		var resetPreloading = function(e){
			isLoading--;
			if(e && e.target){
				addRemoveLoadEvents(e.target, resetPreloading);
			}

			if(!e || isLoading < 0 || !e.target){
				isLoading = 0;
			}
		};

		var isNestedVisible = function(elem, elemExpand){
			var outerRect;
			var parent = elem;
			var visible = getCSS(document.body, 'visibility') == 'hidden' || getCSS(elem, 'visibility') != 'hidden';

			eLtop -= elemExpand;
			eLbottom += elemExpand;
			eLleft -= elemExpand;
			eLright += elemExpand;

			while(visible && (parent = parent.offsetParent) && parent != document.body && parent != docElem){
				visible = ((getCSS(parent, 'opacity') || 1) > 0);

				if(visible && getCSS(parent, 'overflow') != 'visible'){
					outerRect = parent.getBoundingClientRect();
					visible = eLright > outerRect.left &&
						eLleft < outerRect.right &&
						eLbottom > outerRect.top - 1 &&
						eLtop < outerRect.bottom + 1
					;
				}
			}

			return visible;
		};

		var checkElements = function() {
			var eLlen, i, rect, autoLoadElem, loadedSomething, elemExpand, elemNegativeExpand, elemExpandVal, beforeExpandVal;

			var lazyloadElems = lazysizes.elements;

			if((loadMode = lazySizesConfig.loadMode) && isLoading < 8 && (eLlen = lazyloadElems.length)){

				i = 0;

				lowRuns++;

				if(preloadExpand == null){
					if(!('expand' in lazySizesConfig)){
						lazySizesConfig.expand = docElem.clientHeight > 500 && docElem.clientWidth > 500 ? 500 : 370;
					}

					defaultExpand = lazySizesConfig.expand;
					preloadExpand = defaultExpand * lazySizesConfig.expFactor;
				}

				if(currentExpand < preloadExpand && isLoading < 1 && lowRuns > 2 && loadMode > 2 && !document.hidden){
					currentExpand = preloadExpand;
					lowRuns = 0;
				} else if(loadMode > 1 && lowRuns > 1 && isLoading < 6){
					currentExpand = defaultExpand;
				} else {
					currentExpand = shrinkExpand;
				}

				for(; i < eLlen; i++){

					if(!lazyloadElems[i] || lazyloadElems[i]._lazyRace){continue;}

					if(!supportScroll){unveilElement(lazyloadElems[i]);continue;}

					if(!(elemExpandVal = lazyloadElems[i][_getAttribute]('data-expand')) || !(elemExpand = elemExpandVal * 1)){
						elemExpand = currentExpand;
					}

					if(beforeExpandVal !== elemExpand){
						eLvW = innerWidth + (elemExpand * hFac);
						elvH = innerHeight + elemExpand;
						elemNegativeExpand = elemExpand * -1;
						beforeExpandVal = elemExpand;
					}

					rect = lazyloadElems[i].getBoundingClientRect();

					if ((eLbottom = rect.bottom) >= elemNegativeExpand &&
						(eLtop = rect.top) <= elvH &&
						(eLright = rect.right) >= elemNegativeExpand * hFac &&
						(eLleft = rect.left) <= eLvW &&
						(eLbottom || eLright || eLleft || eLtop) &&
						(lazySizesConfig.loadHidden || getCSS(lazyloadElems[i], 'visibility') != 'hidden') &&
						((isCompleted && isLoading < 3 && !elemExpandVal && (loadMode < 3 || lowRuns < 4)) || isNestedVisible(lazyloadElems[i], elemExpand))){
						unveilElement(lazyloadElems[i]);
						loadedSomething = true;
						if(isLoading > 9){break;}
					} else if(!loadedSomething && isCompleted && !autoLoadElem &&
						isLoading < 4 && lowRuns < 4 && loadMode > 2 &&
						(preloadElems[0] || lazySizesConfig.preloadAfterLoad) &&
						(preloadElems[0] || (!elemExpandVal && ((eLbottom || eLright || eLleft || eLtop) || lazyloadElems[i][_getAttribute](lazySizesConfig.sizesAttr) != 'auto')))){
						autoLoadElem = preloadElems[0] || lazyloadElems[i];
					}
				}

				if(autoLoadElem && !loadedSomething){
					unveilElement(autoLoadElem);
				}
			}
		};

		var throttledCheckElements = throttle(checkElements);

		var switchLoadingClass = function(e){
			addClass(e.target, lazySizesConfig.loadedClass);
			removeClass(e.target, lazySizesConfig.loadingClass);
			addRemoveLoadEvents(e.target, rafSwitchLoadingClass);
			triggerEvent(e.target, 'lazyloaded');
		};
		var rafedSwitchLoadingClass = rAFIt(switchLoadingClass);
		var rafSwitchLoadingClass = function(e){
			rafedSwitchLoadingClass({target: e.target});
		};

		var changeIframeSrc = function(elem, src){
			try {
				elem.contentWindow.location.replace(src);
			} catch(e){
				elem.src = src;
			}
		};

		var handleSources = function(source){
			var customMedia;

			var sourceSrcset = source[_getAttribute](lazySizesConfig.srcsetAttr);

			if( (customMedia = lazySizesConfig.customMedia[source[_getAttribute]('data-media') || source[_getAttribute]('media')]) ){
				source.setAttribute('media', customMedia);
			}

			if(sourceSrcset){
				source.setAttribute('srcset', sourceSrcset);
			}
		};

		var lazyUnveil = rAFIt(function (elem, detail, isAuto, sizes, isImg){
			var src, srcset, parent, isPicture, event, firesLoad;

			if(!(event = triggerEvent(elem, 'lazybeforeunveil', detail)).defaultPrevented){

				if(sizes){
					if(isAuto){
						addClass(elem, lazySizesConfig.autosizesClass);
					} else {
						elem.setAttribute('sizes', sizes);
					}
				}

				srcset = elem[_getAttribute](lazySizesConfig.srcsetAttr);
				src = elem[_getAttribute](lazySizesConfig.srcAttr);

				if(isImg) {
					parent = elem.parentNode;
					isPicture = parent && regPicture.test(parent.nodeName || '');
				}

				firesLoad = detail.firesLoad || (('src' in elem) && (srcset || src || isPicture));

				event = {target: elem};

				if(firesLoad){
					addRemoveLoadEvents(elem, resetPreloading, true);
					clearTimeout(resetPreloadingTimer);
					resetPreloadingTimer = setTimeout(resetPreloading, 2500);

					addClass(elem, lazySizesConfig.loadingClass);
					addRemoveLoadEvents(elem, rafSwitchLoadingClass, true);
				}

				if(isPicture){
					forEach.call(parent.getElementsByTagName('source'), handleSources);
				}

				if(srcset){
					elem.setAttribute('srcset', srcset);
				} else if(src && !isPicture){
					if(regIframe.test(elem.nodeName)){
						changeIframeSrc(elem, src);
					} else {
						elem.src = src;
					}
				}

				if(isImg && (srcset || isPicture)){
					updatePolyfill(elem, {src: src});
				}
			}

			if(elem._lazyRace){
				delete elem._lazyRace;
			}
			removeClass(elem, lazySizesConfig.lazyClass);

			rAF(function(){
				if( !firesLoad || (elem.complete && elem.naturalWidth > 1)){
					if(firesLoad){
						resetPreloading(event);
					} else {
						isLoading--;
					}
					switchLoadingClass(event);
				}
			}, true);
		});

		var unveilElement = function (elem){
			var detail;

			var isImg = regImg.test(elem.nodeName);

			//allow using sizes="auto", but don't use. it's invalid. Use data-sizes="auto" or a valid value for sizes instead (i.e.: sizes="80vw")
			var sizes = isImg && (elem[_getAttribute](lazySizesConfig.sizesAttr) || elem[_getAttribute]('sizes'));
			var isAuto = sizes == 'auto';

			if( (isAuto || !isCompleted) && isImg && (elem[_getAttribute]('src') || elem.srcset) && !elem.complete && !hasClass(elem, lazySizesConfig.errorClass) && hasClass(elem, lazySizesConfig.lazyClass)){return;}

			detail = triggerEvent(elem, 'lazyunveilread').detail;

			if(isAuto){
				 autoSizer.updateElem(elem, true, elem.offsetWidth);
			}

			elem._lazyRace = true;
			isLoading++;

			lazyUnveil(elem, detail, isAuto, sizes, isImg);
		};

		var onload = function(){
			if(isCompleted){return;}
			if(Date.now() - started < 999){
				setTimeout(onload, 999);
				return;
			}
			var afterScroll = debounce(function(){
				lazySizesConfig.loadMode = 3;
				throttledCheckElements();
			});

			isCompleted = true;

			lazySizesConfig.loadMode = 3;

			throttledCheckElements();

			addEventListener('scroll', function(){
				if(lazySizesConfig.loadMode == 3){
					lazySizesConfig.loadMode = 2;
				}
				afterScroll();
			}, true);
		};

		return {
			_: function(){
				started = Date.now();

				lazysizes.elements = document.getElementsByClassName(lazySizesConfig.lazyClass);
				preloadElems = document.getElementsByClassName(lazySizesConfig.lazyClass + ' ' + lazySizesConfig.preloadClass);
				hFac = lazySizesConfig.hFac;

				addEventListener('scroll', throttledCheckElements, true);

				addEventListener('resize', throttledCheckElements, true);

				if(window.MutationObserver){
					new MutationObserver( throttledCheckElements ).observe( docElem, {childList: true, subtree: true, attributes: true} );
				} else {
					docElem[_addEventListener]('DOMNodeInserted', throttledCheckElements, true);
					docElem[_addEventListener]('DOMAttrModified', throttledCheckElements, true);
					setInterval(throttledCheckElements, 999);
				}

				addEventListener('hashchange', throttledCheckElements, true);

				//, 'fullscreenchange'
				['focus', 'mouseover', 'click', 'load', 'transitionend', 'animationend', 'webkitAnimationEnd'].forEach(function(name){
					document[_addEventListener](name, throttledCheckElements, true);
				});

				if((/d$|^c/.test(document.readyState))){
					onload();
				} else {
					addEventListener('load', onload);
					document[_addEventListener]('DOMContentLoaded', throttledCheckElements);
					setTimeout(onload, 20000);
				}

				if(lazysizes.elements.length){
					checkElements();
					rAF._lsFlush();
				} else {
					throttledCheckElements();
				}
			},
			checkElems: throttledCheckElements,
			unveil: unveilElement
		};
	})();


	var autoSizer = (function(){
		var autosizesElems;

		var sizeElement = rAFIt(function(elem, parent, event, width){
			var sources, i, len;
			elem._lazysizesWidth = width;
			width += 'px';

			elem.setAttribute('sizes', width);

			if(regPicture.test(parent.nodeName || '')){
				sources = parent.getElementsByTagName('source');
				for(i = 0, len = sources.length; i < len; i++){
					sources[i].setAttribute('sizes', width);
				}
			}

			if(!event.detail.dataAttr){
				updatePolyfill(elem, event.detail);
			}
		});
		var getSizeElement = function (elem, dataAttr, width){
			var event;
			var parent = elem.parentNode;

			if(parent){
				width = getWidth(elem, parent, width);
				event = triggerEvent(elem, 'lazybeforesizes', {width: width, dataAttr: !!dataAttr});

				if(!event.defaultPrevented){
					width = event.detail.width;

					if(width && width !== elem._lazysizesWidth){
						sizeElement(elem, parent, event, width);
					}
				}
			}
		};

		var updateElementsSizes = function(){
			var i;
			var len = autosizesElems.length;
			if(len){
				i = 0;

				for(; i < len; i++){
					getSizeElement(autosizesElems[i]);
				}
			}
		};

		var debouncedUpdateElementsSizes = debounce(updateElementsSizes);

		return {
			_: function(){
				autosizesElems = document.getElementsByClassName(lazySizesConfig.autosizesClass);
				addEventListener('resize', debouncedUpdateElementsSizes);
			},
			checkElems: debouncedUpdateElementsSizes,
			updateElem: getSizeElement
		};
	})();

	var init = function(){
		if(!init.i){
			init.i = true;
			autoSizer._();
			loader._();
		}
	};

	lazysizes = {
		cfg: lazySizesConfig,
		autoSizer: autoSizer,
		loader: loader,
		init: init,
		uP: updatePolyfill,
		aC: addClass,
		rC: removeClass,
		hC: hasClass,
		fire: triggerEvent,
		gW: getWidth,
		rAF: rAF,
	};

	return lazysizes;
}
));


/*! 
 * 
 * ================== js/libs/plugins/jquery.event.move.js =================== 
 **/ 

// jquery.event.move
//
// 1.3.6
//
// Stephen Band
//
// Triggers 'movestart', 'move' and 'moveend' events after
// mousemoves following a mousedown cross a distance threshold,
// similar to the native 'dragstart', 'drag' and 'dragend' events.
// Move events are throttled to animation frames. Move event objects
// have the properties:
//
// pageX:
// pageY:   Page coordinates of pointer.
// startX:
// startY:  Page coordinates of pointer at movestart.
// distX:
// distY:  Distance the pointer has moved since movestart.
// deltaX:
// deltaY:  Distance the finger has moved since last event.
// velocityX:
// velocityY:  Average velocity over last few events.


(function (module) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define(['jquery'], module);
	} else {
		// Browser globals
		module(jQuery);
	}
})(function(jQuery, undefined){

	var // Number of pixels a pressed pointer travels before movestart
	    // event is fired.
	    threshold = 6,
	
	    add = jQuery.event.add,
	
	    remove = jQuery.event.remove,

	    // Just sugar, so we can have arguments in the same order as
	    // add and remove.
	    trigger = function(node, type, data) {
	    	jQuery.event.trigger(type, data, node);
	    },

	    // Shim for requestAnimationFrame, falling back to timer. See:
	    // see http://paulirish.com/2011/requestanimationframe-for-smart-animating/
	    requestFrame = (function(){
	    	return (
	    		window.requestAnimationFrame ||
	    		window.webkitRequestAnimationFrame ||
	    		window.mozRequestAnimationFrame ||
	    		window.oRequestAnimationFrame ||
	    		window.msRequestAnimationFrame ||
	    		function(fn, element){
	    			return window.setTimeout(function(){
	    				fn();
	    			}, 25);
	    		}
	    	);
	    })(),
	    
	    ignoreTags = {
	    	textarea: true,
	    	input: true,
	    	select: true,
	    	button: true
	    },
	    
	    mouseevents = {
	    	move: 'mousemove',
	    	cancel: 'mouseup dragstart',
	    	end: 'mouseup'
	    },
	    
	    touchevents = {
	    	move: 'touchmove',
	    	cancel: 'touchend',
	    	end: 'touchend'
	    };


	// Constructors
	
	function Timer(fn){
		var callback = fn,
		    active = false,
		    running = false;
		
		function trigger(time) {
			if (active){
				callback();
				requestFrame(trigger);
				running = true;
				active = false;
			}
			else {
				running = false;
			}
		}
		
		this.kick = function(fn) {
			active = true;
			if (!running) { trigger(); }
		};
		
		this.end = function(fn) {
			var cb = callback;
			
			if (!fn) { return; }
			
			// If the timer is not running, simply call the end callback.
			if (!running) {
				fn();
			}
			// If the timer is running, and has been kicked lately, then
			// queue up the current callback and the end callback, otherwise
			// just the end callback.
			else {
				callback = active ?
					function(){ cb(); fn(); } : 
					fn ;
				
				active = true;
			}
		};
	}


	// Functions
	
	function returnTrue() {
		return true;
	}
	
	function returnFalse() {
		return false;
	}
	
	function preventDefault(e) {
		e.preventDefault();
	}
	
	function preventIgnoreTags(e) {
		// Don't prevent interaction with form elements.
		if (ignoreTags[ e.target.tagName.toLowerCase() ]) { return; }
		
		e.preventDefault();
	}

	function isLeftButton(e) {
		// Ignore mousedowns on any button other than the left (or primary)
		// mouse button, or when a modifier key is pressed.
		return (e.which === 1 && !e.ctrlKey && !e.altKey);
	}

	function identifiedTouch(touchList, id) {
		var i, l;

		if (touchList.identifiedTouch) {
			return touchList.identifiedTouch(id);
		}
		
		// touchList.identifiedTouch() does not exist in
		// webkit yet… we must do the search ourselves...
		
		i = -1;
		l = touchList.length;
		
		while (++i < l) {
			if (touchList[i].identifier === id) {
				return touchList[i];
			}
		}
	}

	function changedTouch(e, event) {
		var touch = identifiedTouch(e.changedTouches, event.identifier);

		// This isn't the touch you're looking for.
		if (!touch) { return; }

		// Chrome Android (at least) includes touches that have not
		// changed in e.changedTouches. That's a bit annoying. Check
		// that this touch has changed.
		if (touch.pageX === event.pageX && touch.pageY === event.pageY) { return; }

		return touch;
	}


	// Handlers that decide when the first movestart is triggered
	
	function mousedown(e){
		var data;

		if (!isLeftButton(e)) { return; }

		data = {
			target: e.target,
			startX: e.pageX,
			startY: e.pageY,
			timeStamp: e.timeStamp
		};

		add(document, mouseevents.move, mousemove, data);
		add(document, mouseevents.cancel, mouseend, data);
	}

	function mousemove(e){
		var data = e.data;

		checkThreshold(e, data, e, removeMouse);
	}

	function mouseend(e) {
		removeMouse();
	}

	function removeMouse() {
		remove(document, mouseevents.move, mousemove);
		remove(document, mouseevents.cancel, mouseend);
	}

	function touchstart(e) {
		var touch, template;

		// Don't get in the way of interaction with form elements.
		if (ignoreTags[ e.target.tagName.toLowerCase() ]) { return; }

		touch = e.changedTouches[0];
		
		// iOS live updates the touch objects whereas Android gives us copies.
		// That means we can't trust the touchstart object to stay the same,
		// so we must copy the data. This object acts as a template for
		// movestart, move and moveend event objects.
		template = {
			target: touch.target,
			startX: touch.pageX,
			startY: touch.pageY,
			timeStamp: e.timeStamp,
			identifier: touch.identifier
		};

		// Use the touch identifier as a namespace, so that we can later
		// remove handlers pertaining only to this touch.
		add(document, touchevents.move + '.' + touch.identifier, touchmove, template);
		add(document, touchevents.cancel + '.' + touch.identifier, touchend, template);
	}

	function touchmove(e){
		var data = e.data,
		    touch = changedTouch(e, data);

		if (!touch) { return; }

		checkThreshold(e, data, touch, removeTouch);
	}

	function touchend(e) {
		var template = e.data,
		    touch = identifiedTouch(e.changedTouches, template.identifier);

		if (!touch) { return; }

		removeTouch(template.identifier);
	}

	function removeTouch(identifier) {
		remove(document, '.' + identifier, touchmove);
		remove(document, '.' + identifier, touchend);
	}


	// Logic for deciding when to trigger a movestart.

	function checkThreshold(e, template, touch, fn) {
		var distX = touch.pageX - template.startX,
		    distY = touch.pageY - template.startY;

		// Do nothing if the threshold has not been crossed.
		if ((distX * distX) + (distY * distY) < (threshold * threshold)) { return; }

		triggerStart(e, template, touch, distX, distY, fn);
	}

	function handled() {
		// this._handled should return false once, and after return true.
		this._handled = returnTrue;
		return false;
	}

	function flagAsHandled(e) {
		e._handled();
	}

	function triggerStart(e, template, touch, distX, distY, fn) {
		var node = template.target,
		    touches, time;

		touches = e.targetTouches;
		time = e.timeStamp - template.timeStamp;

		// Create a movestart object with some special properties that
		// are passed only to the movestart handlers.
		template.type = 'movestart';
		template.distX = distX;
		template.distY = distY;
		template.deltaX = distX;
		template.deltaY = distY;
		template.pageX = touch.pageX;
		template.pageY = touch.pageY;
		template.velocityX = distX / time;
		template.velocityY = distY / time;
		template.targetTouches = touches;
		template.finger = touches ?
			touches.length :
			1 ;

		// The _handled method is fired to tell the default movestart
		// handler that one of the move events is bound.
		template._handled = handled;
			
		// Pass the touchmove event so it can be prevented if or when
		// movestart is handled.
		template._preventTouchmoveDefault = function() {
			e.preventDefault();
		};

		// Trigger the movestart event.
		trigger(template.target, template);

		// Unbind handlers that tracked the touch or mouse up till now.
		fn(template.identifier);
	}


	// Handlers that control what happens following a movestart

	function activeMousemove(e) {
		var timer = e.data.timer;

		e.data.touch = e;
		e.data.timeStamp = e.timeStamp;
		timer.kick();
	}

	function activeMouseend(e) {
		var event = e.data.event,
		    timer = e.data.timer;
		
		removeActiveMouse();

		endEvent(event, timer, function() {
			// Unbind the click suppressor, waiting until after mouseup
			// has been handled.
			setTimeout(function(){
				remove(event.target, 'click', returnFalse);
			}, 0);
		});
	}

	function removeActiveMouse(event) {
		remove(document, mouseevents.move, activeMousemove);
		remove(document, mouseevents.end, activeMouseend);
	}

	function activeTouchmove(e) {
		var event = e.data.event,
		    timer = e.data.timer,
		    touch = changedTouch(e, event);

		if (!touch) { return; }

		// Stop the interface from gesturing
		e.preventDefault();

		event.targetTouches = e.targetTouches;
		e.data.touch = touch;
		e.data.timeStamp = e.timeStamp;
		timer.kick();
	}

	function activeTouchend(e) {
		var event = e.data.event,
		    timer = e.data.timer,
		    touch = identifiedTouch(e.changedTouches, event.identifier);

		// This isn't the touch you're looking for.
		if (!touch) { return; }

		removeActiveTouch(event);
		endEvent(event, timer);
	}

	function removeActiveTouch(event) {
		remove(document, '.' + event.identifier, activeTouchmove);
		remove(document, '.' + event.identifier, activeTouchend);
	}


	// Logic for triggering move and moveend events

	function updateEvent(event, touch, timeStamp, timer) {
		var time = timeStamp - event.timeStamp;

		event.type = 'move';
		event.distX =  touch.pageX - event.startX;
		event.distY =  touch.pageY - event.startY;
		event.deltaX = touch.pageX - event.pageX;
		event.deltaY = touch.pageY - event.pageY;
		
		// Average the velocity of the last few events using a decay
		// curve to even out spurious jumps in values.
		event.velocityX = 0.3 * event.velocityX + 0.7 * event.deltaX / time;
		event.velocityY = 0.3 * event.velocityY + 0.7 * event.deltaY / time;
		event.pageX =  touch.pageX;
		event.pageY =  touch.pageY;
	}

	function endEvent(event, timer, fn) {
		timer.end(function(){
			event.type = 'moveend';

			trigger(event.target, event);
			
			return fn && fn();
		});
	}


	// jQuery special event definition

	function setup(data, namespaces, eventHandle) {
		// Stop the node from being dragged
		//add(this, 'dragstart.move drag.move', preventDefault);
		
		// Prevent text selection and touch interface scrolling
		//add(this, 'mousedown.move', preventIgnoreTags);
		
		// Tell movestart default handler that we've handled this
		add(this, 'movestart.move', flagAsHandled);

		// Don't bind to the DOM. For speed.
		return true;
	}
	
	function teardown(namespaces) {
		remove(this, 'dragstart drag', preventDefault);
		remove(this, 'mousedown touchstart', preventIgnoreTags);
		remove(this, 'movestart', flagAsHandled);
		
		// Don't bind to the DOM. For speed.
		return true;
	}
	
	function addMethod(handleObj) {
		// We're not interested in preventing defaults for handlers that
		// come from internal move or moveend bindings
		if (handleObj.namespace === "move" || handleObj.namespace === "moveend") {
			return;
		}
		
		// Stop the node from being dragged
		add(this, 'dragstart.' + handleObj.guid + ' drag.' + handleObj.guid, preventDefault, undefined, handleObj.selector);
		
		// Prevent text selection and touch interface scrolling
		add(this, 'mousedown.' + handleObj.guid, preventIgnoreTags, undefined, handleObj.selector);
	}
	
	function removeMethod(handleObj) {
		if (handleObj.namespace === "move" || handleObj.namespace === "moveend") {
			return;
		}
		
		remove(this, 'dragstart.' + handleObj.guid + ' drag.' + handleObj.guid);
		remove(this, 'mousedown.' + handleObj.guid);
	}
	
	jQuery.event.special.movestart = {
		setup: setup,
		teardown: teardown,
		add: addMethod,
		remove: removeMethod,

		_default: function(e) {
			var event, data;
			
			// If no move events were bound to any ancestors of this
			// target, high tail it out of here.
			if (!e._handled()) { return; }

			function update(time) {
				updateEvent(event, data.touch, data.timeStamp);
				trigger(e.target, event);
			}

			event = {
				target: e.target,
				startX: e.startX,
				startY: e.startY,
				pageX: e.pageX,
				pageY: e.pageY,
				distX: e.distX,
				distY: e.distY,
				deltaX: e.deltaX,
				deltaY: e.deltaY,
				velocityX: e.velocityX,
				velocityY: e.velocityY,
				timeStamp: e.timeStamp,
				identifier: e.identifier,
				targetTouches: e.targetTouches,
				finger: e.finger
			};

			data = {
				event: event,
				timer: new Timer(update),
				touch: undefined,
				timeStamp: undefined
			};
			
			if (e.identifier === undefined) {
				// We're dealing with a mouse
				// Stop clicks from propagating during a move
				add(e.target, 'click', returnFalse);
				add(document, mouseevents.move, activeMousemove, data);
				add(document, mouseevents.end, activeMouseend, data);
			}
			else {
				// We're dealing with a touch. Stop touchmove doing
				// anything defaulty.
				e._preventTouchmoveDefault();
				add(document, touchevents.move + '.' + e.identifier, activeTouchmove, data);
				add(document, touchevents.end + '.' + e.identifier, activeTouchend, data);
			}
		}
	};

	jQuery.event.special.move = {
		setup: function() {
			// Bind a noop to movestart. Why? It's the movestart
			// setup that decides whether other move events are fired.
			add(this, 'movestart.move', jQuery.noop);
		},
		
		teardown: function() {
			remove(this, 'movestart.move', jQuery.noop);
		}
	};
	
	jQuery.event.special.moveend = {
		setup: function() {
			// Bind a noop to movestart. Why? It's the movestart
			// setup that decides whether other move events are fired.
			add(this, 'movestart.moveend', jQuery.noop);
		},
		
		teardown: function() {
			remove(this, 'movestart.moveend', jQuery.noop);
		}
	};

	add(document, 'mousedown.move', mousedown);
	add(document, 'touchstart.move', touchstart);

	// Make jQuery copy touch event properties over to the jQuery event
	// object, if they are not already listed. But only do the ones we
	// really need. IE7/8 do not have Array#indexOf(), but nor do they
	// have touch events, so let's assume we can ignore them.
	if (typeof Array.prototype.indexOf === 'function') {
		(function(jQuery, undefined){
			var props = ["changedTouches", "targetTouches"],
			    l = props.length;
			
			while (l--) {
				if (jQuery.event.props.indexOf(props[l]) === -1) {
					jQuery.event.props.push(props[l]);
				}
			}
		})(jQuery);
	};
});


/*! 
 * 
 * ================== js/libs/plugins/jssocials.js =================== 
 **/ 

/*! jssocials - v1.4.0 - 2016-10-10
* http://js-socials.com
* Copyright (c) 2016 Artem Tabalin; Licensed MIT */
(function(window, $, undefined) {

    var JSSOCIALS = "JSSocials",
        JSSOCIALS_DATA_KEY = JSSOCIALS;

    var getOrApply = function(value, context) {
        if($.isFunction(value)) {
            return value.apply(context, $.makeArray(arguments).slice(2));
        }
        return value;
    };

    var IMG_SRC_REGEX = /(\.(jpeg|png|gif|bmp|svg)$|^data:image\/(jpeg|png|gif|bmp|svg\+xml);base64)/i;
    var URL_PARAMS_REGEX = /(&?[a-zA-Z0-9]+=)?\{([a-zA-Z0-9]+)\}/g;

    var MEASURES = {
        "G": 1000000000,
        "M": 1000000,
        "K": 1000
    };

    var shares = {};

    function Socials(element, config) {
        var $element = $(element);

        $element.data(JSSOCIALS_DATA_KEY, this);

        this._$element = $element;

        this.shares = [];

        this._init(config);
        this._render();
    }

    Socials.prototype = {
        url: "",
        text: "",
        shareIn: "blank",

        showLabel: function(screenWidth) {
            return (this.showCount === false) ?
                (screenWidth > this.smallScreenWidth) :
                (screenWidth >= this.largeScreenWidth);
        },

        showCount: function(screenWidth) {
            return (screenWidth <= this.smallScreenWidth) ? "inside" : true;
        },

        smallScreenWidth: 640,
        largeScreenWidth: 1024,

        resizeTimeout: 200,

        elementClass: "jssocials",
        sharesClass: "jssocials-shares",
        shareClass: "jssocials-share",
        shareButtonClass: "jssocials-share-button",
        shareLinkClass: "jssocials-share-link",
        shareLogoClass: "jssocials-share-logo",
        shareLabelClass: "jssocials-share-label",
        shareLinkCountClass: "jssocials-share-link-count",
        shareCountBoxClass: "jssocials-share-count-box",
        shareCountClass: "jssocials-share-count",
        shareZeroCountClass: "jssocials-share-no-count",

        _init: function(config) {
            this._initDefaults();
            $.extend(this, config);
            this._initShares();
            this._attachWindowResizeCallback();
        },

        _initDefaults: function() {
            this.url = window.location.href;
            this.text = $.trim($("meta[name=description]").attr("content") || $("title").text());
        },

        _initShares: function() {
            this.shares = $.map(this.shares, $.proxy(function(shareConfig) {
                if(typeof shareConfig === "string") {
                    shareConfig = { share: shareConfig };
                }

                var share = (shareConfig.share && shares[shareConfig.share]);

                if(!share && !shareConfig.renderer) {
                    throw Error("Share '" + shareConfig.share + "' is not found");
                }

                return $.extend({ url: this.url, text: this.text }, share, shareConfig);
            }, this));
        },

        _attachWindowResizeCallback: function() {
            $(window).on("resize", $.proxy(this._windowResizeHandler, this));
        },

        _detachWindowResizeCallback: function() {
            $(window).off("resize", this._windowResizeHandler);
        },

        _windowResizeHandler: function() {
            if($.isFunction(this.showLabel) || $.isFunction(this.showCount)) {
                window.clearTimeout(this._resizeTimer);
                this._resizeTimer = setTimeout($.proxy(this.refresh, this), this.resizeTimeout);
            }
        },

        _render: function() {
            this._clear();

            this._defineOptionsByScreen();

            this._$element.addClass(this.elementClass);

            this._$shares = $("<div>").addClass(this.sharesClass)
                .appendTo(this._$element);

            this._renderShares();
        },

        _defineOptionsByScreen: function() {
            this._screenWidth = $(window).width();
            this._showLabel = getOrApply(this.showLabel, this, this._screenWidth);
            this._showCount = getOrApply(this.showCount, this, this._screenWidth);
        },

        _renderShares: function() {
            $.each(this.shares, $.proxy(function(_, share) {
                this._renderShare(share);
            }, this));
        },

        _renderShare: function(share) {
            var $share;

            if($.isFunction(share.renderer)) {
                $share = $(share.renderer());
            } else {
                $share = this._createShare(share);
            }

            $share.addClass(this.shareClass)
                .addClass(share.share ? "jssocials-share-" + share.share : "")
                .addClass(share.css)
                .appendTo(this._$shares);
        },

        _createShare: function(share) {
            var $result = $("<div>");
            var $shareLink = this._createShareLink(share).appendTo($result);

            if(this._showCount) {
                var isInsideCount = (this._showCount === "inside");
                var $countContainer = isInsideCount ? $shareLink : $("<div>").addClass(this.shareCountBoxClass).appendTo($result);
                $countContainer.addClass(isInsideCount ? this.shareLinkCountClass : this.shareCountBoxClass);
                this._renderShareCount(share, $countContainer);
            }

            return $result;
        },

        _createShareLink: function(share) {
            var shareStrategy = this._getShareStrategy(share);

            var $result = shareStrategy.call(share, {
                shareUrl: this._getShareUrl(share)
            });

            $result.addClass(this.shareLinkClass)
                .append(this._createShareLogo(share));

            if(this._showLabel) {
                $result.append(this._createShareLabel(share));
            }

            $.each(this.on || {}, function(event, handler) {
                if($.isFunction(handler)) {
                    $result.on(event, $.proxy(handler, share));
                }
            });

            return $result;
        },

        _getShareStrategy: function(share) {
            var result = shareStrategies[share.shareIn || this.shareIn];

            if(!result)
                throw Error("Share strategy '" + this.shareIn + "' not found");

            return result;
        },

        _getShareUrl: function(share) {
            var shareUrl = getOrApply(share.shareUrl, share);
            return this._formatShareUrl(shareUrl, share);
        },

        _createShareLogo: function(share) {
            var logo = share.logo;

            var $result = IMG_SRC_REGEX.test(logo) ?
                $("<img>").attr("src", share.logo) :
                $("<i>").addClass(logo);

            $result.addClass(this.shareLogoClass);

            return $result;
        },

        _createShareLabel: function(share) {
            return $("<span>").addClass(this.shareLabelClass)
                .text(share.label);
        },

        _renderShareCount: function(share, $container) {
            var $count = $("<span>").addClass(this.shareCountClass);

            $container.addClass(this.shareZeroCountClass)
                .append($count);

            this._loadCount(share).done($.proxy(function(count) {
                if(count) {
                    $container.removeClass(this.shareZeroCountClass);
                    $count.text(count);
                }
            }, this));
        },

        _loadCount: function(share) {
            var deferred = $.Deferred();
            var countUrl = this._getCountUrl(share);

            if(!countUrl) {
                return deferred.resolve(0).promise();
            }

            var handleSuccess = $.proxy(function(response) {
                deferred.resolve(this._getCountValue(response, share));
            }, this);

            $.getJSON(countUrl).done(handleSuccess)
                .fail(function() {
                    $.get(countUrl).done(handleSuccess)
                        .fail(function() {
                            deferred.resolve(0);
                        });
                });

            return deferred.promise();
        },

        _getCountUrl: function(share) {
            var countUrl = getOrApply(share.countUrl, share);
            return this._formatShareUrl(countUrl, share);
        },

        _getCountValue: function(response, share) {
            var count = ($.isFunction(share.getCount) ? share.getCount(response) : response) || 0;
            return (typeof count === "string") ? count : this._formatNumber(count);
        },

        _formatNumber: function(number) {
            $.each(MEASURES, function(letter, value) {
                if(number >= value) {
                    number = parseFloat((number / value).toFixed(2)) + letter;
                    return false;
                }
            });

            return number;
        },

        _formatShareUrl: function(url, share) {
            return url.replace(URL_PARAMS_REGEX, function(match, key, field) {
                var value = share[field] || "";
                return value ? (key || "") + window.encodeURIComponent(value) : "";
            });
        },

        _clear: function() {
            window.clearTimeout(this._resizeTimer);
            this._$element.empty();
        },

        _passOptionToShares: function(key, value) {
            var shares = this.shares;

            $.each(["url", "text"], function(_, optionName) {
                if(optionName !== key)
                    return;

                $.each(shares, function(_, share) {
                    share[key] = value;
                });
            });
        },

        _normalizeShare: function(share) {
            if($.isNumeric(share)) {
                return this.shares[share];
            }

            if(typeof share === "string") {
                return $.grep(this.shares, function(s) {
                    return s.share === share;
                })[0];
            }

            return share;
        },

        refresh: function() {
            this._render();
        },

        destroy: function() {
            this._clear();
            this._detachWindowResizeCallback();

            this._$element
                .removeClass(this.elementClass)
                .removeData(JSSOCIALS_DATA_KEY);
        },

        option: function(key, value) {
            if(arguments.length === 1) {
                return this[key];
            }

            this[key] = value;

            this._passOptionToShares(key, value);

            this.refresh();
        },

        shareOption: function(share, key, value) {
            share = this._normalizeShare(share);

            if(arguments.length === 2) {
                return share[key];
            }

            share[key] = value;
            this.refresh();
        }
    };


    $.fn.jsSocials = function(config) {
        var args = $.makeArray(arguments),
            methodArgs = args.slice(1),
            result = this;

        this.each(function() {
            var $element = $(this),
                instance = $element.data(JSSOCIALS_DATA_KEY),
                methodResult;

            if(instance) {
                if(typeof config === "string") {
                    methodResult = instance[config].apply(instance, methodArgs);
                    if(methodResult !== undefined && methodResult !== instance) {
                        result = methodResult;
                        return false;
                    }
                } else {
                    instance._detachWindowResizeCallback();
                    instance._init(config);
                    instance._render();
                }
            } else {
                new Socials($element, config);
            }
        });

        return result;
    };

    var setDefaults = function(config) {
        var component;

        if($.isPlainObject(config)) {
            component = Socials.prototype;
        } else {
            component = shares[config];
            config = arguments[1] || {};
        }

        $.extend(component, config);
    };

    var shareStrategies = {
        popup: function(args) {
            return $("<a>").attr("href", "#")
                .on("click", function() {
                    window.open(args.shareUrl, null, "width=600, height=400, location=0, menubar=0, resizeable=0, scrollbars=0, status=0, titlebar=0, toolbar=0");
                    return false;
                });
        },

        blank: function(args) {
            return $("<a>").attr({ target: "_blank", href: args.shareUrl });
        },

        self: function(args) {
            return $("<a>").attr({ target: "_self", href: args.shareUrl });
        }
    };

    window.jsSocials = {
        Socials: Socials,
        shares: shares,
        shareStrategies: shareStrategies,
        setDefaults: setDefaults
    };

}(window, jQuery));


(function(window, $, jsSocials, undefined) {

    $.extend(jsSocials.shares, {

        email: {
            label: "E-mail",
            logo: "fa fa-at",
            shareUrl: "mailto:{to}?subject={text}&body={url}",
            countUrl: "",
            shareIn: "self"
        },

        twitter: {
            label: "Tweet",
            logo: "fa fa-twitter",
            shareUrl: "https://twitter.com/share?url={url}&text={text}&via={via}&hashtags={hashtags}",
            countUrl: ""
        },

        facebook: {
            label: "Like",
            logo: "fa fa-facebook",
            shareUrl: "https://facebook.com/sharer/sharer.php?u={url}",
            countUrl: "https://graph.facebook.com/?id={url}",
            getCount: function(data) {
                return data.share && data.share.share_count || 0;
            }
        },

        vkontakte: {
            label: "Like",
            logo: "fa fa-vk",
            shareUrl: "https://vk.com/share.php?url={url}&title={title}&description={text}",
            countUrl: "https://vk.com/share.php?act=count&index=1&url={url}",
            getCount: function(data) {
                return parseInt(data.slice(15, -2).split(', ')[1]);
            }
        },

        googleplus: {
            label: "+1",
            logo: "fa fa-google",
            shareUrl: "https://plus.google.com/share?url={url}",
            countUrl: ""
        },

        linkedin: {
            label: "Share",
            logo: "fa fa-linkedin",
            shareUrl: "https://www.linkedin.com/shareArticle?mini=true&url={url}",
            countUrl: "https://www.linkedin.com/countserv/count/share?format=jsonp&url={url}&callback=?",
            getCount: function(data) {
                return data.count;
            }
        },

        pinterest: {
            label: "Pin it",
            logo: "fa fa-pinterest",
            shareUrl: "https://pinterest.com/pin/create/bookmarklet/?media={media}&url={url}&description={text}",
            countUrl: "https://api.pinterest.com/v1/urls/count.json?&url={url}&callback=?",
            getCount: function(data) {
                return data.count;
            }
        },

        stumbleupon: {
            label: "Share",
            logo: "fa fa-stumbleupon",
            shareUrl: "http://www.stumbleupon.com/submit?url={url}&title={title}",
            countUrl:  "https://cors-anywhere.herokuapp.com/https://www.stumbleupon.com/services/1.01/badge.getinfo?url={url}",
            getCount: function(data) {
                return data.result.views;
            }
        },

        telegram: {
            label: "Telegram",
            logo: "fa fa-paper-plane",
            shareUrl: "tg://msg?text={url} {text}",
            countUrl: "",
            shareIn: "self"
        },

        whatsapp: {
            label: "WhatsApp",
            logo: "fa fa-whatsapp",
            shareUrl: "whatsapp://send?text={url} {text}",
            countUrl: "",
            shareIn: "self"
        },

        line: {
            label: "LINE",
            logo: "fa fa-comment",
            shareUrl: "http://line.me/R/msg/text/?{text} {url}",
            countUrl: ""
        },

        viber: {
            label: "Viber",
            logo: "fa fa-volume-control-phone",
            shareUrl: "viber://forward?text={url} {text}",
            countUrl: "",
            shareIn: "self"
        },

        pocket: {
            label: "Pocket",
            logo: "fa fa-get-pocket",
            shareUrl: "https://getpocket.com/save?url={url}&title={title}",
            countUrl: ""
        },

        messenger: {
            label: "Share",
            logo: "fa fa-commenting",
            shareUrl: "fb-messenger://share?link={url}",
            countUrl: "",
            shareIn: "self"
        }

    });

}(window, jQuery, window.jsSocials));


/*! 
 * 
 * ================== js/libs/plugins/jquery.twentytwenty.js =================== 
 **/ 

(function($){

  $.fn.twentytwenty = function(options) {
    var options = $.extend({default_offset_pct: 0.5, orientation: 'horizontal'}, options);
    return this.each(function() {

      var sliderPct = options.default_offset_pct;
      var container = $(this);
      var sliderOrientation = options.orientation;
      var beforeDirection = (sliderOrientation === 'vertical') ? 'down' : 'left';
      var afterDirection = (sliderOrientation === 'vertical') ? 'up' : 'right';
      
      
      container.wrap("<div class='twentytwenty-wrapper twentytwenty-" + sliderOrientation + "'></div>");
      container.append("<div class='twentytwenty-overlay'></div>");
      var beforeImg = container.find("img:first");
      var afterImg = container.find("img:last");
      container.append("<div class='twentytwenty-handle'></div>");
      var slider = container.find(".twentytwenty-handle");
      slider.append("<span class='twentytwenty-" + beforeDirection + "-arrow'></span>");
      slider.append("<span class='twentytwenty-" + afterDirection + "-arrow'></span>");
      container.addClass("twentytwenty-container");
      beforeImg.addClass("twentytwenty-before");
      afterImg.addClass("twentytwenty-after");
      
      var overlay = container.find(".twentytwenty-overlay");
      overlay.append("<div class='twentytwenty-before-label'></div>");
      overlay.append("<div class='twentytwenty-after-label'></div>");

      var calcOffset = function(dimensionPct) {
        var w = beforeImg.width();
        var h = beforeImg.height();
        return {
          w: w+"px",
          h: h+"px",
          cw: (dimensionPct*w)+"px",
          ch: (dimensionPct*h)+"px"
        };
      };

      var adjustContainer = function(offset) {
      	if (sliderOrientation === 'vertical') {
      	  beforeImg.css("clip", "rect(0,"+offset.w+","+offset.ch+",0)");
      	}
      	else {
          beforeImg.css("clip", "rect(0,"+offset.cw+","+offset.h+",0)");
    	}
        container.css("height", offset.h);
      };

      var adjustSlider = function(pct) {
        var offset = calcOffset(pct);
        slider.css((sliderOrientation==="vertical") ? "top" : "left", (sliderOrientation==="vertical") ? offset.ch : offset.cw);
        adjustContainer(offset);
      }

      $(window).on("resize.twentytwenty", function(e) {
        adjustSlider(sliderPct);
      });

      var offsetX = 0;
      var offsetY = 0;
      var imgWidth = 0;
      var imgHeight = 0;
      
      slider.on("movestart", function(e) {
        if (((e.distX > e.distY && e.distX < -e.distY) || (e.distX < e.distY && e.distX > -e.distY)) && sliderOrientation !== 'vertical') {
          e.preventDefault();
        }
        else if (((e.distX < e.distY && e.distX < -e.distY) || (e.distX > e.distY && e.distX > -e.distY)) && sliderOrientation === 'vertical') {
          e.preventDefault();
        }
        container.addClass("active");
        offsetX = container.offset().left;
        offsetY = container.offset().top;
        imgWidth = beforeImg.width(); 
        imgHeight = beforeImg.height();          
      });

      slider.on("moveend", function(e) {
        container.removeClass("active");
      });

      slider.on("move", function(e) {
        if (container.hasClass("active")) {
          sliderPct = (sliderOrientation === 'vertical') ? (e.pageY-offsetY)/imgHeight : (e.pageX-offsetX)/imgWidth;
          if (sliderPct < 0) {
            sliderPct = 0;
          }
          if (sliderPct > 1) {
            sliderPct = 1;
          }
          adjustSlider(sliderPct);
        }
      });

      container.find("img").on("mousedown", function(event) {
        event.preventDefault();
      });

      $(window).trigger("resize.twentytwenty");
    });
  };

})(jQuery);


/*! 
 * 
 * ================== js/libs/plugins/averta/averta-js-tools.js =================== 
 **/ 

/*!
 *  Averta JavaScript Tools - v1.0.0 (2018-08-23)
 *
 *  A collection of JavaScript files that used in multiple projects
 *
 *  Copyright (c) 2010-2018 Averta <info@averta.net> (www.averta.net)
 *  License:
 */


/* -------------------- src/averta-js-normalize.js -------------------- */


/**
 * UAParser.js v0.7.9
 * Lightweight JavaScript-based User-Agent string parser
 * https://github.com/faisalman/ua-parser-js
 *
 * Copyright © 2012-2015 Faisal Salman <fyzlman@gmail.com>
 * Dual licensed under GPLv2 & MIT
 */

(function (window, undefined) {

    'use strict';

    //////////////
    // Constants
    /////////////


    var LIBVERSION  = '0.7.9',
        EMPTY       = '',
        UNKNOWN     = '?',
        FUNC_TYPE   = 'function',
        UNDEF_TYPE  = 'undefined',
        OBJ_TYPE    = 'object',
        STR_TYPE    = 'string',
        MAJOR       = 'major', // deprecated
        MODEL       = 'model',
        NAME        = 'name',
        TYPE        = 'type',
        VENDOR      = 'vendor',
        VERSION     = 'version',
        ARCHITECTURE= 'architecture',
        CONSOLE     = 'console',
        MOBILE      = 'mobile',
        TABLET      = 'tablet',
        SMARTTV     = 'smarttv',
        WEARABLE    = 'wearable',
        EMBEDDED    = 'embedded';


    ///////////
    // Helper
    //////////


    var util = {
        extend : function (regexes, extensions) {
            for (var i in extensions) {
                if ("browser cpu device engine os".indexOf(i) !== -1 && extensions[i].length % 2 === 0) {
                    regexes[i] = extensions[i].concat(regexes[i]);
                }
            }
            return regexes;
        },
        has : function (str1, str2) {
          if (typeof str1 === "string") {
            return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
          } else {
            return false;
          }
        },
        lowerize : function (str) {
            return str.toLowerCase();
        },
        major : function (version) {
            return typeof(version) === STR_TYPE ? version.split(".")[0] : undefined;
        }
    };


    ///////////////
    // Map helper
    //////////////


    var mapper = {

        rgx : function () {

            var result, i = 0, j, k, p, q, matches, match, args = arguments;

            // loop through all regexes maps
            while (i < args.length && !matches) {

                var regex = args[i],       // even sequence (0,2,4,..)
                    props = args[i + 1];   // odd sequence (1,3,5,..)

                // construct object barebones
                if (typeof result === UNDEF_TYPE) {
                    result = {};
                    for (p in props) {
                        q = props[p];
                        if (typeof q === OBJ_TYPE) {
                            result[q[0]] = undefined;
                        } else {
                            result[q] = undefined;
                        }
                    }
                }

                // try matching uastring with regexes
                j = k = 0;
                while (j < regex.length && !matches) {
                    matches = regex[j++].exec(this.getUA());
                    if (!!matches) {
                        for (p = 0; p < props.length; p++) {
                            match = matches[++k];
                            q = props[p];
                            // check if given property is actually array
                            if (typeof q === OBJ_TYPE && q.length > 0) {
                                if (q.length == 2) {
                                    if (typeof q[1] == FUNC_TYPE) {
                                        // assign modified match
                                        result[q[0]] = q[1].call(this, match);
                                    } else {
                                        // assign given value, ignore regex match
                                        result[q[0]] = q[1];
                                    }
                                } else if (q.length == 3) {
                                    // check whether function or regex
                                    if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) {
                                        // call function (usually string mapper)
                                        result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
                                    } else {
                                        // sanitize match using given regex
                                        result[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
                                    }
                                } else if (q.length == 4) {
                                        result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
                                }
                            } else {
                                result[q] = match ? match : undefined;
                            }
                        }
                    }
                }
                i += 2;
            }
            return result;
        },

        str : function (str, map) {

            for (var i in map) {
                // check if array
                if (typeof map[i] === OBJ_TYPE && map[i].length > 0) {
                    for (var j = 0; j < map[i].length; j++) {
                        if (util.has(map[i][j], str)) {
                            return (i === UNKNOWN) ? undefined : i;
                        }
                    }
                } else if (util.has(map[i], str)) {
                    return (i === UNKNOWN) ? undefined : i;
                }
            }
            return str;
        }
    };


    ///////////////
    // String map
    //////////////


    var maps = {

        browser : {
            oldsafari : {
                version : {
                    '1.0'   : '/8',
                    '1.2'   : '/1',
                    '1.3'   : '/3',
                    '2.0'   : '/412',
                    '2.0.2' : '/416',
                    '2.0.3' : '/417',
                    '2.0.4' : '/419',
                    '?'     : '/'
                }
            }
        },

        device : {
            amazon : {
                model : {
                    'Fire Phone' : ['SD', 'KF']
                }
            },
            sprint : {
                model : {
                    'Evo Shift 4G' : '7373KT'
                },
                vendor : {
                    'HTC'       : 'APA',
                    'Sprint'    : 'Sprint'
                }
            }
        },

        os : {
            windows : {
                version : {
                    'ME'        : '4.90',
                    'NT 3.11'   : 'NT3.51',
                    'NT 4.0'    : 'NT4.0',
                    '2000'      : 'NT 5.0',
                    'XP'        : ['NT 5.1', 'NT 5.2'],
                    'Vista'     : 'NT 6.0',
                    '7'         : 'NT 6.1',
                    '8'         : 'NT 6.2',
                    '8.1'       : 'NT 6.3',
                    '10'        : ['NT 6.4', 'NT 10.0'],
                    'RT'        : 'ARM'
                }
            }
        }
    };


    //////////////
    // Regex map
    /////////////


    var regexes = {

        browser : [[

            // Presto based
            /(opera\smini)\/([\w\.-]+)/i,                                       // Opera Mini
            /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,                      // Opera Mobi/Tablet
            /(opera).+version\/([\w\.]+)/i,                                     // Opera > 9.80
            /(opera)[\/\s]+([\w\.]+)/i                                          // Opera < 9.80

            ], [NAME, VERSION], [

            /\s(opr)\/([\w\.]+)/i                                               // Opera Webkit
            ], [[NAME, 'Opera'], VERSION], [

            // Mixed
            /(kindle)\/([\w\.]+)/i,                                             // Kindle
            /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,
                                                                                // Lunascape/Maxthon/Netfront/Jasmine/Blazer

            // Trident based
            /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,
                                                                                // Avant/IEMobile/SlimBrowser/Baidu
            /(?:ms|\()(ie)\s([\w\.]+)/i,                                        // Internet Explorer

            // Webkit/KHTML based
            /(rekonq)\/([\w\.]+)*/i,                                            // Rekonq
            /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium)\/([\w\.-]+)/i
                                                                                // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium
            ], [NAME, VERSION], [

            /(trident).+rv[:\s]([\w\.]+).+like\sgecko/i                         // IE11
            ], [[NAME, 'IE'], VERSION], [

            /(edge)\/((\d+)?[\w\.]+)/i                                          // Microsoft Edge
            ], [NAME, VERSION], [

            /(yabrowser)\/([\w\.]+)/i                                           // Yandex
            ], [[NAME, 'Yandex'], VERSION], [

            /(comodo_dragon)\/([\w\.]+)/i                                       // Comodo Dragon
            ], [[NAME, /_/g, ' '], VERSION], [

            /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i,
                                                                                // Chrome/OmniWeb/Arora/Tizen/Nokia
            /(uc\s?browser|qqbrowser)[\/\s]?([\w\.]+)/i
                                                                                // UCBrowser/QQBrowser
            ], [NAME, VERSION], [

            /(dolfin)\/([\w\.]+)/i                                              // Dolphin
            ], [[NAME, 'Dolphin'], VERSION], [

            /((?:android.+)crmo|crios)\/([\w\.]+)/i                             // Chrome for Android/iOS
            ], [[NAME, 'Chrome'], VERSION], [

            /XiaoMi\/MiuiBrowser\/([\w\.]+)/i                                   // MIUI Browser
            ], [VERSION, [NAME, 'MIUI Browser']], [

            /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)/i         // Android Browser
            ], [VERSION, [NAME, 'Android Browser']], [

            /FBAV\/([\w\.]+);/i                                                 // Facebook App for iOS
            ], [VERSION, [NAME, 'Facebook']], [

            /version\/([\w\.]+).+?mobile\/\w+\s(safari)/i                       // Mobile Safari
            ], [VERSION, [NAME, 'Mobile Safari']], [

            /version\/([\w\.]+).+?(mobile\s?safari|safari)/i                    // Safari & Safari Mobile
            ], [VERSION, NAME], [

            /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i                     // Safari < 3.0
            ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [

            /(konqueror)\/([\w\.]+)/i,                                          // Konqueror
            /(webkit|khtml)\/([\w\.]+)/i
            ], [NAME, VERSION], [

            // Gecko based
            /(navigator|netscape)\/([\w\.-]+)/i                                 // Netscape
            ], [[NAME, 'Netscape'], VERSION], [
            /fxios\/([\w\.-]+)/i                                                // Firefox for iOS
            ], [VERSION, [NAME, 'Firefox']], [
            /(swiftfox)/i,                                                      // Swiftfox
            /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,
                                                                                // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
            /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,
                                                                                // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
            /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,                          // Mozilla

            // Other
            /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf)[\/\s]?([\w\.]+)/i,
                                                                                // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf
            /(links)\s\(([\w\.]+)/i,                                            // Links
            /(gobrowser)\/?([\w\.]+)*/i,                                        // GoBrowser
            /(ice\s?browser)\/v?([\w\._]+)/i,                                   // ICE Browser
            /(mosaic)[\/\s]([\w\.]+)/i                                          // Mosaic
            ], [NAME, VERSION]

            /* /////////////////////
            // Media players BEGIN
            ////////////////////////

            , [

            /(apple(?:coremedia|))\/((\d+)[\w\._]+)/i,                          // Generic Apple CoreMedia
            /(coremedia) v((\d+)[\w\._]+)/i
            ], [NAME, VERSION], [

            /(aqualung|lyssna|bsplayer)\/((\d+)?[\w\.-]+)/i                     // Aqualung/Lyssna/BSPlayer
            ], [NAME, VERSION], [

            /(ares|ossproxy)\s((\d+)[\w\.-]+)/i                                 // Ares/OSSProxy
            ], [NAME, VERSION], [

            /(audacious|audimusicstream|amarok|bass|core|dalvik|gnomemplayer|music on console|nsplayer|psp-internetradioplayer|videos)\/((\d+)[\w\.-]+)/i,
                                                                                // Audacious/AudiMusicStream/Amarok/BASS/OpenCORE/Dalvik/GnomeMplayer/MoC
                                                                                // NSPlayer/PSP-InternetRadioPlayer/Videos
            /(clementine|music player daemon)\s((\d+)[\w\.-]+)/i,               // Clementine/MPD
            /(lg player|nexplayer)\s((\d+)[\d\.]+)/i,
            /player\/(nexplayer|lg player)\s((\d+)[\w\.-]+)/i                   // NexPlayer/LG Player
            ], [NAME, VERSION], [
            /(nexplayer)\s((\d+)[\w\.-]+)/i                                     // Nexplayer
            ], [NAME, VERSION], [

            /(flrp)\/((\d+)[\w\.-]+)/i                                          // Flip Player
            ], [[NAME, 'Flip Player'], VERSION], [

            /(fstream|nativehost|queryseekspider|ia-archiver|facebookexternalhit)/i
                                                                                // FStream/NativeHost/QuerySeekSpider/IA Archiver/facebookexternalhit
            ], [NAME], [

            /(gstreamer) souphttpsrc (?:\([^\)]+\)){0,1} libsoup\/((\d+)[\w\.-]+)/i
                                                                                // Gstreamer
            ], [NAME, VERSION], [

            /(htc streaming player)\s[\w_]+\s\/\s((\d+)[\d\.]+)/i,              // HTC Streaming Player
            /(java|python-urllib|python-requests|wget|libcurl)\/((\d+)[\w\.-_]+)/i,
                                                                                // Java/urllib/requests/wget/cURL
            /(lavf)((\d+)[\d\.]+)/i                                             // Lavf (FFMPEG)
            ], [NAME, VERSION], [

            /(htc_one_s)\/((\d+)[\d\.]+)/i                                      // HTC One S
            ], [[NAME, /_/g, ' '], VERSION], [

            /(mplayer)(?:\s|\/)(?:(?:sherpya-){0,1}svn)(?:-|\s)(r\d+(?:-\d+[\w\.-]+){0,1})/i
                                                                                // MPlayer SVN
            ], [NAME, VERSION], [

            /(mplayer)(?:\s|\/|[unkow-]+)((\d+)[\w\.-]+)/i                      // MPlayer
            ], [NAME, VERSION], [

            /(mplayer)/i,                                                       // MPlayer (no other info)
            /(yourmuze)/i,                                                      // YourMuze
            /(media player classic|nero showtime)/i                             // Media Player Classic/Nero ShowTime
            ], [NAME], [

            /(nero (?:home|scout))\/((\d+)[\w\.-]+)/i                           // Nero Home/Nero Scout
            ], [NAME, VERSION], [

            /(nokia\d+)\/((\d+)[\w\.-]+)/i                                      // Nokia
            ], [NAME, VERSION], [

            /\s(songbird)\/((\d+)[\w\.-]+)/i                                    // Songbird/Philips-Songbird
            ], [NAME, VERSION], [

            /(winamp)3 version ((\d+)[\w\.-]+)/i,                               // Winamp
            /(winamp)\s((\d+)[\w\.-]+)/i,
            /(winamp)mpeg\/((\d+)[\w\.-]+)/i
            ], [NAME, VERSION], [

            /(ocms-bot|tapinradio|tunein radio|unknown|winamp|inlight radio)/i  // OCMS-bot/tap in radio/tunein/unknown/winamp (no other info)
                                                                                // inlight radio
            ], [NAME], [

            /(quicktime|rma|radioapp|radioclientapplication|soundtap|totem|stagefright|streamium)\/((\d+)[\w\.-]+)/i
                                                                                // QuickTime/RealMedia/RadioApp/RadioClientApplication/
                                                                                // SoundTap/Totem/Stagefright/Streamium
            ], [NAME, VERSION], [

            /(smp)((\d+)[\d\.]+)/i                                              // SMP
            ], [NAME, VERSION], [

            /(vlc) media player - version ((\d+)[\w\.]+)/i,                     // VLC Videolan
            /(vlc)\/((\d+)[\w\.-]+)/i,
            /(xbmc|gvfs|xine|xmms|irapp)\/((\d+)[\w\.-]+)/i,                    // XBMC/gvfs/Xine/XMMS/irapp
            /(foobar2000)\/((\d+)[\d\.]+)/i,                                    // Foobar2000
            /(itunes)\/((\d+)[\d\.]+)/i                                         // iTunes
            ], [NAME, VERSION], [

            /(wmplayer)\/((\d+)[\w\.-]+)/i,                                     // Windows Media Player
            /(windows-media-player)\/((\d+)[\w\.-]+)/i
            ], [[NAME, /-/g, ' '], VERSION], [

            /windows\/((\d+)[\w\.-]+) upnp\/[\d\.]+ dlnadoc\/[\d\.]+ (home media server)/i
                                                                                // Windows Media Server
            ], [VERSION, [NAME, 'Windows']], [

            /(com\.riseupradioalarm)\/((\d+)[\d\.]*)/i                          // RiseUP Radio Alarm
            ], [NAME, VERSION], [

            /(rad.io)\s((\d+)[\d\.]+)/i,                                        // Rad.io
            /(radio.(?:de|at|fr))\s((\d+)[\d\.]+)/i
            ], [[NAME, 'rad.io'], VERSION]

            //////////////////////
            // Media players END
            ////////////////////*/

        ],

        cpu : [[

            /(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i                     // AMD64
            ], [[ARCHITECTURE, 'amd64']], [

            /(ia32(?=;))/i                                                      // IA32 (quicktime)
            ], [[ARCHITECTURE, util.lowerize]], [

            /((?:i[346]|x)86)[;\)]/i                                            // IA32
            ], [[ARCHITECTURE, 'ia32']], [

            // PocketPC mistakenly identified as PowerPC
            /windows\s(ce|mobile);\sppc;/i
            ], [[ARCHITECTURE, 'arm']], [

            /((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i                           // PowerPC
            ], [[ARCHITECTURE, /ower/, '', util.lowerize]], [

            /(sun4\w)[;\)]/i                                                    // SPARC
            ], [[ARCHITECTURE, 'sparc']], [

            /((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i
                                                                                // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC
            ], [[ARCHITECTURE, util.lowerize]]
        ],

        device : [[

            /\((ipad|playbook);[\w\s\);-]+(rim|apple)/i                         // iPad/PlayBook
            ], [MODEL, VENDOR, [TYPE, TABLET]], [

            /applecoremedia\/[\w\.]+ \((ipad)/                                  // iPad
            ], [MODEL, [VENDOR, 'Apple'], [TYPE, TABLET]], [

            /(apple\s{0,1}tv)/i                                                 // Apple TV
            ], [[MODEL, 'Apple TV'], [VENDOR, 'Apple']], [

            /(archos)\s(gamepad2?)/i,                                           // Archos
            /(hp).+(touchpad)/i,                                                // HP TouchPad
            /(kindle)\/([\w\.]+)/i,                                             // Kindle
            /\s(nook)[\w\s]+build\/(\w+)/i,                                     // Nook
            /(dell)\s(strea[kpr\s\d]*[\dko])/i                                  // Dell Streak
            ], [VENDOR, MODEL, [TYPE, TABLET]], [

            /(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i                               // Kindle Fire HD
            ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [
            /(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i                  // Fire Phone
            ], [[MODEL, mapper.str, maps.device.amazon.model], [VENDOR, 'Amazon'], [TYPE, MOBILE]], [

            /\((ip[honed|\s\w*]+);.+(apple)/i                                   // iPod/iPhone
            ], [MODEL, VENDOR, [TYPE, MOBILE]], [
            /\((ip[honed|\s\w*]+);/i                                            // iPod/iPhone
            ], [MODEL, [VENDOR, 'Apple'], [TYPE, MOBILE]], [

            /(blackberry)[\s-]?(\w+)/i,                                         // BlackBerry
            /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|huawei|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i,
                                                                                // BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Huawei/Meizu/Motorola/Polytron
            /(hp)\s([\w\s]+\w)/i,                                               // HP iPAQ
            /(asus)-?(\w+)/i                                                    // Asus
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [
            /\(bb10;\s(\w+)/i                                                   // BlackBerry 10
            ], [MODEL, [VENDOR, 'BlackBerry'], [TYPE, MOBILE]], [
                                                                                // Asus Tablets
            /android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7)/i
            ], [MODEL, [VENDOR, 'Asus'], [TYPE, TABLET]], [

            /(sony)\s(tablet\s[ps])\sbuild\//i,                                  // Sony
            /(sony)?(?:sgp.+)\sbuild\//i
            ], [[VENDOR, 'Sony'], [MODEL, 'Xperia Tablet'], [TYPE, TABLET]], [
            /(?:sony)?(?:(?:(?:c|d)\d{4})|(?:so[-l].+))\sbuild\//i
            ], [[VENDOR, 'Sony'], [MODEL, 'Xperia Phone'], [TYPE, MOBILE]], [

            /\s(ouya)\s/i,                                                      // Ouya
            /(nintendo)\s([wids3u]+)/i                                          // Nintendo
            ], [VENDOR, MODEL, [TYPE, CONSOLE]], [

            /android.+;\s(shield)\sbuild/i                                      // Nvidia
            ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [

            /(playstation\s[3portablevi]+)/i                                    // Playstation
            ], [MODEL, [VENDOR, 'Sony'], [TYPE, CONSOLE]], [

            /(sprint\s(\w+))/i                                                  // Sprint Phones
            ], [[VENDOR, mapper.str, maps.device.sprint.vendor], [MODEL, mapper.str, maps.device.sprint.model], [TYPE, MOBILE]], [

            /(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i                         // Lenovo tablets
            ], [VENDOR, MODEL, [TYPE, TABLET]], [

            /(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i,                               // HTC
            /(zte)-(\w+)*/i,                                                    // ZTE
            /(alcatel|geeksphone|huawei|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i
                                                                                // Alcatel/GeeksPhone/Huawei/Lenovo/Nexian/Panasonic/Sony
            ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [

            /(nexus\s9)/i                                                       // HTC Nexus 9
            ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [

            /[\s\(;](xbox(?:\sone)?)[\s\);]/i                                   // Microsoft Xbox
            ], [MODEL, [VENDOR, 'Microsoft'], [TYPE, CONSOLE]], [
            /(kin\.[onetw]{3})/i                                                // Microsoft Kin
            ], [[MODEL, /\./g, ' '], [VENDOR, 'Microsoft'], [TYPE, MOBILE]], [

                                                                                // Motorola
            /\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i,
            /mot[\s-]?(\w+)*/i,
            /(XT\d{3,4}) build\//i
            ], [MODEL, [VENDOR, 'Motorola'], [TYPE, MOBILE]], [
            /android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i
            ], [MODEL, [VENDOR, 'Motorola'], [TYPE, TABLET]], [

            /android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n8000|sgh-t8[56]9|nexus 10))/i,
            /((SM-T\w+))/i
            ], [[VENDOR, 'Samsung'], MODEL, [TYPE, TABLET]], [                  // Samsung
            /((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-n900))/i,
            /(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i,
            /sec-((sgh\w+))/i
            ], [[VENDOR, 'Samsung'], MODEL, [TYPE, MOBILE]], [
            /(samsung);smarttv/i
            ], [VENDOR, MODEL, [TYPE, SMARTTV]], [

            /\(dtv[\);].+(aquos)/i                                              // Sharp
            ], [MODEL, [VENDOR, 'Sharp'], [TYPE, SMARTTV]], [
            /sie-(\w+)*/i                                                       // Siemens
            ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [

            /(maemo|nokia).*(n900|lumia\s\d+)/i,                                // Nokia
            /(nokia)[\s_-]?([\w-]+)*/i
            ], [[VENDOR, 'Nokia'], MODEL, [TYPE, MOBILE]], [

            /android\s3\.[\s\w;-]{10}(a\d{3})/i                                 // Acer
            ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [

            /android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i                     // LG Tablet
            ], [[VENDOR, 'LG'], MODEL, [TYPE, TABLET]], [
            /(lg) netcast\.tv/i                                                 // LG SmartTV
            ], [VENDOR, MODEL, [TYPE, SMARTTV]], [
            /(nexus\s[45])/i,                                                   // LG
            /lg[e;\s\/-]+(\w+)*/i
            ], [MODEL, [VENDOR, 'LG'], [TYPE, MOBILE]], [

            /android.+(ideatab[a-z0-9\-\s]+)/i                                  // Lenovo
            ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [

            /linux;.+((jolla));/i                                               // Jolla
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [

            /((pebble))app\/[\d\.]+\s/i                                         // Pebble
            ], [VENDOR, MODEL, [TYPE, WEARABLE]], [

            /android.+;\s(glass)\s\d/i                                          // Google Glass
            ], [MODEL, [VENDOR, 'Google'], [TYPE, WEARABLE]], [

            /android.+(\w+)\s+build\/hm\1/i,                                        // Xiaomi Hongmi 'numeric' models
            /android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,                   // Xiaomi Hongmi
            /android.+(mi[\s\-_]*(?:one|one[\s_]plus)?[\s_]*(?:\d\w)?)\s+build/i    // Xiaomi Mi
            ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, MOBILE]], [

            /(mobile|tablet);.+rv\:.+gecko\//i                                  // Unidentifiable
            ], [[TYPE, util.lowerize], VENDOR, MODEL]

            /*//////////////////////////
            // TODO: move to string map
            ////////////////////////////

            /(C6603)/i                                                          // Sony Xperia Z C6603
            ], [[MODEL, 'Xperia Z C6603'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [
            /(C6903)/i                                                          // Sony Xperia Z 1
            ], [[MODEL, 'Xperia Z 1'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [

            /(SM-G900[F|H])/i                                                   // Samsung Galaxy S5
            ], [[MODEL, 'Galaxy S5'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-G7102)/i                                                       // Samsung Galaxy Grand 2
            ], [[MODEL, 'Galaxy Grand 2'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-G530H)/i                                                       // Samsung Galaxy Grand Prime
            ], [[MODEL, 'Galaxy Grand Prime'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-G313HZ)/i                                                      // Samsung Galaxy V
            ], [[MODEL, 'Galaxy V'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-T805)/i                                                        // Samsung Galaxy Tab S 10.5
            ], [[MODEL, 'Galaxy Tab S 10.5'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [
            /(SM-G800F)/i                                                       // Samsung Galaxy S5 Mini
            ], [[MODEL, 'Galaxy S5 Mini'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
            /(SM-T311)/i                                                        // Samsung Galaxy Tab 3 8.0
            ], [[MODEL, 'Galaxy Tab 3 8.0'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [

            /(R1001)/i                                                          // Oppo R1001
            ], [MODEL, [VENDOR, 'OPPO'], [TYPE, MOBILE]], [
            /(X9006)/i                                                          // Oppo Find 7a
            ], [[MODEL, 'Find 7a'], [VENDOR, 'Oppo'], [TYPE, MOBILE]], [
            /(R2001)/i                                                          // Oppo YOYO R2001
            ], [[MODEL, 'Yoyo R2001'], [VENDOR, 'Oppo'], [TYPE, MOBILE]], [
            /(R815)/i                                                           // Oppo Clover R815
            ], [[MODEL, 'Clover R815'], [VENDOR, 'Oppo'], [TYPE, MOBILE]], [
             /(U707)/i                                                          // Oppo Find Way S
            ], [[MODEL, 'Find Way S'], [VENDOR, 'Oppo'], [TYPE, MOBILE]], [

            /(T3C)/i                                                            // Advan Vandroid T3C
            ], [MODEL, [VENDOR, 'Advan'], [TYPE, TABLET]], [
            /(ADVAN T1J\+)/i                                                    // Advan Vandroid T1J+
            ], [[MODEL, 'Vandroid T1J+'], [VENDOR, 'Advan'], [TYPE, TABLET]], [
            /(ADVAN S4A)/i                                                      // Advan Vandroid S4A
            ], [[MODEL, 'Vandroid S4A'], [VENDOR, 'Advan'], [TYPE, MOBILE]], [

            /(V972M)/i                                                          // ZTE V972M
            ], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [

            /(i-mobile)\s(IQ\s[\d\.]+)/i                                        // i-mobile IQ
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [
            /(IQ6.3)/i                                                          // i-mobile IQ IQ 6.3
            ], [[MODEL, 'IQ 6.3'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [
            /(i-mobile)\s(i-style\s[\d\.]+)/i                                   // i-mobile i-STYLE
            ], [VENDOR, MODEL, [TYPE, MOBILE]], [
            /(i-STYLE2.1)/i                                                     // i-mobile i-STYLE 2.1
            ], [[MODEL, 'i-STYLE 2.1'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [

            /(mobiistar touch LAI 512)/i                                        // mobiistar touch LAI 512
            ], [[MODEL, 'Touch LAI 512'], [VENDOR, 'mobiistar'], [TYPE, MOBILE]], [

            /////////////
            // END TODO
            ///////////*/

        ],

        engine : [[

            /windows.+\sedge\/([\w\.]+)/i                                       // EdgeHTML
            ], [VERSION, [NAME, 'EdgeHTML']], [

            /(presto)\/([\w\.]+)/i,                                             // Presto
            /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,     // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m
            /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,                          // KHTML/Tasman/Links
            /(icab)[\/\s]([23]\.[\d\.]+)/i                                      // iCab
            ], [NAME, VERSION], [

            /rv\:([\w\.]+).*(gecko)/i                                           // Gecko
            ], [VERSION, NAME]
        ],

        os : [[

            // Windows based
            /microsoft\s(windows)\s(vista|xp)/i                                 // Windows (iTunes)
            ], [NAME, VERSION], [
            /(windows)\snt\s6\.2;\s(arm)/i,                                     // Windows RT
            /(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
            ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
            /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
            ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [

            // Mobile/Embedded OS
            /\((bb)(10);/i                                                      // BlackBerry 10
            ], [[NAME, 'BlackBerry'], VERSION], [
            /(blackberry)\w*\/?([\w\.]+)*/i,                                    // Blackberry
            /(tizen)[\/\s]([\w\.]+)/i,                                          // Tizen
            /(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,
                                                                                // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki
            /linux;.+(sailfish);/i                                              // Sailfish OS
            ], [NAME, VERSION], [
            /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i                 // Symbian
            ], [[NAME, 'Symbian'], VERSION], [
            /\((series40);/i                                                    // Series 40
            ], [NAME], [
            /mozilla.+\(mobile;.+gecko.+firefox/i                               // Firefox OS
            ], [[NAME, 'Firefox OS'], VERSION], [

            // Console
            /(nintendo|playstation)\s([wids3portablevu]+)/i,                    // Nintendo/Playstation

            // GNU/Linux based
            /(mint)[\/\s\(]?(\w+)*/i,                                           // Mint
            /(mageia|vectorlinux)[;\s]/i,                                       // Mageia/VectorLinux
            /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?([\w\.-]+)*/i,
                                                                                // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
                                                                                // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus
            /(hurd|linux)\s?([\w\.]+)*/i,                                       // Hurd/Linux
            /(gnu)\s?([\w\.]+)*/i                                               // GNU
            ], [NAME, VERSION], [

            /(cros)\s[\w]+\s([\w\.]+\w)/i                                       // Chromium OS
            ], [[NAME, 'Chromium OS'], VERSION],[

            // Solaris
            /(sunos)\s?([\w\.]+\d)*/i                                           // Solaris
            ], [[NAME, 'Solaris'], VERSION], [

            // BSD based
            /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i                   // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
            ], [NAME, VERSION],[

            /(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i             // iOS
            ], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [

            /(mac\sos\sx)\s?([\w\s\.]+\w)*/i,
            /(macintosh|mac(?=_powerpc)\s)/i                                    // Mac OS
            ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [

            // Other
            /((?:open)?solaris)[\/\s-]?([\w\.]+)*/i,                            // Solaris
            /(haiku)\s(\w+)/i,                                                  // Haiku
            /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i,                               // AIX
            /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,
                                                                                // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS
            /(unix)\s?([\w\.]+)*/i                                              // UNIX
            ], [NAME, VERSION]
        ]
    };


    /////////////////
    // Constructor
    ////////////////


    var UAParser = function (uastring, extensions) {

        if (!(this instanceof UAParser)) {
            return new UAParser(uastring, extensions).getResult();
        }

        var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
        var rgxmap = extensions ? util.extend(regexes, extensions) : regexes;

        this.getBrowser = function () {
            var browser = mapper.rgx.apply(this, rgxmap.browser);
            browser.major = util.major(browser.version);
            return browser;
        };
        this.getCPU = function () {
            return mapper.rgx.apply(this, rgxmap.cpu);
        };
        this.getDevice = function () {
            return mapper.rgx.apply(this, rgxmap.device);
        };
        this.getEngine = function () {
            return mapper.rgx.apply(this, rgxmap.engine);
        };
        this.getOS = function () {
            return mapper.rgx.apply(this, rgxmap.os);
        };
        this.getResult = function() {
            return {
                ua      : this.getUA(),
                browser : this.getBrowser(),
                engine  : this.getEngine(),
                os      : this.getOS(),
                device  : this.getDevice(),
                cpu     : this.getCPU()
            };
        };
        this.getUA = function () {
            return ua;
        };
        this.setUA = function (uastring) {
            ua = uastring;
            return this;
        };
        this.setUA(ua);
        return this;
    };

    UAParser.VERSION = LIBVERSION;
    UAParser.BROWSER = {
        NAME    : NAME,
        MAJOR   : MAJOR, // deprecated
        VERSION : VERSION
    };
    UAParser.CPU = {
        ARCHITECTURE : ARCHITECTURE
    };
    UAParser.DEVICE = {
        MODEL   : MODEL,
        VENDOR  : VENDOR,
        TYPE    : TYPE,
        CONSOLE : CONSOLE,
        MOBILE  : MOBILE,
        SMARTTV : SMARTTV,
        TABLET  : TABLET,
        WEARABLE: WEARABLE,
        EMBEDDED: EMBEDDED
    };
    UAParser.ENGINE = {
        NAME    : NAME,
        VERSION : VERSION
    };
    UAParser.OS = {
        NAME    : NAME,
        VERSION : VERSION
    };


    ///////////
    // Export
    //////////


    // check js environment
    if (typeof(exports) !== UNDEF_TYPE) {
        // nodejs env
        if (typeof module !== UNDEF_TYPE && module.exports) {
            exports = module.exports = UAParser;
        }
        exports.UAParser = UAParser;
    } else {
        // requirejs env (optional)
        if (typeof(define) === FUNC_TYPE && define.amd) {
            define(function () {
                return UAParser;
            });
        } else {
            // browser env
            window.UAParser = UAParser;
        }
    }

    // jQuery/Zepto specific (optional)
    // Note:
    //   In AMD env the global scope should be kept clean, but jQuery is an exception.
    //   jQuery always exports to global scope, unless jQuery.noConflict(true) is used,
    //   and we should catch that.
    var $ = window.jQuery || window.Zepto;
    if (typeof $ !== UNDEF_TYPE) {
        var parser = new UAParser();
        $.ua = parser.getResult();
        $.ua.get = function() {
            return parser.getUA();
        };
        $.ua.set = function (uastring) {
            parser.setUA(uastring);
            var result = parser.getResult();
            for (var prop in result) {
                $.ua[prop] = result[prop];
            }
        };
    }

})(typeof window === 'object' ? window : this);


window.averta = {};

;(function($){

    //"use strict";

    window.package = function(name){
        if(!window[name]) window[name] = {};
    };

    var extend = function(target , object){
        for(var key in object)  target[key] = object[key];
    };

    Function.prototype.extend = function(superclass){
        if(typeof superclass.prototype.constructor === "function"){
            extend(this.prototype , superclass.prototype);
            this.prototype.constructor = this;
        }else{
            this.prototype.extend(superclass);
            this.prototype.constructor = this;
        }
    };

    // Converts JS prefix to CSS prefix
    var trans = {
        'Moz'    : '-moz-',
        'Webkit' : '-webkit-',
        'Khtml'  : '-khtml-' ,
        'O'      : '-o-',
        'ms'     : '-ms-',
        'Icab'   : '-icab-'
    };

    window._mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    window._touch  = 'ontouchstart' in document;

    // Thanks to LEA VEROU
    // http://lea.verou.me/2009/02/find-the-vendor-prefix-of-the-current-browser/
    function getVendorPrefix() {

        if('result' in arguments.callee) return arguments.callee.result;

        var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/;

        var someScript = document.getElementsByTagName('script')[0];

        for(var prop in someScript.style){
            if(regex.test(prop)){
                return arguments.callee.result = prop.match(regex)[0];
            }
        }

        if('WebkitOpacity' in someScript.style) return arguments.callee.result = 'Webkit';
        if('KhtmlOpacity' in someScript.style) return arguments.callee.result = 'Khtml';

        return arguments.callee.result = '';
    }


    // Thanks to Steven Benner.
    // http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
    window.parseQueryString = function(url){
        var queryString = {};
        url.replace(
            new RegExp("([^?=&]+)(=([^&]*))?", "g"),
            function($0, $1, $2, $3) { queryString[$1] = $3; }
        );

        return queryString;
    };

    function checkStyleValue(prop){
         var b = document.body || document.documentElement;
        var s = b.style;
        var p = prop;
        if(typeof s[p] == 'string') {return true; }

        // Tests for vendor specific prop
        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;
    }

    function supportsTransitions() {
       return checkStyleValue('transition');
    }

    function supportsTransforms(){
       return checkStyleValue('transform');
    }

    function supports3DTransforms(){
        if(!supportsTransforms()) return false;
        var el = document.createElement('i'),
        has3d,
        transforms = {
            'WebkitTransform':'-webkit-transform',
            'OTransform':'-o-transform',
            'MSTransform':'-ms-transform',
            'msTransform':'-ms-transform',
            'MozTransform':'-moz-transform',
            'Transform':'transform',
            'transform':'transform'
        };

        el.style.display = 'block';

        // Add it to the body to get the computed style
        document.body.insertBefore(el, null);

        for(var t in transforms){
            if( el.style[t] !== undefined ){
                el.style[t] = 'translate3d(1px,1px,1px)';
                has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
            }
        }

        document.body.removeChild(el);

        return (has3d != null && has3d.length > 0 && has3d !== "none");
    }


    // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
    // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
    // MIT license

    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];

    for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x ) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame  = window[vendors[x]+'CancelAnimationFrame']
                                    || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if ( !window.requestAnimationFrame ) {
        window.requestAnimationFrame = function ( callback, element ) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    }

    if ( !window.cancelAnimationFrame ) {
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
    }

    if (!window.getComputedStyle) {
        window.getComputedStyle = function(el, pseudo) {
            this.el = el;
            this.getPropertyValue = function(prop) {
                var re = /(\-([a-z]){1})/g;
                if (prop == 'float') prop = 'styleFloat';
                if (re.test(prop)) {
                    prop = prop.replace(re, function () {
                        return arguments[2].toUpperCase();
                    });
                }
                return el.currentStyle[prop] ? el.currentStyle[prop] : null;
            };
            return el.currentStyle;
        };
    }

    // IE8 Array indexOf fix
    if (!Array.prototype.indexOf) {
      Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length >>> 0;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
        if (from < 0)
          from += len;

        for (; from < len; from++)
        {
          if (from in this &&
              this[from] === elt)
            return from;
        }
        return -1;
      };
    }

    $.removeDataAttrs = function($target, exclude) {
        var i,
            attrName,
            dataAttrsToDelete = [],
            dataAttrs = $target[0].attributes,
            dataAttrsLen = dataAttrs.length;

        exclude = exclude || [];

        // loop through attributes and make a list of those
        // that begin with 'data-'
        for (i=0; i<dataAttrsLen; i++) {
            attrName = dataAttrs[i].name;
            if ( 'data-' === attrName.substring(0,5) && exclude.indexOf(attrName) === -1 ) {
                // Why don't you just delete the attributes here?
                // Deleting an attribute changes the indices of the
                // others wreaking havoc on the loop we are inside
                // b/c dataAttrs is a NamedNodeMap (not an array or obj)
                dataAttrsToDelete.push(dataAttrs[i].name);
            }
        }
        // delete each of the attributes we found above
        // i.e. those that start with "data-"
        $.each( dataAttrsToDelete, function( index, attrName ) {
            $target.removeAttr( attrName );
        })
    };

    /* ----------------------------------------------------------------------------------- */
    // based on jQuery browser object
    (function(){

        window.AuxUserAgent = new UAParser().getResult();
        var browser = AuxUserAgent.browser;


        /**
         * check ie browser
         * @param  {Number | string}  version
         * @return {Boolean}
         */
        browser.isMSIE = function ( version ) {
            if ( !browser.msie ) {
                return false;
            } else if ( !version ) {
                return true;
            }
            var ieVer = browser.version.slice(0 , browser.version.indexOf('.'));
            if ( typeof version === 'string' ) {
                if ( version.indexOf('<') !== -1  || version.indexOf('>') !== -1) {
                    return eval( ieVer + version );
                } else {
                    return eval( version + '==' + ieVer );
                }
            } else {
                return version == ieVer;
            }
        }

        browser.webkit  = AuxUserAgent.engine.name === 'WebKit';
        browser.firefox = browser.name === 'Firefox';
        browser.opera   = browser.name === 'Opera';
        browser.chrome  = browser.name === 'Chrome';
        browser.safari  = browser.name === 'Safari';
        browser.msie    = browser.name === 'IE';

        averta.browser = browser;
        window.AuxBrowser = browser;

    })();

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

    if ( $ ) {
        $.fn.preloadImg = function(src , _event){
            this.each(function(){
                var $this = $(this);
                var self  = this;
                var img = new Image();
                img.onload = function(event){
                    if(event == null) event = {}; // IE8
                    $this.attr('src' , src);
                    event.width = img.width;
                    event.height = img.height;
                    $this.data('width', img.width);
                    $this.data('height', img.height);
                    setTimeout(function(){_event.call(self , event);},50);
                    img = null;
                };
                img.src = src;
            });
            return this;
        };

        $(document).ready(function(){
            window._jcsspfx         = getVendorPrefix();       // JS CSS VendorPrefix
            window._csspfx          = trans[window._jcsspfx];  // CSS VendorPrefix
            window._cssanim         = supportsTransitions();
            window._css3d           = supports3DTransforms();
            window._css2d           = supportsTransforms();
        });
    }

    /* ------------------------------------------------------------------------------ */
    /*\
    |*|
    |*|  Polyfill which enables the passage of arbitrary arguments to the
    |*|  callback functions of JavaScript timers (HTML5 standard syntax).
    |*|
    |*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
    |*|
    |*|  Syntax:
    |*|  var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
    |*|  var timeoutID = window.setTimeout(code, delay);
    |*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
    |*|  var intervalID = window.setInterval(code, delay);
    |*|
    \*/

    (function() {
      setTimeout(function(arg1) {
        if (arg1 === 'test') {
          // feature test is passed, no need for polyfill
          return;
        }
        var __nativeST__ = window.setTimeout;
        window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
          var aArgs = Array.prototype.slice.call(arguments, 2);
          return __nativeST__(vCallback instanceof Function ? function() {
            vCallback.apply(null, aArgs);
          } : vCallback, nDelay);
        };
      }, 0, 'test');

      var interval = setInterval(function(arg1) {
        clearInterval(interval);
        if (arg1 === 'test') {
          // feature test is passed, no need for polyfill
          return;
        }
        var __nativeSI__ = window.setInterval;
        window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
          var aArgs = Array.prototype.slice.call(arguments, 2);
          return __nativeSI__(vCallback instanceof Function ? function() {
            vCallback.apply(null, aArgs);
          } : vCallback, nDelay);
        };
      }, 0, 'test');
    }());

})(jQuery);


/* -------------------- src/averta-js-timer.js -------------------- */


/**
 *  Ticker Class
 *  Author: Averta Ltd
 */

;(function(){
    "use strict";

    averta.Ticker = function(){};

    var st = averta.Ticker,
        list = [],
        len = 0,
        __stopped = true;

    st.add = function (listener , ref){
        list.push([listener , ref]);

        if(list.length === 1) st.start();
        len = list.length;
        return len;
    };

    st.remove = function (listener , ref) {
        for(var i = 0 , l = list.length ; i<l ; ++i){
            if(list[i] && list[i][0] === listener && list[i][1] === ref){
                list.splice(i , 1);
            }
        }

        len = list.length;

        if( len === 0 ){
            st.stop();
        }
    };

    st.start = function (){
        if(!__stopped) return;
        __stopped = false;
        __tick();
    };

    st.stop = function (){
        __stopped = true;
    };

    var __tick = function () {
        if(st.__stopped) return;
        var item;
        for(var i = 0; i!==len; i++){
            item = list[i];
            item[0].call(item[1]);
        }

        requestAnimationFrame(__tick);
    };

})();

/**
 *  Timer Class
 *  Author: Averta Ltd
 */
;(function(){
    "use strict";

    if(!Date.now){
        Date.now = function(){
            return new Date().getTime();
        };
    }

    averta.Timer = function(delay , autoStart) {
        this.delay = delay;
        this.currentCount = 0;
        this.paused = false;
        this.onTimer = null;
        this.refrence = null;

        if(autoStart) this.start();

    };

    averta.Timer.prototype = {

        constructor : averta.Timer,

        start : function(){
            this.paused = false;
            this.lastTime = Date.now();
            averta.Ticker.add(this.update , this);
        },

        stop : function(){
            this.paused = true;
            averta.Ticker.remove(this.update , this);
        },

        reset : function(){
            this.currentCount = 0;
            this.paused = true;
            this.lastTime = Date.now();
        },

        update : function(){
            if(this.paused || Date.now() - this.lastTime < this.delay) return;
            this.currentCount ++;
            this.lastTime = Date.now();
            if(this.onTimer)
                this.onTimer.call(this.refrence , this.getTime());

        } ,

        getTime : function(){
            return this.delay * this.currentCount;
        }

    };
})();


/* -------------------- src/averta-js-eventdispatcher.js -------------------- */


;(function(){

    "use strict";

    averta.EventDispatcher = function(){
        this.listeners = {};
    };

    averta.EventDispatcher.extend = function(_proto){
        var instance = new averta.EventDispatcher();
        for(var key in instance)
            if(key != 'constructor') _proto[key] =  averta.EventDispatcher.prototype[key];
    };

    averta.EventDispatcher.prototype = {

        constructor : averta.EventDispatcher,

        addEventListener : function(event , listener , ref){
            if(!this.listeners[event]) this.listeners[event] = [];
            this.listeners[event].push({listener:listener , ref:ref});

        },

        removeEventListener : function(event , listener , ref){
            if(this.listeners[event]){

                for(var i = 0; i < this.listeners[event].length ; ++i){

                    if(listener === this.listeners[event][i].listener && ref === this.listeners[event][i].ref){
                        this.listeners[event].splice(i--,1);
                    }
                }

                if (this.listeners[event].length === 0){
                    this.listeners[event] = null;
                }
            }
        },

        dispatchEvent : function (event) {
            event.target = this;
            if(this.listeners[event.type]){
                for(var i = 0 , l = this.listeners[event.type].length; i < l ; ++i){
                    this.listeners[event.type][i].listener.call(this.listeners[event.type][i].ref , event);
                }
            }
        }
    };

})();


/* -------------------- src/averta-js-touchswipe.js -------------------- */


;(function( window, document, undefined ){

    "use strict";

    var isTouch     = 'ontouchstart' in document,
        isPointer   = window.navigator.pointerEnabled,
        isMSPoiner  = !isPointer && window.navigator.msPointerEnabled,
        usePointer  = isPointer || isMSPoiner,

    // Events
    ev_start  = (isPointer ? 'pointerdown ' : '' ) + (isMSPoiner ? 'MSPointerDown ' : '' ) + (isTouch ? 'touchstart ' : '' ) + 'mousedown',
    ev_move   = (isPointer ? 'pointermove ' : '' ) + (isMSPoiner ? 'MSPointerMove ' : '' ) + (isTouch ? 'touchmove '  : '' ) + 'mousemove',
    ev_end    = (isPointer ? 'pointerup '   : '' ) + (isMSPoiner ? 'MSPointerUp '   : '' ) + (isTouch ? 'touchend '   : '' ) + 'mouseup',
    ev_cancel = (isPointer ? 'pointercancel '   : '' ) + (isMSPoiner ? 'MSPointerCancel ': '' ) + 'touchcancel';


    averta.TouchSwipe = function(element){
        if ( element.jquery ) {
            if ( !element.length ) {
                return;
            }

            element = element[0];
        }
        this.element = element;
        this.enabled = true;

        this._bindEvents( element, ev_start, this._touchStart );

        element.swipe = this;

        this.onSwipe    = null;
        this.swipeType  = 'horizontal';
        this.noSwipeSelector = 'input, textarea, button, .no-swipe, .ms-no-swipe';

        this.lastStatus = {};

    };

    var p = averta.TouchSwipe.prototype;

    /*-------------- METHODS --------------*/

    p._bindEvents = function( target, events, cb ) {
        events.split( ' ' ).forEach( function( event ){
            target.addEventListener( event, cb.bind( this ) );
        }, this );
    };

    p._unbindEvents = function( target, events, cb ) {
        events.split( ' ' ).forEach( function( event ){
            target.removeEventListener( event, cb.bind( this ) );
        }, this );
    };

    p._getDirection = function(new_x , new_y){
        switch(this.swipeType){
            case 'horizontal':
                return new_x <= this.start_x ? 'left' : 'right';
            break;
            case 'vertical':
                return new_y <= this.start_y ? 'up' : 'down';
            break;
            case 'all':
                if(Math.abs(new_x - this.start_x) > Math.abs(new_y - this.start_y))
                    return new_x <= this.start_x ? 'left' : 'right';
                else
                    return new_y <= this.start_y ? 'up' : 'down';
            break;
        }
    };

    p._priventDefultEvent = function(new_x , new_y){
        //if(this.priventEvt != null) return this.priventEvt;
        var dx = Math.abs(new_x - this.start_x);
        var dy = Math.abs(new_y - this.start_y);

        var horiz =  dx > dy;

        return (this.swipeType === 'horizontal' && horiz) ||
               (this.swipeType === 'vertical' && !horiz);

        //return this.priventEvt;
    };

    p._createStatusObject = function(evt){
        var status_data = {} , temp_x , temp_y;

        temp_x = this.lastStatus.distanceX || 0;
        temp_y = this.lastStatus.distanceY || 0;

        status_data.distanceX = evt.pageX - this.start_x;
        status_data.distanceY = evt.pageY - this.start_y;
        status_data.moveX = status_data.distanceX - temp_x;
        status_data.moveY = status_data.distanceY - temp_y;

        status_data.distance  = parseInt( Math.sqrt(Math.pow(status_data.distanceX , 2) + Math.pow(status_data.distanceY , 2)) );

        status_data.duration  = new Date().getTime() - this.start_time;
        status_data.direction = this._getDirection(evt.pageX , evt.pageY);

        return status_data;
    };

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

    p._reset = function( event ) {
        this.reset = false;
        this.lastStatus = {};
        this.start_time = new Date().getTime();
        this.start_x = isTouch ? event.touches[0].pageX : event.pageX;
        this.start_y = isTouch ? event.touches[0].pageY : event.pageY;
    };

    p._touchStart = function( event ) {
        if ( !this.enabled ) {
            return;
        }

        if ( event.target.closest(this.noSwipeSelector, this.$element) ) {
            return;
        }

        if ( usePointer ) {
            this.element.style.msTouchAction = this.swipeType === 'horizontal' ? 'pan-y' : 'pan-x';
        }

        if ( !this.onSwipe ) {
            console.log( 'Swipe listener is undefined' );
            return;
        }

        if ( this.touchStarted ) {
            return;
        }

        var swipeEvent = isTouch ? event.touches[0] : event;

        this.start_x = swipeEvent.pageX;
        this.start_y = swipeEvent.pageY;

        this.start_time = new Date().getTime();

        this._bindEvents( document, ev_end,    this._touchEnd );
        this._bindEvents( document, ev_move,   this._touchMove );
        this._bindEvents( document, ev_cancel, this._touchCancel );

        var status = this._createStatusObject( swipeEvent );
        status.phase = 'start';

        this.onSwipe.call( null , status );

        if( !isTouch ) {
            event.preventDefault();
        }

        this.lastStatus = status;
        this.touchStarted = true;
    };

    p._touchMove = function( event ) {

        if ( !this.touchStarted ) return;

        clearTimeout(this.timo);

        this.timo = setTimeout( function() {
            this._reset(event);
        }, 60);

        var swipeEvent = isTouch ? event.touches[0] : event;
        var status = this._createStatusObject( swipeEvent );

        if ( this._priventDefultEvent( swipeEvent.pageX ,  swipeEvent.pageY ) ) {
            event.preventDefault();
        }

        status.phase = 'move';

        //if(this.lastStatus.direction !== status.direction) this._reset(event , jqevt);

        this.lastStatus = status;

        this.onSwipe.call( null , status );
    };

    p._touchEnd = function( event ) {

        clearTimeout(this.timo);

        var swipeEvent = isTouch ? event.touches[0] : event;
        var status = this.lastStatus;

        if ( !isTouch ){
            event.preventDefault();
        }

        status.phase = 'end';

        this.touchStarted = false;
        this.priventEvt   = null;

        this._unbindEvents( document ,ev_end     , this._touchEnd);
        this._unbindEvents( document ,ev_move    , this._touchMove);
        this._unbindEvents( document ,ev_cancel  , this._touchCancel);

        status.speed = status.distance / status.duration;

        this.onSwipe.call( null, status );
    };

    p._touchCancel = function( event ) {
        this._touchEnd( event );
    };

    p.enable = function(){
        this.enabled = true;
    };

    p.disable = function(){
        this.enabled = false;
    };

})( window, document );

/* ------------------------------------------------------------------------------ */
// Element.closest polyfill
// From https://github.com/jonathantneal/closest
(function (ElementProto) {
    if (typeof ElementProto.matches !== 'function') {
        ElementProto.matches = ElementProto.msMatchesSelector || ElementProto.mozMatchesSelector || ElementProto.webkitMatchesSelector || function matches(selector) {
            var element = this;
            var elements = (element.document || element.ownerDocument).querySelectorAll(selector);
            var index = 0;

            while (elements[index] && elements[index] !== element) {
                ++index;
            }

            return Boolean(elements[index]);
        };
    }

    if (typeof ElementProto.closest !== 'function') {
        ElementProto.closest = function closest(selector) {
            var element = this;

            while (element && element.nodeType === 1) {
                if (element.matches(selector)) {
                    return element;
                }

                element = element.parentNode;
            }

            return null;
        };
    }
})(window.Element.prototype);
/* ------------------------------------------------------------------------------ */
;


/* -------------------- src/averta-js-aligner.js -------------------- */


;(function(){

    "use strict";

    window.AVTAligner = function(type , $container , $img, options ){

        this.$container = $container;
        this.$img       = $img;
        this.img        = $img[0];
        this.options    = options || {};
        this.type       = type || 'stretch'; // fill , fit , stretch , tile , center

        this.widthOnly = false;
        this.heightOnly = false;
    };

    var p = AVTAligner.prototype;

    /*-------------- METHODS --------------*/

    p.init = function(w , h){

        w = w || this.img.naturalWidth;
        h = h || this.img.naturalHeight;


        this.baseWidth = w;
        this.baseHeight = h;
        this.imgRatio = w / h;
        this.imgRatio2 = h / w;

        switch(this.type){
            case 'tile':
                this.$container.css('background-image' , 'url('+ this.$img.attr('src') +')');
                this.$img.hide();
            break;
            case 'center':
                this.$container.css('background-image' , 'url('+ this.$img.attr('src') +')');
                this.$container.css({
                    backgroundPosition  : 'center center',
                    backgroundRepeat    : 'no-repeat'
                });
                this.$img.hide();
            break;
            case 'stretch':
                this.$img.css({
                    width   :   '100%',
                    height  :   '100%'
                });
            break;
            case 'fill':
            case 'fit' :
                this.needAlign = true;
                this.align();
            break;
        }

        if ( this.options.srcset ) {
            this.$img.on('load', function( e ){
                // update aspects and realign image
                var img = e.target,
                    w = img.naturalWidth  || this.$img.width(),
                    h = img.naturalHeight || this.$image.height();

                    this.baseWidth = w;
                    this.baseHeight = h;
                    this.imgRatio = w / h;
                    this.imgRatio2 = h / w;

                    this.align();
            }.bind(this));
        }
    };

    p.align = function(){
        if(!this.needAlign) return;

        this.cont_w = this.options.containerWidth  ? this.options.containerWidth()  : this.$container.width();
        this.cont_h = this.options.containerHeight ? this.options.containerHeight() : this.$container.height();

        var contRatio = this.cont_w / this.cont_h;

        if(this.type == 'fill'){
            if(this.imgRatio < contRatio ){
                this.$img.width(this.cont_w);
                this.$img.height(this.cont_w * this.imgRatio2);
            }else{
                this.$img.height(this.cont_h);
                this.$img.width(this.cont_h * this.imgRatio);
            }

        }else if(this.type == 'fit'){

            if(this.imgRatio < contRatio){
                this.$img.height(this.cont_h);
                this.$img.width(this.cont_h * this.imgRatio);
            }else{
                this.$img.width(this.cont_w);
                this.$img.height(this.cont_w * this.imgRatio2);
            }
        }

        this.setMargin();

    };

    p.setMargin = function(){

        var position = this.options.position || 'cm',
            img = this.$img[0];


        switch( position.charAt(0) ) {
            case 'l':
                img.style.marginLeft = 0;
                break;
            case 'r':
                img.style.marginLeft = this.cont_w - img.offsetWidth + 'px';
                break;
            case 'c':
            default:
                img.style.marginLeft = (this.cont_w - img.offsetWidth ) / 2 + 'px';
        }


        switch( position.charAt(1) ) {
            case 't':
                img.style.marginTop = 0;
                break;
            case 'b':
                img.style.marginTop = this.cont_h - img.offsetHeight + 'px';
                break;
            case 'm':
            default:
                img.style.marginTop = (this.cont_h - img.offsetHeight ) / 2 + 'px';
        }
    };

})();


/* -------------------- src/averta-js-csstweener.js -------------------- */


;(function(){

    "use strict";

    var evt = null;

    window.CSSTween = function(element , duration , delay , ease){
        if ( element.jquery ) {
            if ( !element.length ) {
                return;
            }

            element = element[0];
        }

        this.element    = element;
        this.duration   = duration  || 1000;
        this.delay      = delay     || 0;
        this.ease       = ease      || 'linear';

        /*if(!evt){
            if(window._jcsspfx === 'O')
                evt = 'otransitionend';
            else if(window._jcsspfx == 'Webkit')
                evt = 'webkitTransitionEnd';
            else
                evt = 'transitionend' ;
        }*/

    };

    var p = CSSTween.prototype;

    /*-------------- METHODS --------------*/

    p.to = function(callback , target){
        this.to_cb          = callback;
        this.to_cb_target   = target;

        return this;
    };

    p.from = function(callback , target ){
        this.fr_cb          = callback;
        this.fr_cb_target   = target;

        return this;
    };

    p.onComplete = function(callback ,target){
        this.oc_fb          = callback;
        this.oc_fb_target   = target;

        return this;
    };

    p.chain = function(csstween){
        this.chained_tween = csstween;
        return this;
    };

    p.reset = function(){
        //element.removeEventListener(evt , this.onTransComplete , true);
        clearTimeout(this.start_to);
        clearTimeout(this.end_to);
    };

    p.start = function(){
        var element = this.element;

        clearTimeout(this.start_to);
        clearTimeout(this.end_to);

        this.fresh = true;

        if(this.fr_cb){
            element.style[window._jcsspfx + 'TransitionDuration'] = '0ms';
            this.fr_cb.call(this.fr_cb_target);
        }

        var that = this;

        this.onTransComplete = function(event){

            if(!that.fresh) return;

            //that.$element[0].removeEventListener(evt , this.onTransComplete, true);
            //event.stopPropagation();

            that.reset();

            element.style[window._jcsspfx + 'TransitionDuration'] = '';
            element.style[window._jcsspfx + 'TransitionProperty'] = '';
            element.style[window._jcsspfx + 'TransitionTimingFunction'] = '';
            element.style[window._jcsspfx + 'TransitionDelay'] = '';

            that.fresh = false;
            if(that.chained_tween) that.chained_tween.start();
            if(that.oc_fb)  that.oc_fb.call(that.oc_fb_target);

        };

        this.start_to = setTimeout(function(){
            if ( !that.element ) return;
            element.style[window._jcsspfx + 'TransitionDuration'] = that.duration + 'ms';
            element.style[window._jcsspfx + 'TransitionProperty'] = that.transProperty || 'all';

            if(that.delay > 0)  element.style[window._jcsspfx + 'TransitionDelay'] = that.delay + 'ms';
            else                element.style[window._jcsspfx + 'TransitionDelay'] = '';

            element.style[window._jcsspfx + 'TransitionTimingFunction'] = that.ease;

            if(that.to_cb)  that.to_cb.call(that.to_cb_target);

            //that.$element[0].addEventListener(evt , that.onTransComplete , true );

            that.end_to = setTimeout(function(){that.onTransComplete();} , that.duration + (that.delay || 0));
        } , 10);

        return this;
    };

})();

/**
 *  Cross Tween Class
 */
;(function(){

    "use strict";

    var _cssanim = null;
    window.CTween = {};

    CTween.animate = function(element , duration , properties , options){
        if(_cssanim == null) _cssanim = window._cssanim;

        options = options || {};

        if(_cssanim){
            var tween = new CSSTween(element , duration , options.delay , EaseDic[options.ease]);
            if ( options.transProperty ) {
                tween.transProperty = options.transProperty;
            }
            tween.to(function(){ element.css(properties);});
            if(options.complete) tween.onComplete(options.complete , options.target);
            tween.start();
            tween.stop = tween.reset;
            return tween;
        }

        var onCl;

        if(options.delay) element.delay(options.delay);
        if(options.complete)
            onCl = function(){
                options.complete.call(options.target);
            };

        element.stop(true).animate(properties , duration , options.ease || 'linear' , onCl);

        return element;
    };

    CTween.fadeOut = function(target , duration , remove) {
        var options = {};
        if(remove === true) {
            options.complete = function(){target.remove();};
        } else if ( remove === 2 ) {
            options.complete = function(){target.css('display', 'none');};
        }

        CTween.animate(target , duration || 1000 , {opacity : 0} , options);
    };

    CTween.fadeIn = function(target , duration, reset){
        if( reset !== false ) {
            target.css('opacity' , 0).css('display', '');
        }

        CTween.animate(target , duration || 1000 , {opacity : 1});
    };

})();

;(function(){

    // Thanks to matthewlein
    // https://github.com/matthewlein/Ceaser

    window.EaseDic = {
        'linear'            : 'linear',
        'ease'              : 'ease',
        'easeIn'            : 'ease-in',
        'easeOut'           : 'ease-out',
        'easeInOut'         : 'ease-in-out',

        'easeInCubic'       : 'cubic-bezier(.55,.055,.675,.19)',
        'easeOutCubic'      : 'cubic-bezier(.215,.61,.355,1)',
        'easeInOutCubic'    : 'cubic-bezier(.645,.045,.355,1)',
        'easeInCirc'        : 'cubic-bezier(.6,.04,.98,.335)',
        'easeOutCirc'       : 'cubic-bezier(.075,.82,.165,1)',
        'easeInOutCirc'     : 'cubic-bezier(.785,.135,.15,.86)',
        'easeInExpo'        : 'cubic-bezier(.95,.05,.795,.035)',
        'easeOutExpo'       : 'cubic-bezier(.19,1,.22,1)',
        'easeInOutExpo'     : 'cubic-bezier(1,0,0,1)',
        'easeInQuad'        : 'cubic-bezier(.55,.085,.68,.53)',
        'easeOutQuad'       : 'cubic-bezier(.25,.46,.45,.94)',
        'easeInOutQuad'     : 'cubic-bezier(.455,.03,.515,.955)',
        'easeInQuart'       : 'cubic-bezier(.895,.03,.685,.22)',
        'easeOutQuart'      : 'cubic-bezier(.165,.84,.44,1)',
        'easeInOutQuart'    : 'cubic-bezier(.77,0,.175,1)',
        'easeInQuint'       : 'cubic-bezier(.755,.05,.855,.06)',
        'easeOutQuint'      : 'cubic-bezier(.23,1,.32,1)',
        'easeInOutQuint'    : 'cubic-bezier(.86,0,.07,1)',
        'easeInSine'        : 'cubic-bezier(.47,0,.745,.715)',
        'easeOutSine'       : 'cubic-bezier(.39,.575,.565,1)',
        'easeInOutSine'     : 'cubic-bezier(.445,.05,.55,.95)',
        'easeInBack'        : 'cubic-bezier(.6,-.28,.735,.045)',
        'easeOutBack'       : 'cubic-bezier(.175, .885,.32,1.275)',
        'easeInOutBack'     : 'cubic-bezier(.68,-.55,.265,1.55)'
    };
})();


/* -------------------- src/averta-js-slickcontroller.js -------------------- */


/**
 *  Slick controller
 *  version 1.1.2
 *
 *  @author averta
 *
 *  Copyright © 2015, Averta Ltd. All rights reserved.
 */

;(function(){

    "use strict";

    var _options = {
        bouncing            : true,
        snapping            : false,
        snapsize            : null,
        friction            : 0.05,
        outFriction         : 0.05,
        outAcceleration     : 0.09,
        minValidDist        : 0.3,
        snappingMinSpeed    : 2,
        paging              : false,
        endless             : false,
        maxSpeed            : 160
    };


    var SlickController = function(min , max , options){

        if(max === null || min === null) {
            throw new Error('Max and Min values are required.');
        }

        this.options = options || {};

        for(var key in _options){
            if(!(key in this.options))
                this.options[key] = _options[key];
        }

        this._max_value     = max;
        this._min_value     = min;

        this.value          = min;
        this.end_loc        = min;

        this.current_snap   = this.getSnapNum(min);

        this.__extrStep     = 0;
        this.__extraMove    = 0;

        this.__animID       = -1;

    };

    var p = SlickController.prototype;

    /*
    ---------------------------------------------------
        PUBLIC METHODS
    ----------------------------------------------------
    */


    p.changeTo = function(value , animate , speed , snap_num , dispatch) {
        this.stopped = false;
        this._internalStop();
        value = this._checkLimits(value);
        speed = Math.abs(speed || 0);

        if(this.options.snapping){
            snap_num = snap_num || this.getSnapNum(value);
            if( dispatch !== false )this._callsnapChange(snap_num);
            this.current_snap = snap_num;
        }

        if(animate){
            this.animating = true;

            var self = this,
                active_id = ++self.__animID,
                amplitude = value - self.value,
                timeStep = 0,
                targetPosition = value,
                animFrict = 1 - self.options.friction,
                timeconst = animFrict + (speed - 20)  * animFrict * 1.3 / self.options.maxSpeed;

            var tick = function(){

                if(active_id !== self.__animID) return;

                var dis =  value - self.value;

                if( Math.abs(dis) > self.options.minValidDist && self.animating ){
                    window.requestAnimationFrame(tick);
                } else {

                    if( self.animating ){
                        self.value = value;
                        self._callrenderer();
                    }

                    self.animating = false;

                    if( active_id !== self.__animID ){
                        self.__animID = -1;
                    }

                    self._callonComplete('anim');

                    return;
                }

                //self.value += dis * timeconst
                self.value = targetPosition - amplitude * Math.exp(-++timeStep * timeconst);

                self._callrenderer();
            };

            tick();

            return;
        }

        this.value = value;
        this._callrenderer();
    };

    p.drag = function(move){

        if(this.start_drag){
            this.drag_start_loc  = this.value;
            this.start_drag = false;
        }

        this.animating      = false;
        this._deceleration  = false;

        this.value -= move;

        if ( !this.options.endless && (this.value > this._max_value || this.value < 0)) {
            if (this.options.bouncing) {
                this.__isout = true;
                this.value += move * 0.6;
            } else if (this.value > this._max_value) {
                this.value = this._max_value;
            } else {
                this.value = 0;
            }
        }else if(!this.options.endless && this.options.bouncing){
                this.__isout = false;
        }

        this._callrenderer();

    };

    p.push = function(speed){
        this.stopped = false;
        if(this.options.snapping && Math.abs(speed) <= this.options.snappingMinSpeed){
            this.cancel();
            return;
        }

        this.__speed = speed;
        this.__startSpeed = speed;

        this.end_loc = this._calculateEnd();

        if(this.options.snapping){

            var snap_loc = this.getSnapNum(this.value),
                end_snap = this.getSnapNum(this.end_loc);

            if(this.options.paging){
                snap_loc = this.getSnapNum(this.drag_start_loc);

                this.__isout = false;
                if(speed > 0){
                    this.gotoSnap(snap_loc + 1 , true , speed);
                }else{
                    this.gotoSnap(snap_loc - 1 , true , speed);
                }
                return;
            }else if(snap_loc === end_snap){
                this.cancel();
                return;
            }

            this._callsnapChange(end_snap);
            this.current_snap = end_snap;

        }

        this.animating = false;

        this.__needsSnap = this.options.endless || (this.end_loc > this._min_value && this.end_loc < this._max_value) ;

        if(this.options.snapping && this.__needsSnap)
            this.__extraMove = this._calculateExtraMove(this.end_loc);


        this._startDecelaration();
    };

    p.bounce = function(speed){
        if(this.animating) return;
        this.stopped = false;
        this.animating = false;

        this.__speed = speed;
        this.__startSpeed = speed;

        this.end_loc = this._calculateEnd();

        //if(this.options.paging){}

        this._startDecelaration();
    };

    p.stop = function(){
        this.stopped = true;
        this._internalStop();
    };

    p.cancel = function(){
        this.start_drag = true; // reset flag for next drag
        if(this.__isout){
            this.__speed = 0.0004;
            this._startDecelaration();
        }else if(this.options.snapping){
            this.gotoSnap(this.getSnapNum(this.value) , true);
        }

    };

    p.renderCallback = function(listener , ref){
        this.__renderHook = {fun:listener , ref:ref};
    };

    p.snappingCallback = function(listener , ref){
        this.__snapHook = {fun:listener , ref:ref};
    };

    p.snapCompleteCallback = function(listener , ref){
        this.__compHook = {fun:listener , ref:ref};
    };

    p.getSnapNum = function(value){
        return Math.floor(( value + this.options.snapsize / 2 ) / this.options.snapsize);
    };

    p.nextSnap = function(animate, speed){
        this._internalStop();

        var curr_snap = this.getSnapNum(this.value),
            snapsize = this.options.snapsize;

        if(!this.options.endless && (curr_snap + 1) * snapsize > this._max_value){

            // if distance is larger than 10% of snap size, it moves to the end location without bounce.
            if ( this._max_value - this.value > snapsize * 0.1 ) {
                this.changeTo(this._max_value, true);
                return;
            }

            this.__speed = 8;
            this.__needsSnap = false;
            this._startDecelaration();
        }else{
            this.gotoSnap(curr_snap + 1 , true);
        }

    };

    p.prevSnap = function(animate, speed){
        this._internalStop();

        var curr_snap = this.getSnapNum(this.value),
            snapsize = this.options.snapsize;

        if(!this.options.endless && (curr_snap - 1) * snapsize < this._min_value){

            // if distance is larger than 10% of snap size, it moves to the start location without bounce.
            if ( this.value - this._min_value > snapsize * 0.1 ) {
                this.changeTo(this._min_value, true);
                return;
            }

            this.__speed = -8;
            this.__needsSnap = false;
            this._startDecelaration();
        }else{
            this.gotoSnap(curr_snap - 1 , true);
        }

    };

    p.gotoSnap = function(snap_num , animate , speed){
        this.changeTo(snap_num * this.options.snapsize , animate , speed , snap_num);
    };

    p.destroy = function(){
        this._internalStop();
        this.__renderHook = null;
        this.__snapHook = null;
        this.__compHook = null;
    };

    /*
    ---------------------------------------------------
        PRIVATE METHODS
    ----------------------------------------------------
    */

    p._internalStop = function(){
        this.start_drag = true; // reset flag for next drag
        this.animating = false;
        this._deceleration = false;
        this.__extrStep = 0;
    };

    p._calculateExtraMove = function(value){
        var m = value % this.options.snapsize;
        return m < this.options.snapsize / 2  ? -m : this.options.snapsize - m;
    };

    p._calculateEnd = function(step){
        var temp_speed = this.__speed;
        var temp_value = this.value;
        var i = 0;
        while(Math.abs(temp_speed) > this.options.minValidDist){
            temp_value += temp_speed;
            temp_speed *= this.options.friction;
            i++;
        }
        if(step) return i;
        return temp_value;
    };

    p._checkLimits = function(value){
        if(this.options.endless)    return value;
        if(value < this._min_value) return this._min_value;
        if(value > this._max_value) return this._max_value;
        return value;
    };

    p._callrenderer = function(){
        if(this.__renderHook) this.__renderHook.fun.call(this.__renderHook.ref , this , this.value);
    };

    p._callsnapChange = function(targetSnap){
        if(!this.__snapHook || targetSnap === this.current_snap) return;
        this.__snapHook.fun.call(this.__snapHook.ref , this , targetSnap , targetSnap - this.current_snap);
    };

    p._callonComplete = function(type){
        if(this.__compHook && !this.stopped){
            this.__compHook.fun.call(this.__compHook.ref , this , this.current_snap , type);
        }

    };

    p._computeDeceleration = function(){

        if(this.options.snapping && this.__needsSnap){
            var xtr_move = (this.__startSpeed - this.__speed) / this.__startSpeed * this.__extraMove;
            this.value += this.__speed + xtr_move - this.__extrStep;
            this.__extrStep = xtr_move;
        }else{
            this.value += this.__speed;
        }

        this.__speed *= this.options.friction; //* 10;

        if(!this.options.endless && !this.options.bouncing){
            if(this.value <= this._min_value){
                this.value = this._min_value;
                this.__speed = 0;
            }else if(this.value >= this._max_value){
                this.value = this._max_value;
                this.__speed = 0;
            }
        }

        this._callrenderer();

        if(!this.options.endless && this.options.bouncing){

            var out_value = 0;

            if(this.value < this._min_value){
                out_value = this._min_value - this.value;
            }else if(this.value > this._max_value){
                out_value = this._max_value - this.value;
            }

            this.__isout =  Math.abs(out_value) >= this.options.minValidDist;

            if(this.__isout){
                if(this.__speed * out_value <= 0){
                    this.__speed += out_value * this.options.outFriction;
                }else {
                    this.__speed = out_value * this.options.outAcceleration;
                }
            }
        }
    };

    p._startDecelaration = function(){
        if(this._deceleration) return;
        this._deceleration = true;

        var self = this;

        var tick = function (){

            if(!self._deceleration) return;

            self._computeDeceleration();

            if(Math.abs(self.__speed) > self.options.minValidDist || self.__isout){
                window.requestAnimationFrame(tick);
            }else{
                self._deceleration = false;
                self.__isout = false;

                if(self.__needsSnap && self.options.snapping && !self.options.paging){
                    self.value = self._checkLimits(self.end_loc + self.__extraMove);
                }else{
                    self.value = Math.round(self.value);
                }

                self._callrenderer();
                self._callonComplete('decel');
            }
        };

        tick();
    };

    window.SlickController = SlickController;

})();


/*! 
 * 
 * ================== js/libs/modules/highlight.pack.js =================== 
 **/ 

/*! highlight.js v9.3.0 | BSD3 License | git.io/hljslicense */
!function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/&/gm,"&amp;").replace(/</gm,"&lt;").replace(/>/gm,"&gt;")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0==t.index}function a(e){return/^(no-?highlight|plain|text)$/i.test(e)}function i(e){var n,t,r,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=/\blang(?:uage)?-([\w-]+)\b/i.exec(i))return w(t[1])?t[1]:"no-highlight";for(i=i.split(/\s+/),n=0,r=i.length;r>n;n++)if(w(i[n])||a(i[n]))return i[n]}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3==i.nodeType?a+=i.nodeValue.length:1==i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!=r[0].offset?e[0].offset<r[0].offset?e:r:"start"==r[0].event?e:r:e.length?e:r}function o(e){function r(e){return" "+e.nodeName+'="'+n(e.value)+'"'}f+="<"+t(e)+Array.prototype.map.call(e.attributes,r).join("")+">"}function u(e){f+="</"+t(e)+">"}function c(e){("start"==e.event?o:u)(e.node)}for(var s=0,f="",l=[];e.length||r.length;){var g=i();if(f+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g==e){l.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g==e&&g.length&&g[0].offset==s);l.reverse().forEach(o)}else"start"==g[0].event?l.push(g[0].node):l.pop(),c(g.splice(0,1)[0])}return f+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):Object.keys(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),void 0===a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"==e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var f=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=f.length?t(f.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){for(var t=0;t<n.c.length;t++)if(r(n.c[t].bR,e))return n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function c(e,n){return!a&&r(n.iR,e)}function g(e,n){var t=N.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function p(e,n,t,r){var a=r?"":E.classPrefix,i='<span class="'+a,o=t?"":"</span>";return i+=e+'">',i+n+o}function h(){if(!k.k)return n(M);var e="",t=0;k.lR.lastIndex=0;for(var r=k.lR.exec(M);r;){e+=n(M.substr(t,r.index-t));var a=g(k,r);a?(B+=a[1],e+=p(a[0],n(r[0]))):e+=n(r[0]),t=k.lR.lastIndex,r=k.lR.exec(M)}return e+n(M.substr(t))}function d(){var e="string"==typeof k.sL;if(e&&!R[k.sL])return n(M);var t=e?f(k.sL,M,!0,y[k.sL]):l(M,k.sL.length?k.sL:void 0);return k.r>0&&(B+=t.r),e&&(y[k.sL]=t.top),p(t.language,t.value,!1,!0)}function b(){L+=void 0!==k.sL?d():h(),M=""}function v(e,n){L+=e.cN?p(e.cN,"",!0):"",k=Object.create(e,{parent:{value:k}})}function m(e,n){if(M+=e,void 0===n)return b(),0;var t=o(n,k);if(t)return t.skip?M+=n:(t.eB&&(M+=n),b(),t.rB||t.eB||(M=n)),v(t,n),t.rB?0:n.length;var r=u(k,n);if(r){var a=k;a.skip?M+=n:(a.rE||a.eE||(M+=n),b(),a.eE&&(M=n));do k.cN&&(L+="</span>"),k.skip||(B+=k.r),k=k.parent;while(k!=r.parent);return r.starts&&v(r.starts,""),a.rE?0:n.length}if(c(n,k))throw new Error('Illegal lexeme "'+n+'" for mode "'+(k.cN||"<unnamed>")+'"');return M+=n,n.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var x,k=i||N,y={},L="";for(x=k;x!=N;x=x.parent)x.cN&&(L=p(x.cN,"",!0)+L);var M="",B=0;try{for(var C,j,I=0;;){if(k.t.lastIndex=I,C=k.t.exec(t),!C)break;j=m(t.substr(I,C.index-I),C[0]),I=C.index+j}for(m(t.substr(I)),x=k;x.parent;x=x.parent)x.cN&&(L+="</span>");return{r:B,value:L,language:e,top:k}}catch(O){if(-1!=O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function l(e,t){t=t||E.languages||Object.keys(R);var r={r:0,value:n(e)},a=r;return t.filter(w).forEach(function(n){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function g(e){return E.tabReplace&&(e=e.replace(/^((<[^>]+>|\t)+)/gm,function(e,n){return n.replace(/\t/g,E.tabReplace)})),E.useBR&&(e=e.replace(/\n/g,"<br>")),e}function p(e,n,t){var r=n?x[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function h(e){var n=i(e);if(!a(n)){var t;E.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(/<br[ \/]*>/g,"\n")):t=e;var r=t.textContent,o=n?f(n,r,!0):l(r),s=u(t);if(s.length){var h=document.createElementNS("http://www.w3.org/1999/xhtml","div");h.innerHTML=o.value,o.value=c(s,u(h),r)}o.value=g(o.value),e.innerHTML=o.value,e.className=p(e.className,n,o.language),e.result={language:o.language,re:o.r},o.second_best&&(e.second_best={language:o.second_best.language,re:o.second_best.r})}}function d(e){E=o(E,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");Array.prototype.forEach.call(e,h)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=R[n]=t(e);r.aliases&&r.aliases.forEach(function(e){x[e]=n})}function N(){return Object.keys(R)}function w(e){return e=(e||"").toLowerCase(),R[e]||R[x[e]]}var E={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},R={},x={};return e.highlight=f,e.highlightAuto=l,e.fixMarkup=g,e.highlightBlock=h,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|like)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("xml",function(s){var e="[A-Za-z0-9\\._:-]+",t={eW:!0,i:/</,r:0,c:[{cN:"attr",b:e,r:0},{b:/=\s*/,r:0,c:[{cN:"string",endsParent:!0,v:[{b:/"/,e:/"/},{b:/'/,e:/'/},{b:/[^\s"'=<>`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xsl","plist"],cI:!0,c:[{cN:"meta",b:"<!DOCTYPE",e:">",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("<!--","-->",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0}]},{cN:"tag",b:"<style(?=\\s|>|$)",e:">",k:{name:"style"},c:[t],starts:{e:"</style>",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"<script(?=\\s|>|$)",e:">",k:{name:"script"},c:[t],starts:{e:"</script>",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"meta",v:[{b:/<\?xml/,e:/\?>/,r:10},{b:/<\?\w+/,e:/\?>/}]},{cN:"tag",b:"</?",e:"/?>",c:[{cN:"name",b:/[^\/><\s]+/,r:0},t]}]}});hljs.registerLanguage("java",function(e){var t=e.UIR+"(<"+e.UIR+"(\\s*,\\s*"+e.UIR+")*>)?",a="false synchronized int abstract float private char boolean static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports",r="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",s={cN:"number",b:r,r:0};return{aliases:["jsp"],k:a,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+t+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:a,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:a,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},s,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("css",function(e){var c="[a-zA-Z-][a-zA-Z0-9_-]*",t={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",i:/:/,c:[{cN:"keyword",b:/\w+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:c,r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,t]}]}});hljs.registerLanguage("ruby",function(e){var r="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",b={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},c={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},s=[e.C("#","$",{c:[c]}),e.C("^\\=begin","^\\=end",{c:[c],r:10}),e.C("^__END__","\\n$")],n={cN:"subst",b:"#\\{",e:"}",k:b},t={cN:"string",c:[e.BE,n],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:b},d=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(s)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:r}),i].concat(s)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:r}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:b},{b:"("+e.RSR+")\\s*",c:[a,{cN:"regexp",c:[e.BE,n],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(s),r:0}].concat(s);n.c=d,i.c=d;var l="[>?]>",o="[\\w#]+\\(\\w+\\):\\d+:\\d+>",u="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",w=[{b:/^\s*=>/,starts:{e:"$",c:d}},{cN:"meta",b:"^("+l+"|"+o+"|"+u+")",starts:{e:"$",c:d}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:b,i:/\/\*/,c:s.concat(w).concat(d)}});hljs.registerLanguage("coffeescript",function(e){var c={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},n="[A-Za-z$_][0-9A-Za-z$_]*",r={cN:"subst",b:/#\{/,e:/}/,k:c},s=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,r]},{b:/"/,e:/"/,c:[e.BE,r]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[r,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{b:"@"+n},{b:"`",e:"`",eB:!0,eE:!0,sL:"javascript"}];r.c=s;var i=e.inherit(e.TM,{b:n}),t="(\\(.*\\))?\\s*\\B[-=]>",o={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:c,c:["self"].concat(s)}]};return{aliases:["coffee","cson","iced"],k:c,i:/\/\*/,c:s.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+n+"\\s*=\\s*"+t,e:"[-=]>",rB:!0,c:[i,o]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:t,e:"[-=]>",rB:!0,c:[o]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[i]},i]},{b:n+":",e:":",rB:!0,rE:!0,r:0}])}});hljs.registerLanguage("cs",function(e){var r={keyword:"abstract as base bool break byte case catch char checked const continue decimal dynamic default delegate do double else enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long when object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual volatile void while async protected public private internal ascending descending from get group into join let orderby partial select set value var where yield",literal:"null false true"},t=e.IR+"(<"+e.IR+">)?(\\[\\])?";return{aliases:["csharp"],k:r,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:"<!--|-->"},{b:"</?",e:">"}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},{cN:"string",b:'@"',e:'"',c:[{b:'""'}]},e.ASM,e.QSM,e.CNM,{bK:"class interface",e:/[{;=]/,i:/[^\s:]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{bK:"new return throw await",r:0},{cN:"function",b:"("+t+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:r,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:r,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]}]}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}});hljs.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}|	)",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:"^\\[.+\\]:",rB:!0,c:[{cN:"symbol",b:"\\[",e:"\\]:",eB:!0,eE:!0,starts:{cN:"link",e:"$"}}]}]}});hljs.registerLanguage("php",function(e){var c={b:"\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*"},a={cN:"meta",b:/<\?(php)?|\?>/},i={cN:"string",c:[e.BE,a],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},e.inherit(e.ASM,{i:null}),e.inherit(e.QSM,{i:null})]},t={v:[e.BNM,e.CNM]};return{aliases:["php3","php4","php5","php6"],cI:!0,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[e.HCM,e.C("//","$",{c:[a]}),e.C("/\\*","\\*/",{c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.C("__halt_compiler.+?;",!1,{eW:!0,k:"__halt_compiler",l:e.UIR}),{cN:"string",b:/<<<['"]?\w+['"]?$/,e:/^\w+;?$/,c:[e.BE,{cN:"subst",v:[{b:/\$\w+/},{b:/\{\$/,e:/\}/}]}]},a,c,{b:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{cN:"function",bK:"function",e:/[;{]/,eE:!0,i:"\\$|\\[|%",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",c,e.CBCM,i,t]}]},{cN:"class",bK:"class interface",e:"{",eE:!0,i:/[:\(\$"]/,c:[{bK:"extends implements"},e.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[e.UTM]},{bK:"use",e:";",c:[e.UTM]},{b:"=>"},i,t]}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:n,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})],i:"\\S"},c={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return n.splice(n.length,0,t,c),{c:n,k:i,i:"\\S"}});hljs.registerLanguage("javascript",function(e){return{aliases:["js","jsx"],k:{keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,{cN:"string",b:"`",e:"`",c:[e.BE,{cN:"subst",b:"\\$\\{",e:"\\}"}]},e.CLCM,e.CBCM,{cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{b:/</,e:/(\/\w+|\w+\/)>/,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:["self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:[e.CLCM,e.CBCM]}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}});


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.photoswipe.js =================== 
 **/ 

(function($, window, document, undefined) {
    "use strict";

    /* ------------------------------------------------------------------------------ */
    // insert photoswipe markup to the page

    if (!window.photoswipe_l10n) {
        window.photoswipe_l10n = {};
    }

    var $pswp = $(
        '<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">' +
            '<div class="pswp__bg"></div>' +
            '<div class="pswp__scroll-wrap">' +
            '<div class="pswp__container">' +
            '<div class="pswp__item"></div>' +
            '<div class="pswp__item"></div>' +
            '<div class="pswp__item"></div>' +
            "</div>" +
            '<div class="pswp__ui pswp__ui--hidden">' +
            '<div class="pswp__top-bar">' +
            '<div class="pswp__counter"></div>' +
            '<button class="pswp__button pswp__button--close" title="' +
            (photoswipe_l10n.close || "Close (Esc)") +
            '"></button>' +
            '<button class="pswp__button pswp__button--share" title="' +
            (photoswipe_l10n.share || "Share") +
            '"></button>' +
            '<button class="pswp__button pswp__button--fs" title="' +
            (photoswipe_l10n.fullscreen || "Toggle fullscreen") +
            '"></button>' +
            '<button class="pswp__button pswp__button--zoom" title="' +
            (photoswipe_l10n.zoom || "Zoom in/out") +
            '"></button>' +
            '<div class="pswp__preloader">' +
            '<div class="pswp__preloader__icn">' +
            '<div class="pswp__preloader__cut">' +
            '<div class="pswp__preloader__donut"></div>' +
            "</div>" +
            "</div>" +
            "</div>" +
            "</div>" +
            '<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">' +
            '<div class="pswp__share-tooltip"></div> ' +
            "</div>" +
            '<button class="pswp__button pswp__button--arrow--left" title="' +
            (photoswipe_l10n.previous || "Previous (arrow left)") +
            '">' +
            "</button>" +
            '<button class="pswp__button pswp__button--arrow--right" title="' +
            (photoswipe_l10n.next || "Next (arrow right)") +
            '">' +
            "</button>" +
            '<div class="pswp__caption">' +
            '<div class="pswp__caption__center"></div>' +
            "</div>" +
            "</div>" +
            "</div>" +
            "</div>"
    ).appendTo("body");

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

    var defaults = {
            target: "a",
            ui: PhotoSwipeUI_Default,
            titleMap: false,
            thumbnailMap: false,
            autoplay: 0,
            showHideOpacity: true,
            getThumbBoundsFn: false
        },
        _uid = 1;

    function JQPhotoSwipe(element, options) {
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this.slides = [];
        this.UID = _uid++;
        this.element = element;
        this.$element = $(element);
        this.init();
    }

    $.extend(JQPhotoSwipe.prototype, {
        init: function() {
            this.$element
                .find(this.settings.target)
                .each(this._registerSlide.bind(this));

            // Parse URL and open gallery if it contains #&pid=3&gid=1
            var hashData = this._photoswipeParseHash();
            if (hashData.pid && hashData.gid) {
                // disable animation
                var animDuration = this.settings.showAnimationDuration;
                this.settings.showAnimationDuration = 0;

                this._openPhotoSwipe(hashData.pid, true);

                this.settings.showAnimationDuration = animDuration;
            }
        },

        getSlides: function() {
            return this.slides;
        },

        _registerSlide: function(index, item) {
            var $item = $(item),
                slide = {
                    src: $item.is("a")
                        ? $item.attr("href")
                        : $item.data("original-src") || $item.attr("src"),
                    w: $item.data("original-width"),
                    h: $item.data("original-height"),
                    item: item
                };

            if ($item.data("type") == "video" && $item.is("a")) {
                slide = {
                    html: this._getVideoHtml($item.attr("href"))
                };
            }

            // title
            if (this.settings.titleMap) {
                slide.title = this.settings.titleMap($item, index, this);
            } else {
                slide.title =
                    $item.data("caption") ||
                    $item.attr("title") ||
                    $item.attr("alt");
            }

            // thumbnail
            if (this.settings.thumbnailMap) {
                var thumb = this.settings.thumbnailMap($item, index, this);
                slide.el = thumb.element;
                slide.msrc = thumb.src;
            } else if ($item.is("img")) {
                slide.el = item;
                slide.msrc = $item.attr("src");
            } else {
                var img = $item.find("img");
                if (img.length) {
                    slide.el = img[0];
                    slide.msrc = img.attr("src");
                }
            }

            $item.data("index", index);
            $item.on("click.photoswipe", this._onItemClick.bind(this));
            this.slides.push(slide);
        },

        // get clean html video data
        _getVideoHtml: function(url) {
            var videoEmbedLink = url;

            if (url.match(/(youtube.com)/)) {
                var split_c = "v=";
                var split_n = 1;
            }

            if (url.match(/(youtu.be)/) || url.match(/(vimeo.com\/)+[0-9]/)) {
                var split_c = "/";
                var split_n = 3;
            }

            if (url.match(/(vimeo.com\/)+[a-zA-Z]/)) {
                var split_c = "/";
                var split_n = 5;
            }

            var getYouTubeVideoID = url.split(split_c)[split_n];

            var cleanVideoID = getYouTubeVideoID.replace(/(&)+(.*)/, "");

            if (url.match(/(youtu.be)/) || url.match(/(youtube.com)/)) {
                videoEmbedLink =
                    "//www.youtube.com/embed/" +
                    cleanVideoID +
                    "?autoplay=" +
                    this.settings.autoplay +
                    "";
            }
            if (
                url.match(/(vimeo.com\/)+[0-9]/) ||
                url.match(/(vimeo.com\/)+[a-zA-Z]/)
            ) {
                videoEmbedLink =
                    "//player.vimeo.com/video/" +
                    cleanVideoID +
                    "?autoplay=" +
                    this.settings.autoplay +
                    "";
            }

            return (
                '<div class="video-wrapper"><iframe class="pswp__video" src="' +
                videoEmbedLink +
                '" width="960" height="640" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>'
            );
        },

        _onItemClick: function(e) {
            e.preventDefault();
            this._openPhotoSwipe($(e.currentTarget).data("index"));
        },

        _thumbnailBounds: function(index) {
            var thumbnail = this.slides[index].el,
                pageYScroll =
                    window.pageYOffset || document.documentElement.scrollTop;

            if (thumbnail) {
                var rect = thumbnail.getBoundingClientRect();
                return {
                    x: rect.left,
                    y: rect.top + pageYScroll,
                    w: rect.width
                };
            } else {
                return null;
            }
        },

        // parse picture index and gallery index from URL (#&pid=1&gid=2)
        _photoswipeParseHash: function() {
            var hash = window.location.hash.substring(1),
                params = {};

            if (hash.length < 5) {
                return params;
            }

            var vars = hash.split("&");
            for (var i = 0; i < vars.length; i++) {
                if (!vars[i]) {
                    continue;
                }
                var pair = vars[i].split("=");
                if (pair.length < 2) {
                    continue;
                }
                params[pair[0]] = pair[1];
            }

            if (params.gid) {
                params.gid = parseInt(params.gid, 10);
            }

            return params;
        },

        _openPhotoSwipe: function(index, fromURL) {
            var gallery,
                options = this.settings;

            $.extend(options, {
                galleryUID: this.UID,
                getThumbBoundsFn: this._thumbnailBounds.bind(this)
            });

            // PhotoSwipe opened from URL
            if (fromURL) {
                // in URL indexes start from 1
                options.index = parseInt(index, 10) - 1;
            } else {
                options.index = parseInt(index, 10);
            }

            // exit if index not found
            if (isNaN(options.index)) {
                return;
            }

            // Pass data to PhotoSwipe and initialize it
            gallery = new PhotoSwipe(
                $pswp[0],
                options.ui,
                this.slides,
                options
            );
            gallery.init();
            this._photoswipeListen(gallery);
        },

        _photoswipeListen: function(gallery) {
            gallery.listen("beforeChange", function() {
                var $allItems = $(this.container).find(".pswp__video");
                // Remove active class from all items
                $allItems.removeClass("active");
                // Add active class too current open item
                $(this.currItem.container)
                    .find(".pswp__video")
                    .addClass("active");
                // Check all items
                $allItems.each(function() {
                    if (!$(this).hasClass("active")) {
                        $(this).attr("src", $(this).attr("src"));
                    }
                });
            });
            gallery.listen("close", function() {
                $(this.currItem.container)
                    .find(".pswp__video")
                    .each(function() {
                        $(this).attr("src", "about:blank");
                    });
            });
        }
    });

    // $.fn.photoSwipe = function ( options ) {
    //     return this.each(function() {
    //         if ( !$.data( this, 'averta_photoswipe' ) ) {
    //             $.data( this, 'averta_photoswipe', new JQPhotoSwipe( this, options ) );
    //         }
    //     });
    // };

    $.fn.photoSwipe = function(options) {
        var args = arguments,
            plugin = "averta_photoswipe";

        if (options === undefined || typeof options === "object") {
            return this.each(function() {
                if (!$.data(this, plugin)) {
                    $.data(this, plugin, new JQPhotoSwipe(this, options));
                }
            });
        } else if (
            typeof options === "string" &&
            options[0] !== "_" &&
            options !== "init"
        ) {
            var returns;

            this.each(function() {
                var instance = $.data(this, plugin);

                if (
                    instance instanceof JQPhotoSwipe &&
                    typeof instance[options] === "function"
                ) {
                    returns = instance[options].apply(
                        instance,
                        Array.prototype.slice.call(args, 1)
                    );
                }

                // Allow instances to be destroyed via the 'destroy' method
                if (options === "destroy") {
                    $.data(this, plugin, null);
                }
            });

            return returns !== undefined ? returns : this;
        }
    };
})(jQuery, window, document);


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.floatLayout.js =================== 
 **/ 

/**
 * Auxin Float Layout
 * @author Averta [www.averta.net]
 *
 * Auto locating attributes:
 *     @example
 *          `<div class="aux-auto-locate" data-tablet="second-bar" data-tablet-method="append"> </div>`
 *          `<div class="aux-auto-locate" data-phone="second-bar" data-phone-method="append"> </div>`
 *          `<div class="aux-auto-locate" data-locate="second-bar" data-locate-method="append"> </div>`
 *
 *      possible methods:
 *          append, preprend, after, before
 */

;(function ( $, window, document, undefined ) {

    "use strict";

    var $window = $(window);

    // Create the defaults once
    var pluginName = "AuxinFloatLayout",
        defaults = {
            autoLocate          : true,                     // enables auto locating elements in defferent screen sizes
            placeholder         : 'aux-placehoder',         // placeholder element classname
            dynamicSelector     : '.aux-auto-locate',       // it finds all elements in the and watchs for relocating them on page resize.
            checkMiddle         : true,

            phoneClassName      : 'aux-phone',
            tabletClassName     : 'aux-tablet',
            desktopClassName    : 'aux-desktop',
            breakpoints     : {   // relocating breakpoints
                992: 'tablet',
                767: 'phone'
            }
    };

    /* ------------------------------------------------------------------------------ */
    // The actual plugin constructor
    function Plugin( element, options ) {
        this.element = element;
        this.$element = $( element );
        // future instances of the plugin
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {
        init: function() {

            // catch the watch elements list
            var dynamicElements = this.$element.find( this.settings.dynamicSelector );
            this.dynamicElements = dynamicElements;

            if ( this.settings.autoLocate && dynamicElements.length ) {
                // init watch elements
                for ( var i = 0, l = dynamicElements.length; i !== l; i++ ) {
                    var element = $( dynamicElements[i] );
                    dynamicElements[i] = element.data( 'placeholder', $( '<span style="display:none;"></span>' ) )
                                                .data( 'layout', 'default' );
                }
            }

            $window.on( 'resize', $.proxy( this._onResize, this ) );
            this._onResize();
        },

        /**
         * updates the element
         * it checks watch
         */
        update: function () {
            this._onResize();

            if ( this.$containerPlaceHolder ) {
                this._onScroll();
            }
        },

        /**
         * destroys the plugin
         */
        destroy: function () {
            $window.off( 'resize', this._onResize )
                   .off( 'scroll', this._onScroll );

            if ( this.dynamicElements ) {
                for ( var i = 0, l = this.dynamicElements.length; i !== l; i++ ) {
                    var dynamicElement = this.dynamicElements[i];
                    dynamicElement.data( 'placeholder' ).remove(); // remove watch element place holder
                    dynamicElement.data( 'placeholder', null );
                }

                this.dynamicElements = null;
            }

            // remove placeholder
            if ( this.$containerPlaceHolder ) {
                this.$containerPlaceHolder.remove();
            }
        },

        /**
         * on resize listener
         */
        _onResize: function() {
            var width = window.innerWidth,
                layout = 'default',
                lastPoint = null;

            // find breakpoint
            for ( var point in this.settings.breakpoints ) {
                if ( width < point && ( lastPoint === null || point < lastPoint ) ) {
                    layout = this.settings.breakpoints[point];
                    lastPoint = point;
                }
            }

            if ( layout === this.lastLayout ) {
                return;
            }


            // remove device class names
            this.$element.removeClass( this.settings.desktopClassName )
                         .removeClass( this.settings.phoneClassName )
                         .removeClass( this.settings.tabletClassName );

            // update device classnames
            if ( layout === 'default' ) {
                this.$element.addClass( this.settings.desktopClassName );
            } else {
                this.$element.addClass( this.settings[layout + 'ClassName'] );
            }

            // check for middle align.
            // this checks height size of element for being odd value, and changes it to even. It causes the element appears sharp
            if ( this.settings.checkMiddle ) {
                this.$element.find( '[class*="-middle"]' ).each( function( index, element ) {
                    var _height = $(element).height();
                    if ( _height % 2 !== 0 ) { // even
                        element.style.paddingBottom = '1px';
                    }
                }.bind(this) );
            }

            this.lastLayout = layout;

            if ( this.settings.autoLocate ) {
                // update all dynamic elements based on new layout
                for ( var i = 0, l = this.dynamicElements.length; i !== l; i++ ) {
                    this._checkElement( this.dynamicElements[i], layout );
                }
            }
        },

        /**
         * check the dynamic element for the new layout
         * @param  {jQuery} $dynamicElement
         * @param  {String} layout
         */
        _checkElement: function( $dynamicElement, layout ) {

            if ( $dynamicElement.data( 'layout' ) === layout ) {
                return;
            }

            if ( layout === 'phone' || layout === 'tablet' ) {

                if ( $dynamicElement.data( 'layout' ) === 'default' ) {
                    // insert placeholder
                    $dynamicElement.after( $dynamicElement.data( 'placeholder' ) );
                }

                // read target $dynamicElement
                var target = $dynamicElement.data( layout );

                if ( target === undefined ) {
                    target = $dynamicElement.data( 'locate' );
                    $( target ).eq(0)[ $dynamicElement.data( 'locate-method' ) || 'append' ] ( $dynamicElement );
                } else {
                    $( target ).eq(0)[ $dynamicElement.data( layout + '-method' ) || 'append' ] ( $dynamicElement );
                }

            } else {
                // move back to placeholder
                $dynamicElement.data( 'placeholder' ).after( $dynamicElement ).detach();
            }

            $dynamicElement.data( 'layout', layout );
        }

    });

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

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function( options ) {
        var _arguments = arguments;
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                 $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            } else if ( typeof options === 'string' && options.indexOf(0) !== '_' )  {
                // access to public methods method
                var plugin = $.data( this, "plugin_" + pluginName);
                plugin[options].apply( plugin, Array.prototype.slice.call( _arguments, 1 ) );
            }
        });
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.stickyPosition.js =================== 
 **/ 

/**
 * Auxin Sticky Position
 * @author Averta [www.averta.net]
 *
 *
 *     Rearrangement:
 *     This plugin support moving elements on sticky position in side the target block.
 *     Each element that required to move need to have data-sticky-move attribute which specifies the target location on sticky.
 *     In addition, data-sticky-move-method is supported for changing the jQuery's move method, default is "append".
 *
 */
;(function ( $, window, document, undefined ) {

    "use strict";

    // Create the defaults once
    var pluginName = "AuxinStickyPosition",
        $window = $(window),
        defaults = {
            className       : 'aux-sticky',
            placeholder     : 'aux-sticky-placeholder',
            schemePrefix    : 'aux-header-',
            stickyMargin    : 0,        // specifies the space between element and top of the page to trigger sticky position
            disablePoint    : 0,        // responsive disable point
            checkBoundaries : false,    // check element boundaries while scrolling to prevent overlapping
            boundryTarget   : '',       // boundry target selector
            rearrange       : true,     // check for rearrangement of elements in the block on sticky
            useTransform    : false     // whether to use transform instead of fixed position or not.
        },
        attributesMap = {
            'sticky-margin' : 'stickyMargin',
            'sticky-off'    : 'disablePoint',
            'rearrange'     : 'rearrange',
            'boundaries'    : 'checkBoundaries',
            'boundry-target': 'boundryTarget',
            'use-transform' : 'useTransform'
        };

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $(element);
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this._scheme = this.$element.data("color-scheme") || false;
        this._stickyScheme = this.$element.data("sticky-scheme") || false;
        this._stickyDisableFlag = false;

        // read attributes
        for ( var attrName in attributesMap ) {
            var value = this.$element.data( attrName );
            if ( value !== undefined ) {
                this.settings[attributesMap[attrName]] = value;
            }
        }
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {
        init: function () {
            //this.containerHeight = this.$element.data('sticky-height') || this.$element.outerHeight();
            this.containerHeight = this.$element.outerHeight();
            // create sticky placeholder
            this.$containerPlaceHolder = $('<div></div>').addClass( this.settings.placeholder );
            this.$element.before( this.$containerPlaceHolder );
            $window.on( 'scroll resize', $.proxy( this._update, this ) );
            this._update();

            // is there wp admin bar?
            this._wpadminbarHeight = $('#wpadminbar').outerHeight() || 0;
        },

        _disable: function(){
            if ( this.settings.useTransform ) {
                this.element.style[_jcsspfx + 'Transform'] = '';
            } else {
                this.element.style.top = '';
            }
            this._stickyDisableFlag = true;
            this.$containerPlaceHolder.css( 'display', 'none' );
            // trigger proper event
            this.$element.trigger( 'unsticky' );
        },

        _update: function() {
            var wst = $window.scrollTop(),
                etp = this.$containerPlaceHolder.offset().top - this.settings.stickyMargin - this._wpadminbarHeight;

            if ( this.settings.disablePoint >= window.innerWidth ) {
                this._disable();
                return;
            } else if( this._stickyDisableFlag ) {
                this.$containerPlaceHolder.css( 'display', 'initial' );
            }

            if ( wst > etp && !this.stickyEnabled ) {
                this.$element.addClass( this.settings.className );
                this.stickyEnabled = true;

                if( this._scheme !== this._stickyScheme ) {
                    if( this._scheme ){
                        this.$element.removeClass( this.settings.schemePrefix + this._scheme );
                    }
                    if( this._stickyScheme ){
                        this.$element.addClass( this.settings.schemePrefix + this._stickyScheme );
                    }
                }

                if ( !this.settings.useTransform ) {
                    this.$containerPlaceHolder.height( this.containerHeight );
                }

                if ( this.settings.rearrange ) {
                    this._checkForRearrange( true );
                }

                if ( !this.useTransform && this.settings.stickyMargin ) {
                    this.element.style.top = this.settings.stickyMargin + this._wpadminbarHeight + 'px';
                }

                // trigger on sticky event
                this.$element.trigger( 'sticky' );

            } else if ( this.stickyEnabled && wst <= etp ) {
                this.stickyEnabled = false;
                this.$containerPlaceHolder.height( 0 );
                this.$element.removeClass( this.settings.className );

                // update height value
                //this.containerHeight = this.$element.data('sticky-height') || this.$element.outerHeight();
                //this.containerHeight = this.$element.outerHeight();

                if( this._scheme !== this._stickyScheme ) {
                    if( this._scheme ){
                        this.$element.addClass( this.settings.schemePrefix + this._scheme );
                    }
                    if( this._stickyScheme ){
                        this.$element.removeClass( this.settings.schemePrefix + this._stickyScheme );
                    }
                }

                if ( this.settings.rearrange ) {
                    this._checkForRearrange( false );
                }

                if ( !this.useTransform && this.settings.stickyMargin ) {
                    this.element.style.top = '';
                }

                // trigger proper event
                this.$element.trigger( 'unsticky' );
            }

            if ( this.settings.useTransform ) {
                if ( this.stickyEnabled ) {
                    var calc = wst - etp;
                    if ( this.settings.checkBoundaries ) {
                        this._checkElementBoundaries( etp, wst, calc );
                    } else {
                        this.element.style[_jcsspfx + 'Transform'] = 'translateY(' + calc + 'px)';
                    }
                } else {
                    this.element.style[_jcsspfx + 'Transform'] = '';
                }
            } else if ( this.settings.checkBoundaries ) {
                this._checkElementBoundaries( etp, wst );
            }
        },

        _checkElementBoundaries: function( etp, wst, calc ) {
            etp  = etp || this.$containerPlaceHolder.offset().top;
            wst  = wst || $window.scrollTop();
            calc = calc || 0;

            this.$boundryTarget = this.settings.boundryTarget.length ? $( this.settings.boundryTarget ) : this.$element.parent().eq(0);
            var boundryTargetOffTop = this.$boundryTarget.offset().top - this._wpadminbarHeight;
            var diff = boundryTargetOffTop + this.$boundryTarget.outerHeight(true) - ( etp + this.$element.outerHeight(true));

            if ( calc >= 0 && calc <= diff ) {
                this.element.style[_jcsspfx + 'Transform'] = 'translateY(' + ( calc ) + 'px)';
            } else if  ( calc >  diff ){
                this.element.style[_jcsspfx + 'Transform'] = 'translateY(' + ( diff ) + 'px)';
            } else {
                this.element.style[_jcsspfx + 'Transform'] = '';
            }

        },

        /**
         * this method moves elements that have sticky move attribute to the target location upon sticky activate
         */
        _checkForRearrange: function( attach ) {
            var self = this;

            if ( attach ) {
                this.$element.find( '[data-sticky-move]' ).each( function(){
                    var $this = $(this),
                        $target = self.$element.find( $this.data( 'sticky-move' ) );

                    if ( $target.length == 0 ) {
                        return;
                    }

                    if ( !$this.data( 'placeholder' ) ) {
                        $this.data( 'placeholder', $('<span style="display:none"></span>') );
                    }

                    $this.after( $this.data( 'placeholder' ) );

                    $target[$this.data( 'sticky-move-method') || 'append']( $this );
                });

            } else {
                this.$element.find( '[data-sticky-move]' ).each( function(){
                    var $this = $(this);
                    if ( $this.data( 'placeholder' ) ) {
                        $this.data( 'placeholder').after( $this ).detach();
                    }
                });
            }
        }

    });

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.hovers.js =================== 
 **/ 

/**
 * This file contains requred jq plugins to create intractive hover effects
 */

/* ------------------------------------------------------------------------------ */
// CUBE
;(function ( $, window, document, undefined ) {
    "use strict";

    var pluginName = "AuxinCubeHover",
        defaults = {
            hitArea: '.aux-hover-active'
        };

    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $( element );
        this.settings = $.extend( {}, defaults, options );
        this._name = pluginName;
        this.init();
    }

    $.extend(Plugin.prototype, {
        init: function() {
            if ( this.settings.hitArea ) {
                var target = this.$element.parents( this.settings.hitArea ).eq(0);
                target.on( 'mouseenter', this._movein.bind(this) );
                target.on( 'mouseleave', this._moveout.bind(this) );
            } else {
                this.$element.on( 'mouseenter', this._movein.bind(this) );
                this.$element.on( 'mouseleave', this._moveout.bind(this) );
            }

            this._fixOrigin();
        },

        _fixOrigin: function() {
            var shift = -this.$element.outerHeight() / 2,
                dir = -1,
                axis = 'X';

            if ( this.$element.hasClass( 'aux-rotate-down') ) {
                dir = 1;
            } else if ( this.$element.hasClass( 'aux-rotate-left') ) {
                shift = -this.$element.outerWidth() / 2;
                axis = 'Y';
                dir = 1;
            } else if ( this.$element.hasClass( 'aux-rotate-right') ) {
                shift = -this.$element.outerWidth() / 2;
                axis = 'Y';
            }

            this._outTransform = 'perspective(1000px) translateZ(' + shift + 'px)';
            this._inTransform  = this._outTransform + ' rotate' + axis + '( ' + (90 * dir) + 'deg )';

            this.element.style[ _jcsspfx + 'TransitionDuration' ] = '0ms';
            this.element.style[ _jcsspfx + 'Transform' ] = this._outTransform;
            this.element.style[ _jcsspfx + 'TransformOrigin' ] = 'center center ' + shift + 'px';

            setTimeout( function() {
                this.element.style[ _jcsspfx + 'TransitionDuration' ] = '';
            }.bind(this), 5);
        },

        _movein: function() {
            this._fixOrigin();
            clearTimeout( this._hoverdelay );
            this._hoverdelay = setTimeout( function(){
                this.element.style[ _jcsspfx + 'Transform' ] = this._inTransform;
            }.bind(this), 10 );
        },

        _moveout: function() {
            clearTimeout( this._hoverdelay );
            this.element.style[ _jcsspfx + 'Transform' ] = this._outTransform;
        },

        destroy: function(){

        }
    });

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );

/* ------------------------------------------------------------------------------ */
// Two ways hover
;(function ( $, window, document, undefined ) {
    "use strict";

    var pluginName = "AuxTwoWayHover",
        defaults = {
            in      : 'aux-hover-in',
            out     : 'aux-hover-out',
            reset   : 'aux-hover-reset'
    };

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    $.extend(Plugin.prototype, {
        init: function () {
            var $element = $(this.element),
                st = this.settings;

            $element.mouseenter( function() {
                $element.removeClass( st.out )
                        .addClass( st.reset );

                clearTimeout( this._hoverTimeout );
                this._hoverTimeout = setTimeout( function(){
                    $element.addClass( st.in ).removeClass( st.reset );
                }, 30 );
            }.bind( this ) ).mouseleave( function(event) {
                clearTimeout( this._hoverTimeout );
                $element.addClass( st.out );
                $element.removeClass( st.in );
            }.bind( this ) );
        }
    });

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );

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



;


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.isoxin.js =================== 
 **/ 

;(function ( $, window, document, undefined ) {

    "use strict";

    // Create the defaults once
    var pluginName = "AuxIsotope",
        defaults = {
            space                   : -1,
            layoutMode              : 'masonry',
            lazyload                : false,
            paginationLoc           : null,
            loadingHeight           : 500,
            searchFilter            : false,
            grouping                : null,
            deeplink                : true,
            isOriginLeft            : true,
            slug                    : 'recent',
            filters                 : '.aux-isotope-filters',

            // isoxin animation timing options
            revealTransitionDelay       : 50,
            revealTransitionDuration    : 50,
            revealBetweenDelay          : 200,
            hideTransitionDuration      : null,
            hideTransitionDelay         : 0,
            hideBetweenDelay            : 200,
            loadingTransitionDuration   : 600,
            imgSizes                    : true,

            resizeTransition        : false,
            paginationClass         : 'aux-pagination aux-round aux-page-no-border aux-iso-pagination',
            loadingClass            : 'aux-loading',
            afterInitClass          : 'aux-isotope-ready',
            groupingPrefix          : '.aux-grouping-',
            searchClass             : '.aux-isotope-search',
            updateUponResize        : false,
            isInitLayout            : false, // prevent auto initialization in isotope
            transitionDuration      : 0, // isotope animation duration ( 0 recommended )

            itemsLoading    : '.aux-items-loading',
            loadingVisible  : 'aux-loading-visible',
            loadingHide     : 'aux-loading-hide',

            // transition helper class names
            transitionHelpers   : {
                hiding          : 'aux-iso-hiding',
                hidden          : 'aux-iso-hidden',
                revealing       : 'aux-iso-revealing',
                visible         : 'aux-iso-visible'
            }

    }, attributeOptionsMap = {
        'pagination'       : 'pagination',
        'perpage'          : 'inPage',
        'layout'           : 'layoutMode',
        'lazyload'         : 'lazyload',
        'space'            : 'space',
        'loading-height'   : 'loadingHeight',
        'search-filter'    : 'searchFilter',
        'grouping'         : 'grouping',
        'deeplink'         : 'deeplink',
        'slug'             : 'slug',
        'filters'          : 'filters',
        'pagination-class' : 'paginationClass'
    };

    // The actual plugin constructor
    function Plugin ( element, options ) {

        if ( !window.Isotope && !$.fn.isotope ) {
            // isotope is not available in this page.
            $.error( 'isotope is not available in this page.' );
            return;
        }

        this.element = element;
        this.$element = $( element );
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;

        // read options from the element
        /* ------------------------------------------------------------------------------ */
        for ( var attr in attributeOptionsMap ) {
            var value = this.$element.data( attr );
            if ( value !== undefined ) {
                this.settings[ attributeOptionsMap[attr] ] = value;
            }
        }

        // check layout
        if ( this.settings.layoutMode === 'grid' ) {
            this.settings.layoutMode = 'masonry';
        }
        /* ------------------------------------------------------------------------------ */

        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend( Plugin.prototype, {
        init: function() {
            this.$element.addClass( this.settings.afterInitClass );

            if ( this.settings.lazyload ) {
                this.$element.height( this.settings.loadingHeight );
            }

            if ( this.$element.parents('.rtl').length ) {
                this.settings.isOriginLeft  = false;
            }

            this._isoElement = this.$element[0];

            if ( this.settings.space >= 0 ) {
                this.$element.children( this.settings.itemSelector ).css({
                    'margin-bottom': this.settings.space + 'px',
                    'padding-right': this.settings.space + 'px'
                });

               this.$element.css( 'margin-right', -this.settings.space + 'px' );
            }

            // Retrieve custom transition settings
            this.settings.revealTransitionDuration = this.$element.data("reveal-transition-duration") || this.settings.revealTransitionDuration;
            this.settings.revealBetweenDelay       = this.$element.data("reveal-between-delay"      ) || this.settings.revealBetweenDelay;
            this.settings.revealTransitionDelay    = this.$element.data("reveal-transition-delay"   ) || this.settings.revealTransitionDelay;

            this.settings.hideTransitionDuration   = this.$element.data("hide-transition-duration"  ) || this.settings.hideTransitionDuration;
            this.settings.hideBetweenDelay         = this.$element.data("hide-between-delay"        ) || this.settings.hideBetweenDelay;
            this.settings.hideTransitionDelay      = this.$element.data("hide-transition-delay"     ) || this.settings.hideTransitionDelay;

            // initialize isotope
            this._isotope = new Isotope( this._isoElement, this.settings );

            // disable default transitions in isotope
            this._isotope.options.hiddenStyle = {};
            this._isotope.options.visibleStyle = {};

            // store isotope on element
            this.$element.data( 'isotope', this._isotope );

            var self = this;
            this._isotope.options.filter = function() {
                return self._filtering( this );
            };

            this._groupValue    = null;
            this._filterValue   = null;
            this._searchValue   = null;
            this._currentFilter = null;
            this._currentSearch = null;
            this._currentGroup  = null;

            if( this.settings.grouping ){
                this._setGroupValue();
            }

            if ( this.settings.deeplink ) {
                this._initDeeplink();
            }

            if ( this.settings.pagination ) {
                // create pagination markup
                this._isotope.options.pagination = true;
                this._initPagination();
            }

            if ( this.settings.lazyload && window.imagesLoaded ) {
                this._isotope.on( 'itemLoading', this._setLazyload.bind(this) );
            } else if ( window.imagesLoaded ) {
                this.$element.imagesLoaded().always( function( instance, image ) {
                    this._arrangeIsotope();
                }.bind( this ) );
            }

            // arrange items
            this._isotope.arrange();
            this._currentPage = this._isotope.options.page;

            this._isotope.items.forEach( function( item ){
                // define $element in item
                if ( !item.$element ) {
                    item.$element = $(item.element);
                }
            }, this );

            if ( this.settings.lazyload ){
                // generate the loading
                this.$loading = this.$element.find( this.settings.itemsLoading )
                                             .addClass( this.settings.loadingHide )
                                             .appendTo( this.$element );
                this._instantlyHideItems();
                this._revealItems();
            }

            // update upon resize
            if ( this.settings.updateUponResize ) {
                $(window).on( 'resize', this._arrangeIsotope.bind( this ) );
            }

            this.ـinitFilters();
        },

        arrange: function( method, options ) {
            var io = this._isotope.options;

            // check filter and page
            if ( this._currentFilter === this._filterValue && ( !this.settings.grouping || this._currentGroup === this._groupValue ) && ( !this.settings.searchFilter || this._currentSearch === this._searchValue   ) && ( !this.settings.pagination || this._currentPage === io.page ) ) {
                return;
            } else {
                this._currentPage   = io.page;
                this._currentFilter = this._filterValue;
                this._currentSearch = this._searchValue;
                this._currentGroup  = this._groupValue;
            }

            var items = this._isotope.filteredItems,
                totalHideDuration = this.settings.transitionDelay,
                totalRevealDuration = 0,
                helpers = this.settings.transitionHelpers,
                i = 0,
                st = this.settings,
                self = this;

            items.forEach ( function( item ){
                self._hideItem( item, self.settings.hideBetweenDelay * (++i) + st.hideTransitionDelay, st.hideTransitionDuration );
            });

            totalHideDuration = st.hideBetweenDelay * i + st.hideTransitionDelay + st.hideTransitionDuration;

            clearTimeout( this._hidingTimeout );
            clearTimeout( this._revealingTimeout );

            this._hidingTimeout = setTimeout( function(){
                self._instantlyHideItems();
                
                if ( !method || method === 'arrange' ) {
                    self._isotope._noTransition( self._isotope.arrange );
                } else {
                    self._isotope[method].apply( self._isotope, options );
                }

                self._revealItems();

            }, totalHideDuration );

            if ( st.deeplink ) {
                self._updateHash();
            }

            this.$element.trigger( 'auxinIsotopeArrange' );

        },

        insert: function( $item ) {
            if ( this.settings.space >= 0 ) {
                $item.css({
                    'margin-bottom': this.settings.space + 'px',
                    'padding-right': this.settings.space + 'px'
                });
            }

            this._isotope.insert($item);
            this._isotope.items.forEach( function( item ){
                // define $element in item
                if ( !item.$element ) {
                    item.$element = $(item.element);
                }
            }, this );

            this._instantlyHideItems();
            this._revealItems();
        },

        remove: function( items ) {
            if ( !Array.isArray( items ) ) {
                items = [items];
            }

            this._isotope.remove( items.map( function( item ) { return item.element; } ) );
            this._isotope.arrange();
        },

        removeAll: function() {
            this._isotope.remove( this._isotope.items.map( function( item ) { return item.element; } ) );
            this.updateIsotope();
            this._isotope.options.page = 1;
        },

        updateIsotope: function(){
            this._arrangeIsotope();
        },

        /**
         * destroys the plugin
         * @public
         */
        destroy: function() {
            if ( this.settings.pagination ) {
                this.$pagination.remove();
            }

            if ( this.settings.updateUponResize ) {
                $(window).off( 'resize', this._arrangeIsotope.bind( this ) );
            }

            this.$element.data( 'isotope', null );
            this._isotope.destroy();
            this.$element.remove();
        },

        changeGroup: function( groupName ){
            // Keep old group name
            this._oldGroup   =  this._groupValue;
            // Update group value
            this._groupValue = groupName;
            // Set localStorage
            localStorage.setItem( 'auxinIsotopeGroup', this._groupValue );
            // Change Filter List View
            this.$filters.find( this.settings.groupingPrefix + this._groupValue ).removeClass( this.settings.transitionHelpers.hidden );
            this.$filters.find( this.settings.groupingPrefix + this._oldGroup ).addClass( this.settings.transitionHelpers.hidden );
            // Arrange isotope
            if ( !this._internalFilterChange ) {
                this.arrange( 'arrange' );
            } else {
                this._internalFilterChange = false;
            }
        },
        
        /* ------------------------------------------------------------------------------ */
        // loading
        showLoading: function(){
            if ( this._loadingIsVisible ) {
                return;
            }

            this.$element.height( this.settings.loadingHeight );

            this._loadingIsVisible = true;
            clearTimeout( this._loadingTimeout );
            this.$loading.show()

            setTimeout(function(){
                this.$loading.addClass( this.settings.loadingVisible )
                .removeClass( this.settings.loadingHide );
            }.bind(this), 1);
            
                         
        },

        hideLoading: function(){
            if ( !this._loadingIsVisible ) {
                return;
            }

            this._loadingIsVisible = false;
            this.$loading.removeClass( this.settings.loadingVisible )
                         .addClass( this.settings.loadingHide );

            clearTimeout( this._loadingTimeout );
            this._loadingTimeout = setTimeout( function(){
                this.$loading.hide();
            }.bind(this), this.settings.loadingTransitionDuration );
        },
        
        /* ------------------------------------------------------------------------------ */
        // Private methods

        _instantlyHideItems: function() {
            this._isotope.items.forEach( function( item ){
                item.element.style[window._jcsspfx + 'TransitionDelay']    = '0';
                item.element.style[window._jcsspfx + 'TransitionDuration'] = '0';
                this._removeHelpers( item.$element );
                item.$element.addClass( this.settings.transitionHelpers.hidden );
            }, this);
        },

        _isFilteredItemsLoaded: function() {
            var items = this._isotope.filteredItems;
            for ( var i = 0, l = items.length; i !== l; i++ ) {
                if( !items[i].loaded ) {
                    return false;
                }
            }

            return true;
        },

        _revealItems: function() {
            var items = this._isotope.filteredItems,
                st = this.settings,
                i = 0;

            if ( !st.lazyload || this._isFilteredItemsLoaded() ) {
                if ( st.lazyload ) {
                    this.hideLoading();
                    this._isotope._noTransition(this._isotope.layout);
                    this._waitForLoad = false;
                }

                this._revealingTimeout = setTimeout( function() {
                    items.forEach( function( item ){
                        this._removeHelpers( item.$element );
                        item.$element.addClass( st.transitionHelpers.hidden );
                        this._revealItem( item, st.revealBetweenDelay * (++i) , st.revealTransitionDuration );
                    }, this);
                }.bind(this), Math.max(st.revealTransitionDelay, 10) );

                this.$element.trigger( 'auxinIsotopeReveal', [items] );
            } else {
                this.showLoading();
                this._waitForLoad = true;
            }
        },

        _revealItem: function( item, delay, duration ) {
            item.element.style[window._jcsspfx + 'TransitionDelay']    = delay + 'ms';
            item.element.style[window._jcsspfx + 'TransitionDuration'] = duration + 'ms';
            this._removeHelpers( item.$element );
            item.$element.addClass( this.settings.transitionHelpers.revealing );

            clearTimeout( item._animTimeout );
            item._animTimeout = setTimeout( function(){
                this._removeHelpers( item.$element );
                item.element.style[window._jcsspfx + 'TransitionDelay']    = '';
                item.element.style[window._jcsspfx + 'TransitionDuration'] = '';
                item.$element.addClass( this.settings.transitionHelpers.visible );
            }.bind(this), delay + duration );
        },

        _hideItem: function( item, delay, duration ) {
            item.element.style[window._jcsspfx + 'TransitionDelay']    = delay + 'ms';
            item.element.style[window._jcsspfx + 'TransitionDuration'] = duration + 'ms';
            this._removeHelpers( item.$element );
            item.$element.addClass( this.settings.transitionHelpers.hiding );

            clearTimeout( item._animTimeout );
            item._animTimeout = setTimeout( function(){
                this._removeHelpers( item.$element );
                item.element.style[window._jcsspfx + 'TransitionDelay']    = '';
                item.element.style[window._jcsspfx + 'TransitionDuration'] = '';
                item.$element.addClass( this.settings.transitionHelpers.hidden );
            }.bind(this), delay + duration );
        },


        _arrangeIsotope: function(){
            this._isotope.layout();
        },

        /**
         * removes transition helpers class name from item.
         * @return {[type]}      [description]
         */
        _removeHelpers: function( $item ) {
           var helpers = this.settings.transitionHelpers;

            // remove old classNames
            for ( var classKey in helpers ) {
                $item.removeClass( helpers[classKey] );
            }
        },


        _setLazyload: function( item, imagesloaded ) {
            var iso = this._isotope,
                that = this;
                imagesloaded.on( 'always', function(e) {
                item.loaded = true;

                // We need to reset isotope item width and height to make sure it calculates the items size correctly
                item.element.style.height = '';
                item.element.style.width = '';

                setTimeout( function() {
                    this.elements.forEach( function( element ) {
                            $(element).removeClass( this.settings.loadingClass );
                    }, that );

                    that._revealItems();
                }.bind( this ) );
            });
        },

        /* ------------------------------------------------------------------------------ */
        // filters
        _filtering: function( itemElement ){
            var $item = $(itemElement);

            // Item list filter
            if( this._filterValue && this._filterValue !== 'all' && !$item.is( this._filterValue ) ){
                return false;
            }

            // Serach value filter
            if( this._searchValue && !( $item.text().match( this._searchValue ) || itemElement.className.match( this._searchValue ) ) ) {
                return false;
            }

            // Grouping filter
            if( this._groupValue && !$item.is( this.settings.groupingPrefix + this._groupValue ) ) {
                return false;
            }

            return true;
        },

        ـinitFilters: function() {
            if ( this.settings.filters ) {
                this.$filters = this.$element.siblings( this.settings.filters ).eq(0);

                if ( !this.$filters ) {
                    return;
                }

                var self = this;
                // List Filters
                this.$filters.find( 'li' ).on( 'click', function( e ) {
                    var $this = $(this),
                        filter = $this.data( 'filter' );

                    if ( filter.length ) {
                        if ( filter === 'all' ) {
                            self._filterValue = false;
                        } else {
                            self._filterValue = '.' + filter;
                        }
                    } else {
                        self._filterValue = false;
                    }

                    if ( !self._internalFilterChange && e.originalEvent ) {
                        self.arrange( 'arrange' );
                    } else {
                        self._internalFilterChange = false;
                    }

                    e.preventDefault();
                });

                // Search Filter
                this.$filters.find( self.settings.searchClass ).keyup( this._debounce( function( e ) {
                    var $this = $(this),
                        filter = $this.val();

                    if( filter.length > 2 ) {
                        self._searchValue = new RegExp( filter, 'gi' );
                    } else {
                        self._searchValue = false;
                    }

                    if ( !self._internalFilterChange && e.originalEvent ) {
                        self.arrange( 'arrange' );
                    } else {
                        self._internalFilterChange = false;
                    }
                }, 200 ) );

                setTimeout( this._updateSelectedFilter.bind(this), 300 );
            }
        },

        _setGroupValue: function(){
            this._localGroupValue = localStorage.getItem("auxinIsotopeGroup");
            this._groupValue = this._localGroupValue ? this._localGroupValue : this.settings.grouping;
        },

        _updateSelectedFilter: function() {
            this._internalFilterChange = true;
            this.$filters.find( '[data-filter="' + (this._filterValue || 'all').replace('.' ,'') + '"] a' ).trigger( 'click' );
        },

        _debounce: function( fn, threshold ) {
            var timeout;
            threshold = threshold || 100;
            return function debounced() {
                clearTimeout( timeout );
                var args  = arguments;
                var _this = this;
                function delayed() {
                    fn.apply( _this, args );
                }
                timeout = setTimeout( delayed, threshold );
            };
        },

        /* ------------------------------------------------------------------------------ */
        // pagination

        /**
         * initialize the pagination control
         */
        _initPagination: function() {

            this.$pagination = $('<nav></nav>').addClass( this.settings.paginationClass );

            if ( this.settings.paginationLoc ) {
                this.$pagination.appendTo( this.settings.paginationLoc );
            } else {
                this.$pagination.insertAfter( this.$element );
            }

            this.$pagination.on( 'click', this._updatePage.bind(this) );

            // update pagination buttons
            this._isotope.on( 'paginationUpdate', this._updatePagination.bind(this) );

        },

        /**
         * updates the pagination control
         * @param  {Number} currentPage
         * @param  {Number} totalPage
         * @param  {Array} items
         */
        _updatePagination: function( currentPage, totalPage, items ) {

            if ( this._internalPaginate ) {
                this._internalPaginate = false;
                return;
            }

            // generate pagination markup
            var html = '<ul class="pagination">';

            if ( totalPage > 1 ) {
                //if ( currentPage !== 1 ) {
                    html += '<li class="prev"><a href="#" data-prev="true">Previous</a></li>';
                //}

                for ( var i = 0; i !== totalPage; i++ ) {
                    var page =  i + 1;
                    html += '<li class="page ' + ( page === currentPage ? 'active' : '' ) + ' "><a data-page="' + page + '" href="#">' + page + '</a>';
                }

                //if ( currentPage !== totalPage ) {
                    html += '<li class="next"><a href="#" data-next="true">Next</a></li>';
                //}
            }

            html += '</ul>';

            this.$pagination.html( html );
        },

        /**
         * pagination click listener
         */
        _updatePage: function( event ) {
            var $btn = $( event.target ),
                page;

            if ( $btn.data( 'page' ) !== undefined ) {
                page = $btn.data( 'page' );
            } else if ( $btn.data( 'next' ) ) {
                page = Math.min( this._isotope.currentPage() + 1 , this._isotope.totalPages() );
            } else if ( $btn.data( 'prev' ) ) {
                page = Math.max( this._isotope.currentPage() - 1 , 1 );
            } else {
                return;
            }

            this._isotope.options.page = page;
            this.$pagination.find('.page').removeClass('active')
                                          .eq( page - 1  )
                                          .addClass('active');
            this._internalPaginate = true;
            this.arrange('arrange');
            event.preventDefault();
        },

        /* ------------------------------------------------------------------------------ */
        // deeplink

        _initDeeplink: function() {
            this._readHash( false );
            $(window).on( 'hashchange', this._readHash.bind(this) );
            //this._isotope.on( 'arrangeComplete', this._updateHash.bind(this) );
        },

        _findHashData: function() {
            var hash = window.location.hash.slice(1).split(','),
                result

            for ( var i = 0, l = hash.length; i !== l; i++ ) {
                result = hash[i].split( '/' );
                if ( result.indexOf( this.settings.slug ) !== -1 ) {
                    return result;
                }
            }

            return false;
        },

        _readHash: function( arrange ) {
            if ( this._internalHashUpdate ) {
                this._internalHashUpdate = false;
                return;
            }

            // #/slug/filter/page
            // #/recent/all/1

            var result = this._findHashData();
            if ( !result ) {
                return;
            }

            var io = this._isotope.options,
                oldFilter = this._filterValue,
                oldPage   = io.page;

            this._filterValue = this._parseFilter( result[2] );
            if ( this.settings.pagination ){
                io.page = this._checkPagePolicy( parseInt( result[3] ) );
            }

            if ( !arrange || ( this._filterValue === oldFilter && ( !this.settings.pagination || io.page === oldPage ) ) ) {
                return;
            }

            if ( this.$filters ) {
                this._updateSelectedFilter();
            }

            this._internalHashRead = true;
            this.arrange('arrange');
        },

        _updateHash: function() {
            if ( this._internalHashRead ) {
                this._internalHashRead = false;

                return;
            }

            var hashStr = '/' + this.settings.slug + '/' + this._sanitizeFilter(this._filterValue),
                currentHash = window.location.hash.slice(1);

            if ( this.settings.pagination ) {
                hashStr += '/' + this._isotope.options.page;
            }

            var inHash = this._findHashData();

            this._internalHashUpdate = true;

            if ( inHash ) {
                var hash = currentHash.split(',');
                for ( var i = 0, l = hash.length; i !== l; i++ ) {
                    if ( hash[i].split( '/' ).indexOf( this.settings.slug ) !== -1 ) {
                        hash[i] = hashStr;
                        break;
                    }
                }

                window.location.hash = hash.join(',');
            } else if ( currentHash.length ) {
                window.location.hash = currentHash + ',' + hashStr;
            } else {
                window.location.hash = hashStr;
            }
        },

        _checkPagePolicy: function( page ) {
            if ( !this._isotope.options.pagination ) {
                return undefined;
            }

            if ( page <= 0 ) {
                return 1;
            }

            if ( page > this._isotope.totalPages() ) {
                return this._isotope.totalPages();
            }

            if ( isNaN(page) ) {
                return 1;
            }

            return page;
        },

        _sanitizeFilter: function( filter ) {
            if ( !filter ) {
                return 'all';
            }

            return filter.replace(/\s/g, '&').replace('.', '');
        },

        _parseFilter: function( filter ) {
            if ( filter === 'all' || filter === undefined ) {
                return undefined;
            }

            return '.' + $.trim( filter.replace('&', ' .') );
        }

    });

    $.fn[pluginName] = function (options) {
        var args = arguments,
            plugin = 'plugin_' + pluginName;
        if (options === undefined || typeof options === 'object') {
            return this.each(function () {
                if (!$.data(this, plugin)) {
                    $.data(this, plugin, new Plugin( this, options ));
                }
            });
        } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
            var returns;

            this.each(function () {
                var instance = $.data(this, plugin);
                if (instance instanceof Plugin && typeof instance[options] === 'function') {
                    returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
                }
                if (options === 'destroy') {
                  $.data(this, plugin, null);
                }
            });
            return returns !== undefined ? returns : this;
        }
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.loadmore.js =================== 
 **/ 

/**
 * Auxin Ajax Load
 */
;(function ( $, window, document, undefined ) {

    "use strict";

    // Create the defaults once
    var pluginName  = "AuxLoadMore",
        $window = $(window),
        defaults = {
            elementID: ''
        },
        attributesMap = {
            'element-id': 'elementID'
        };

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element        = element;
        this.$element       = $(element);
        this.settings       = $.extend( {}, defaults, options );
        this._defaults      = defaults;
        this._name          = pluginName;
        this._isotopeLayout = this.$element.find('.aux-isotope-ready').length;
        this.ajaxView       = this.$element.find('.aux-ajax-view');
        // read attributes
        for ( var attrName in attributesMap ) {
            var value = this.ajaxView.data( attrName );
            if ( value !== undefined ) {
                this.settings[attributesMap[attrName]] = value;
            }
        }

        this.content        = auxin.content.loadmore[this.settings.elementID];
        this.args           = this.content.args;
        this.nonce          = this.content.nonce;
        this.handler        = this.content.handler;
        this.postPerPage    = parseInt(this.args.loadmore_per_page);
        this.offset         = parseInt(this.args.offset) || 0;
        this.defaultOffset  = this.offset;

        // main element controller
        this.ajaxController = this.$element.find('.aux-ajax-controller');
        // next-prev element
        this.loadNextPrev   = this.ajaxController.find('.aux-load-next-prev');
        // load more button element
        this.loadMoreBtn    = this.ajaxController.find('.aux-load-more');
        // Check ajax status (Especially for scroll loads)
        this.ajaxLoaded     = true;

        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {

        init: function () {
            if ( this.$element.is('.aux-ajax-type-next-prev') ) {
                //call _loadNextPrev function on click button
                this.loadNextPrev.click( this._loadNextPrev.bind(this) );

            } else if ( this.$element.is('.aux-ajax-type-scroll') ) {
                //call _loadScroll function on scroll changes
                $window.scroll( this._loadScroll.bind(this) );

            } else if ( this.$element.is('.aux-ajax-type-next') ) {
                 //call _loadNext function on click button
                this.loadMoreBtn.click( this._loadNext.bind(this) );
            }
        },

        _callAjax: function( type, offset ) {
            //set post offset
            this.args.offset= offset;
            // This value will fix synchronous conflicts
            this.ajaxLoaded = false;
            //run AJAX functionality
            $.ajax({
                type        :'POST',
                dataType    : 'json',
                url         : auxin.ajax_url,
                data : {
                    action  : "load_more_element",
                    handler : this.handler,
                    nonce   : this.nonce,
                    args    : this.args
                },
                success: function(response) {
                    // Set post counter variable
                    var postCounter;
                    //check results status
                    if( response.success ) {
                        switch( type ){
                            case 'next-prev':
                                this.ajaxView.empty();
                                if( offset === this.defaultOffset ) {
                                    this.ajaxController.find('.np-prev-section').addClass('hidden');
                                } else {
                                    this.ajaxController.find('.np-prev-section').removeClass('hidden');
                                }
                                break;
                            default:
                                this.loadMoreBtn.removeClass( 'aux-active-loading' );
                        }
                        // Remove widget container progress class
                        this.$element.removeClass('aux-in-progress');

                        var $newContent = $(response.data);

                        // Get post count DOM data from response.data
                        postCounter         = $newContent.filter('.aux-post-count').text();
                        // Remove aux-post-count block from response.data
                        $newContent = $newContent.filter('.aux-ajax-item, .aux-date-label, style');

                        // append new data by isotope insert | append method
                        if( this._isotopeLayout ) {
                            $newContent.each(function( index, element ) {
                                var $item = $(element);
                                if ( $item.is( 'style' ) ) {
                                    this.ajaxView.append( $item );
                                    return;
                                }
                                this.ajaxView.AuxIsotope( 'insert', $item );
                                $item.imagesLoaded({}, function () {
                                    this.ajaxView.AuxIsotope('arrange').AuxIsotope('updateIsotope');
                                }.bind(this));
                                this._afterAppend( $item );
                            }.bind(this));
                        } else {
                            $newContent.each(function( index, element ) {
                                var $item = $(element);
                                this.ajaxView.append( $item );
                                if ( $item.is( 'style' ) ) {
                                    return;
                                }
                                this._afterAppend( $item );
                            }.bind(this));
                        }
                        // display next page button
                        this.ajaxController.find('.np-next-section').removeClass('hidden');
                    }// end if

                    if ( postCounter < this.postPerPage  || !response.success ) {
                        switch( type ){
                            case 'next-prev':
                                this.ajaxController.find('.np-next-section').addClass('hidden');
                                break;
                            default:
                                this.ajaxController.remove();
                        }
                    }// end if

                    // Fix matchHeight on DOM insert
                    if( $newContent && this.ajaxView.hasClass('aux-match-height') ) {
                        $.fn.matchHeight._maintainScroll = true;
                        $newContent.imagesLoaded( {}, function() {
                            this.ajaxView.find('.aux-col').matchHeight();
                            setTimeout($.fn.matchHeight._update, 100);
                        }.bind( this ));
                    }
                    // Hooray! Ajax is loaded :)
                    this.ajaxLoaded     = true;
                // End success status
                }.bind(this)
            });

        },

        _afterAppend: function( $content ) {

            // $(window).trigger('resize');
            $content.setOnAppear(true, 100).addClass('aux-ajax-anim');         

            if( $content.hasClass( 'aux-image-box' ) ) {
                // update image alignment inside the tiles upon loadmore
                $content.AuxinImagebox();
            }

            $content.AuxinCarouselInit();

            $content.find('.aux-frame-cube').AuxinCubeHover();
            $content.find('.aux-hover-twoway').AuxTwoWayHover();            

            if( $content.find( '.aux-media-video, .aux-media-audio' ).length ) {
                if( $content.find( 'iframe' ).length ) {
                    // Creating intrinsic ratios for videos
                    $content.fitVids({ customSelector: 'iframe[src^="http://w.soundcloud.com"], iframe[src^="https://w.soundcloud.com"]'});
                } else {
                    // Call mediaelement player
                    $content.find('video,audio').mediaelementplayer();
                }
            }

            $content.find('.aux-lightbox-frame').photoSwipe({
                    target: '.aux-lightbox-btn',
                    bgOpacity: 0.8,
                    shareEl: true
                }
            );
        },

        _loadNext: function() {
            // Returns when AJAX is not loaded yet
            if( !this.ajaxLoaded ) {
                return;
            }
            // Update offset value
            this.offset +=  this.postPerPage;
            this.loadMoreBtn.addClass( 'aux-active-loading' );
            this.$element.addClass('aux-in-progress');
            this._callAjax( 'next', this.offset );
        },

        _loadScroll: function( event ) {
            // Returns when AJAX is not loaded yet
            if( !this.ajaxLoaded ) {
                return;
            }
            // get current load more container position
            var elementPosition = this.ajaxController[0].getBoundingClientRect().bottom;
            // check elementPosition with windows height
            if ( elementPosition <= $window.height() ) {
                // Update offset value
                this.offset +=  this.postPerPage;
                this.$element.addClass('aux-in-progress');
                this.loadMoreBtn.addClass( 'aux-active-loading' );
                this._callAjax( 'scroll', this.offset );
            }
            // no page reload
            event.preventDefault();
        },

        _loadNextPrev: function( event ) {
            // Returns when AJAX is not loaded yet
            if( !this.ajaxLoaded ) {
                return;
            }
            // Check offset value
            if( $(event.currentTarget).hasClass('np-next-section') ){
                this.offset +=  this.postPerPage;
            } else {
                this.offset =   this.offset <= this.defaultOffset ? this.defaultOffset : this.offset - this.postPerPage;
            }
            this.$element.addClass('aux-in-progress');
            this._callAjax( 'next-prev', this.offset );
            // no page reload
            event.preventDefault();
        }

    });

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.carousel.js =================== 
 **/ 

/**
 * Auxin Carousel Plugin.
 *
 * @package Auxin
 * @author Averta
 */
;(function ( $, window, document, undefined ) {

    "use strict";

    // Create the defaults once
    var pluginName = "AuxinCarousel",
        $window = $(window),
        defaults = {
            viewClass           : 'aux-mc-view',
            containerClass      : 'aux-mc-container',
            itemClass           : 'aux-mc-item',
            arrowsClass         : 'aux-mc-arrows',
            bulletsClass        : 'aux-bullets',
            bulletClass         : 'aux-bullet',
            selectedBulletClass : 'aux-selected',
            arrows              : true,
            matchHeight         : false,
            startItem           : 0,
            bullets             : false,
            wrapControls        : false,
            arrowNextMarkup     : '.aux-next-arrow',
            arrowPrevMarkup     : '.aux-prev-arrow',
            controlsClass       : 'aux-mc-controls',
            noJS                : 'aux-no-js',
            initClass           : 'aux-mc-init',
            beforeInit          : 'aux-mc-before-init',
            initCb              : null
    },

    attributeOptionsMap = {
        'loop'          : 'loop',
        'space'         : 'space',
        'dir'           : 'dir',
        'center'        : 'center',
        'speed'         : 'speed',
        'swipe'         : 'swipe',
        'mouse-swipe'   : 'mouseSwipe',
        'start'         : 'startItem',
        'rtl'           : 'rtl',
        'arrows'        : 'arrows',
        'bullets'       : 'bullets',
        'bullet-class'  : 'bulletsClass',
        'auto-height'   : 'autoHeight',
        'autoplay'      : 'autoplay',
        'delay'         : 'autoplayDelay',
        'columns'       : 'columns',
        'same-height'   : 'matchHeight',
        // responsive value example: 150:5, 220:2
        'responsive'    : 'responsive',
        'auto-pause'    : 'pauseOnHover',
        'navigation'    : 'navigation',
        'lazyload'      : 'preload',
        'empty-height'  : 'emptyHeight',
        'wrap-controls' : 'wrapControls'
    }

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element = element;
        // future instances of the plugin
        this.settings = $.extend( {}, defaults, options );
        this.$element = $(element);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {
        init: function () {

            // check for Master Carousel
            if ( !window.MasterCarousel ) {
                $.error( 'Master Carousel does not found in the page.' );
                return;
            }


            // read attributes
            for ( var attrName in attributeOptionsMap ) {
                var value = this.$element.data( attrName );
                if ( value !== undefined ) {
                    this.settings[attributeOptionsMap[attrName]] = value;
                }
            }

            // parse responsive options
            if ( this.$element.data( 'responsive' ) ) {
                var resp = {};

                $.each(this.settings.responsive.replace( /\s+/g, '' ).split(','), function( index, value ) {
                    value = value.split(':');
                    resp[value[0]] = { columns: value[1] };
                });

                this.settings.responsive = resp;
            }

            // match height items
            if ( this.settings.matchHeight ) {
                $window.on( 'resize', this._updateItemsHeight.bind(this) );
            }

            // carousel instance
            this.mc = new MasterCarousel( this.$element[0] , this.settings );
            this.mc.addEventListener( MCEvents.INIT, this._onCarouselInit, this );
            this.mc.setup();

            // remove no-js class
            this.$element.removeClass( this.settings.noJS );
        },

        _onCarouselInit: function() {

            var st = this.settings;

            // add js active class name to the carousel
            this.$element.addClass( this.settings.initClass )
                         .removeClass( this.settings.beforeInit );

            if ( st.arrows || st.bullets && st.wrapControls ) {
                this.$controlsWrap = $('<div></div>').addClass( st.controlsClass ).insertAfter( this.$element );
            }

            // insert arrows
            if ( st.arrows ) {
                this.$prevArrow = $('<div></div>').addClass( st.arrowsClass + ' aux-prev' )
                                                  .click( { action: 'prev' }, $.proxy( this._controlCarousel, this ) );

                if ( st.wrapControls ) {
                    this.$prevArrow.appendTo( this.$controlsWrap );
                } else {
                    this.$prevArrow.insertAfter( this.$element );
                }

                if ( st.arrowPrevMarkup ) {
                    this.$element.find( st.arrowPrevMarkup ).appendTo( this.$prevArrow );
                }

                this.$nextArrow = $('<div></div>').addClass( st.arrowsClass + ' aux-next' )
                                                  .click( { action: 'next' }, $.proxy( this._controlCarousel, this ) );

                if ( st.wrapControls ) {
                    this.$nextArrow.appendTo( this.$controlsWrap );
                } else {
                    this.$nextArrow.insertAfter( this.$element );
                }

                if ( st.arrowNextMarkup ) {
                    this.$element.find( st.arrowNextMarkup ).appendTo( this.$nextArrow );
                }
            }

            // bullets container
            if ( st.bullets ) {
                this.$bullets = $('<div></div>').addClass( st.bulletsClass );
                this._generateBullets();
                this.mc.view.addEventListener( MCEvents.SCROLL, this._updateCurrentBullet, this );
                $window.on( 'resize', this._updateBullets.bind(this) );
            }

            // match height items
            if ( st.matchHeight ) {
                this.matchHeightTo = setTimeout( this._updateItemsHeight.bind( this ), 150, true );
            }

            // check siteorigin-panels-stretch
            if ( this.$element.parents( '.siteorigin-panels-stretch' ).length ) {
                $window.on( 'resize.master-carousel', this._updateCarouselSize.bind(this) );
                this._updateCarouselSize();
            }

            if ( st.initCb ) {
                st.initCb( this );
            }

            this.$element.trigger( 'auxinCarouselInit' );
        },

        _updateCarouselSize : function() {
            setTimeout( this.mc.view._resize.bind( this.mc.view ) , 0 );
        },

        _generateBullets: function() {
            this.$bullets.children().remove();
            this._bullets = [];

            if ( this.settings.wrapControls ) {
                this.$bullets.appendTo( this.$controlsWrap );
            } else {
                this.insertAfter( this.$element );
            }

            //insert bullets
            for ( var i = 0, l = this.mc.count(); i !== l; i++ ) {
                this._bullets.push ( $('<div></div>').addClass( this.settings.bulletClass ).appendTo( this.$bullets ).click( { action: 'bullet', index: i }, $.proxy( this._controlCarousel, this ) ) );
            }

            this._updateCurrentBullet();
        },

        _updateBullets: function() {
            if ( this._bullets.length === this.mc.count() ) {
                return;
            }

            this._generateBullets();
        },

        _updateItemsHeight: function( withDelay ) {

            if ( !this.mc.items ) {
                return;
            }

            if ( withDelay !== true ) {
                clearTimeout( this.matchHeightTo )
                this.matchHeightTo = setTimeout( this._updateItemsHeight.bind( this ), 20, true );
                return;
            }

            var maxHeight = 0;

            this.mc.items.forEach( function( item ){
                item.$element[0].style.height = '';
                maxHeight = Math.max( item.$element.height(), maxHeight );
            }.bind( this ) );

            this.mc.items.forEach( function( item ){
                item.$element.height( maxHeight );
            }.bind( this ) );
        },

        /**
         * controls
         */
        _controlCarousel: function( event ) {
            var target = event.target,
                action = event.data.action;

            switch ( action ) {
                case 'next':
                    this.mc.next();
                break;
                case 'prev':
                    this.mc.previous();
                break;
                case 'bullet':
                    this.mc.goto( event.data.index + 1, true );
                break;
            }

        },

        /**
         * updates the current class name on bullets
         */
        _updateCurrentBullet: function() {
            var target = this.mc.current() - 1;
            if ( this._currentPosition === target ) {
                return;
            }
            this._currentPosition = target;
            this.$bullets.find( '.' + this.settings.bulletClass ).removeClass( this.settings.selectedBulletClass ).eq(target).addClass( this.settings.selectedBulletClass );
        },

        /**
         * removes all
         * @return {[type]} [description]
         */
        destroy: function() {
            // remove listeners
            this.mc.removeEventListener( MCEvents.INIT, this._onCarouselInit, this );
            this.mc.view.removeEventListener( MCEvents.SCROLL, this._updateCurrentBullet, this );

            if ( this.settings.matchHeight ) {
                $window.off( 'resize', this._updateItemsHeight.bind(this) );
            }

            $window.off( 'resize.master-carousel' );

            if ( this.settings.arrows ) {
                this.$nextArrow.remove();
                this.$prevArrow.remove();
            }

            if ( this.settings.bullets ) {
                $window.off( 'resize', this._updateBullets.bind(this) );
                this.$bullets.remove();
            }

            // destory master carousel
            this.mc.destroy();
            this.$element.remove();
        }

    });

    $.fn[pluginName] = function (options) {
        var args = arguments,
            plugin = 'plugin_' + pluginName;

        // Is the first parameter an object (options), or was omitted,
        // instantiate a new instance of the plugin.
        if (options === undefined || typeof options === 'object') {
            return this.each(function () {

                // Only allow the plugin to be instantiated once,
                // so we check that the element has no plugin instantiation yet
                if (!$.data(this, plugin)) {
                    $.data(this, plugin, new Plugin( this, options ));
                }
            });

        // If the first parameter is a string and it doesn't start
        // with an underscore or "contains" the `init`-function,
        // treat this as a call to a public method.
        } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {

            // Cache the method call
            // to make it possible
            // to return a value
            var returns;

            this.each(function () {
                var instance = $.data(this, plugin);

                // Tests that there's already a plugin-instance
                // and checks that the requested public method exists
                if (instance instanceof Plugin && typeof instance[options] === 'function') {

                    // Call the method of our plugin instance,
                    // and pass it the supplied arguments.
                    returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
                }

                // Allow instances to be destroyed via the 'destroy' method
                if (options === 'destroy') {
                  $.data(this, plugin, null);
                }
            });

            // If the earlier cached method
            // gives a value back return the value,
            // otherwise return this to preserve chainability.
            return returns !== undefined ? returns : this;
        }
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.toggleSelected.js =================== 
 **/ 

;(function ( $, window, document, undefined ) {

    "use strict";

    var pluginName = "AuxinToggleSelected",
        defaults = {
            isotope       : null, // isotope element
            overlayClass  : 'aux-overlay',
            overlay       : 'aux-select-overlay',
            event         : 'click',
            target        : 'li>a',
            selected      : 'aux-selected',
            resizeOverlay : true
        };

    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $(element);
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {
        init: function() {
            this.$targets = this.$element.find( this.settings.target );

            this.$targets.on( this.settings.event, this._toggleSelected.bind(this) );

            if ( this.$element.hasClass( this.settings.overlayClass ) ) {
                this.overlay = this.$element.find( '.' + this.settings.overlay )[0];
                $(window).resize( this._locateOverlay.bind( this ) );
            }

            // select first if nothing selected
            if ( this.$element.find( '.' + this.settings.selected ).length === 0 ) {
                this.$current = this.$targets.eq(0);
                this._toggleSelected( { currentTarget: this.$current[0] } );
            }

            this._locateOverlay();

        },

        _toggleSelected: function( event ) {
            this.$targets.removeClass( this.settings.selected );
            var $this = $(event.currentTarget);
            $this.addClass( this.settings.selected );

            // update isotope, applies data-filter to isotope instance
            if ( this.settings.isotope ) {
                 this.settings.isotope.arrange( { filter: $this.data('filter') } );
            }

            this.$current = $this;
            this._locateOverlay();
        },

        _locateOverlay: function() {
            if ( !this.overlay || !this.$current ) {
                return;
            }

            this.overlay.style[window._jcsspfx + 'Transform'] = 'translate(' +
                                    ( this.$current.offset().left - this.$element.offset().left ) + 'px, ' +
                                    ( this.$current.offset().top  - this.$element.offset().top  ) + 'px  )';

            if ( this.settings.resizeOverlay ) {
                this.overlay.style.width  = ( this.$current.outerWidth() - 1 ) + 'px';
                this.overlay.style.height = ( this.$current.outerHeight() - 1 ) + 'px';
            }

        },

        destroy: function() {
            $(window).off( 'resize', this._locateOverlay );
            this.$overlay = null;
            this.$element.remove();
        }

    });


    $.fn[pluginName] = function (options) {
        var args = arguments,
            plugin = 'plugin_' + pluginName;

        if (options === undefined || typeof options === 'object') {
            return this.each(function () {

                if (!$.data(this, plugin)) {
                    $.data(this, plugin, new Plugin( this, options ));
                }
            });
        } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {

            var returns;

            this.each(function () {
                var instance = $.data(this, plugin);

                if (instance instanceof Plugin && typeof instance[options] === 'function') {
                    returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
                }

                // Allow instances to be destroyed via the 'destroy' method
                if (options === 'destroy') {
                  $.data(this, plugin, null);
                }
            });

            return returns !== undefined ? returns : this;
        }
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.videobox.js =================== 
 **/ 

/**
 * Auxin video box html element
 *
 *      Example markup:
 *          <div class="aux-video-box" data-fill="fill">
 *              <video>
 *                  <source src="video.mp4" type="video/mp4"/>
 *                  <source src="video.webm" type="video/webm"/>
 *                  <source src="video.ogv" type="video/ogg"/>
 *              </video>
 *          </div>
 */

;(function ( $, window, document, undefined ) {

    "use strict";

    // Create the defaults once
    var pluginName = "AuxinVideobox";

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $( element );
        this._name = pluginName;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {
        init: function() {
            this.$video = this.$element.find( '>video' );

            if ( this.$video.length === 0 ) {
                return;
            }

            this.video = this.$video[0];

            this.video.addEventListener( 'loadedmetadata', this._initVideo.bind( this ) );

            if ( !AVTAligner ){
                $.error( "AVTAligner is not defined in this page, Auxin video box requires this library to perform correctly." );
            } else {
                this.aligner = new AVTAligner( this.$element.data( 'fill' ) || 'fill' , this.$element, this.$video );
                $(window).on( 'resize', this._alignVideo.bind( this ) );
            }
        },

        _initVideo: function() {
            if ( this._videoInit ) {
                return;
            }

            this._videoInit = true;
            this.aligner.init( this.video.videoWidth , this.video.videoHeight );
            this.aligner.align();
            this.video.play();
        },

        _alignVideo: function() {
            this.aligner.align();
        },

        destroy: function(){
            $(window).off( 'resize', this._alignVideo );
        }
    });

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        var args = arguments,
            plugin = 'plugin_' + pluginName;

        if (options === undefined || typeof options === 'object') {
            return this.each(function () {

                if (!$.data(this, plugin)) {
                    $.data(this, plugin, new Plugin( this, options ));
                }
            });
        } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {

            var returns;

            this.each(function () {
                var instance = $.data(this, plugin);

                if (instance instanceof Plugin && typeof instance[options] === 'function') {
                    returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
                }

                // Allow instances to be destroyed via the 'destroy' method
                if (options === 'destroy') {
                  $.data(this, plugin, null);
                }
            });

            return returns !== undefined ? returns : this;
        }
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.imagebox.js =================== 
 **/ 

/**
 * Auxin Image Box
 *
 *  This plugin aligns and sizes image element inside it's frame element
 *
 */

;(function ( $, window, document, undefined ) {

    "use strict";

    // Create the defaults once
    var pluginName = "AuxinImagebox",
        defaults = {
            target  : 'img',
            frame   : null,
            fill    : 'fill'
        },
        attributeOptionsMap = {
            'fill'          : 'fill',
            'target'        : 'target',
            'frame'        : 'frame'
        }

    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $( element );
        this.settings = $.extend( {}, defaults, options );
        this._name = pluginName;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {
        init: function() {

            if ( !AVTAligner ){
                $.error( "AVTAligner is not defined in this page, Auxin image box requires this library to perform correctly." );
                return;
            }

            // read attributes
            for ( var attrName in attributeOptionsMap ) {
                var value = this.$element.data( attrName );
                if ( value !== undefined ) {
                    this.settings[attributeOptionsMap[attrName]] = value;
                }
            }

            this.$image = this.$element.find( this.settings.target );

            if ( !this.$image.length ) {
                return;
            }

            this.$image.preloadImg( this.$image.attr('src'), this._initAligner.bind(this) );
            this.$frame = this.settings.frame ? this.$element.find( this.settings.frame ) : this.$element;
            this.aligner = new AVTAligner( this.settings.fill , this.$parent, this.$image, {
                            containerWidth: this.$frame.innerWidth.bind( this.$frame ),
                            containerHeight: this.$frame.innerHeight.bind( this.$frame ),
                            srcset: !!this.$image.attr( 'srcset' )
                        });
            $(window).on( 'resize', this._alignImage.bind( this ) );

        },

        _initAligner: function() {

            if ( this._aligenrInit ) {
                return;
            }

            this._aligenrInit = true;
            var img = this.$image[0],
                w = img.naturalWidth  || this.$image.data('width'),
                h = img.naturalHeight || this.$image.data('height');
            this.aligner.init( w, h);
            this.aligner.align();
        },

        _alignImage: function() {
            this.aligner.align();
        },

        update: function(){
            this._alignImage();
        },

        destroy: function(){
            $(window).off( 'resize', this._alignImage );
        }
    });

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function ( options ) {
        var args = arguments,
            plugin = 'plugin_' + pluginName;

        if (options === undefined || typeof options === 'object') {
            return this.each(function () {

                if (!$.data(this, plugin)) {
                    $.data(this, plugin, new Plugin( this, options ));
                }
            });
        } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {

            var returns;

            this.each(function () {
                var instance = $.data(this, plugin);

                if (instance instanceof Plugin && typeof instance[options] === 'function') {
                    returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
                }

                // Allow instances to be destroyed via the 'destroy' method
                if (options === 'destroy') {
                  $.data(this, plugin, null);
                }
            });

            return returns !== undefined ? returns : this;
        }
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.fullscreenHero.js =================== 
 **/ 

;(function ( $, window, document, undefined ) {

    "use strict";

    // Create the defaults once
    var pluginName = "AuxinFullscreenHero";

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $(element);
        this._name = pluginName;
        this.init();
    }

    $.extend(Plugin.prototype, {
        init: function () {
            $(window).on( 'resize', this.update.bind( this ) );
            this.update();
        },

        update: function(){
            this.$element.height( Math.max(0, window.innerHeight - this.$element.offset().top) + 'px' );
        }
    });

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.animateAndRedirect.js =================== 
 **/ 

/**
 * A jQuery plugin for adding custom effect on changing pages
 *
 *  @author Averta
 *  @package Auxin Framework
 */
;(function ( $, window, document, undefined ) {

    "use strict";

    var pluginName = "AuxinAnimateAndRedirect",
        defaults = {
            target              : 'body',                                    // The container which needs to animating before and after loading page
            scrollFixTarget     : 'body',                                    // The container that checks for scroll top value on animation
            checkLinkTarget     : true,                                      // Check the anchor target attribute and only work on _self
            checkTargetEvents   : true,                                      // Don't work if the target has other click events
            skipRelativeLinks   : true,                                      // Skips those are relatively linked
            noAnimate           : '.aux-no-page-animate, .aux-lightbox-btn, [data-elementor-open-lightbox="yes"], [bdt-lightbox] a', // Targets by this class don't animate the page
            animateIn           : 'aux-show-page',                           // The animation class name of page
            animateOut          : 'aux-hide-page',                           // Hide animation class name of page
            beforeAnimateOut    : 'aux-before-hide-page',                    // It adds this class name before starting the hide animation
            disableOn           : null,                                      // Do not work if the link is a child of it
            delay               : 800,                                       // The delay between opening links, it recommended to be set same as animation duration
            fixScroll           : true,                                      // Fix scroll position on hiding the page
            linkClicked         : null,                                      // Callback for when link clicked
            startToHide         : null,                                      // Callback for when it starts to hide
            startToShow         : null                                       // Callback for when it starts to show
        };

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element   = element;
        this.$element  = $(element);
        this.settings  = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name     = pluginName;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {
        init: function () {
            var st = this.settings,
                evts = $._data( this.element, 'events' ) || {},
                $target = $( st.target ),
                $scrollTarget = $( st.scrollFixTarget ),
                linkHref = this.element.href;

            if ( st.animateIn && !$target.data( 'isAnimated' ) ) {
                $target.addClass( st.animateIn ).data( 'isAnimated', true );

                if ( st.startToShow ) {
                    st.startToShow();
                }
            }

            // Is it required to animate page?
            /* ------------------------------------------------------------------------------ */
            // no animation class name
            if ( st.noAnimate && this.$element.is( st.noAnimate ) ) { return; }

            // skip relative links
            if ( st.skipRelativeLinks && !(/http(s?):\/\//).test(this.$element.attr('href')) ) { return; }

            // target is blank
            if ( this.$element.attr( 'target' ) === '_blank' ) { return; }

            // link has click event
            if ( st.checkTargetEvents && ( 'click' in evts || this.element.onclick ) ) { return; }

            // link location is to current page
            if ( this.element.hash !== '' && this.element.origin + this.element.pathname + this.element.search === location.origin + location.pathname + location.search ) { return; }

            // check parents
            if ( st.disableOn && this.$element.parents( st.disableOn ).length ) { return; }
            /* ------------------------------------------------------------------------------ */

            this.$element.click( function( e ) {

                // check keys
                if ( e.ctrlKey || e.metaKey || e.which !== 1 ) {
                    return;
                }

                e.preventDefault();

                var scrollTop = document.documentElement.scrollTop;
                $target.addClass( st.beforeAnimateOut ).removeClass( st.animateIn );

                setTimeout( function(){
                    $target.addClass( st.animateOut );
                }, 1 );

                if ( st.fixScroll ) {
                   $scrollTarget.scrollTop( scrollTop );
                }

                if ( st.linkClicked ) {
                    st.linkClicked();
                }

                clearTimeout( this.timeout );
                this.timeout = setTimeout( function(){
                    window.location.href = this.element.href;

                    if ( st.startToHide ) {
                        st.startToHide();
                    }

                }.bind(this), st.delay );

            }.bind(this));
        }
    });

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/averta-jquery.parallaxBox.js =================== 
 **/ 

;(function ( $, window, document, undefined ) {

    "use strict";

    // Create the defaults once
    var pluginName = "AvertaParallaxBox",
        defaults = {
            targets       : 'aux-parallax', // target elements classname to move in parallax
            defaultDepth  : 0.5,            // default target parallax depth
            defaultOrigin : 'top',          // defalut target parallax origin, possible values: 'top', 'bottom', 'middle'
            forceHR       : false           // force use hardware accelerated
        },
        $window = $(window);

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.$element = $(element);
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {
        init: function () {
            this.$targets = this.$element.find( '.' + this.settings.targets );
            this._targetsNum = this.$targets.length;
            this._prefix = window._jcsspfx || '';

            if ( this._targetsNum === 0 ) {
                return;
            }

            $window.on( 'scroll resize', this.update.bind( this ) );
            this.update();
        },

        /**
         * Updates the position of parallax element in box
         * @param  {Element} $target
         * @param  {Number} scrollValue
         */
        _setPosition: function( $target, scrollValue ) {

            var origin       = $target.data( 'parallax-origin' ) || this.settings.defaultOrigin,
                depth        = $target.data( 'parallax-depth' )  || this.settings.defaultDepth,
                disablePoint = $target.data( 'parallax-off' ),
                absDepth     = Math.abs(depth),
                dir          = depth < 0 ? 1 : -1,
                type         = $target.data( 'parallax-type' )   || 'position',
                value;

            if ( disablePoint >= window.innerWidth ) {
                if ( $target.data( 'disabled' ) ) {
                    return;
                }

                $target.data( 'disabled', true );

                if ( type === 'background' ) {
                    $target[0].style.backgroundPosition = '';
                } else {
                    $target[0].style[this._prefix + 'Transform'] = '';
                }

                return;
            } else {
                $target.data( 'disabled', false );
            }

            switch( origin ) {
                case 'top':
                    value = Math.min( 0, this._spaceFromTop * absDepth );
                    break;
                case 'bottom':
                    value = Math.max( 0, this._spaceFromBot * absDepth );
                    break;
                case 'middle':
                    value = this._spaceFromMid * absDepth;
                    break;
            }

            if ( value < 0 ) {
                value = Math.max( value, -window.innerHeight );
            } else {
                value = Math.min( value, window.innerHeight );
            }

            if ( type === 'background' ) {
                $target[0].style.backgroundPosition = '50% ' + value * dir + 'px';
            } else {
                $target[0].style[this._prefix + 'Transform'] = 'translateY(' + value * dir + 'px)' + ( this.settings.forceHR ? ' translateZ(1px)' : '' );
            }
        },

        /* ------------------------------------------------------------------------------ */
        // public methods

        /**
         * update the parallax
         */
        update: function() {
            this._boxHeight    = this.$element.height();
            this._spaceFromTop = this.$element[0].getBoundingClientRect().top;
            this._spaceFromBot = window.innerHeight - this._boxHeight - this._spaceFromTop;
            this._spaceFromMid = window.innerHeight / 2 - this._boxHeight / 2 - this._spaceFromTop;
            for( var i = 0; i !== this._targetsNum; i++ ) {
                this._setPosition( this.$targets.eq(i), $window.scrollTop() );
            }
        },

        /**
         * Enables the parallax effect in box
         */
        enable: function() {
            $window.on( 'resize scroll', this.update );
            this.update();
        },

        /**
         * Disables the parallax effect in box
         */
        disable: function() {
            $window.off( 'resize scroll', this.update );
        },

        destroy: function() {
            this.disable();
        }
    });

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function( options ) {
        var _arguments = arguments;
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                 $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            } else if ( typeof options === 'string' && options.indexOf(0) !== '_' )  {
                // access to public methods method
                var plugin = $.data( this, "plugin_" + pluginName);
                plugin[options].apply( plugin, Array.prototype.slice.call( _arguments, 1 ) );
            }
        });
    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery.masonry.Animation.js =================== 
 **/ 

/**
 * A jQuery plugin for Adding Animation To Masonry
 *
 *  @author Averta
 *  @package Auxin Framework
 */
;( function( $, window, document, undefined ) {

    "use strict";

    var pluginName = "AuxinMasonryAnimate",
        defaults = {
            columns      : 3,
            tabletColumns: 2,
            mobileColumns: 1,
            columnClass  : 'aux-parallax-column',
            numItems     : 8,
            offset       : 0.2,
            minHeight    : 500,
            insetOffset  : 0.3
        },
        
        attributeDataMap = {
            'd-columns'   : 'columns',
            't-columns'   : 'tabletColumns',
            'm-columns'   : 'mobileColumns',
            'length'      : 'numItems',
            'offset'      : 'offset',
            'inset-offset': 'insetOffset',
        },

        $window = $(window)

    // The actual plugin constructor
    function Plugin ( element, options ) {

		this.element = element;
		this.$element = $(element);

		// create element attribute options object
		var elementData = {},
			tempData;
		for ( var attribute in attributeDataMap ) {
            tempData = this.$element.data(attribute);
			if ( tempData !== undefined ) {
				elementData[attributeDataMap[attribute]] = tempData;
			}
		}

		this.settings      = $.extend( {}, defaults, options, elementData );
		this._defaults     = defaults;
        this._name         = pluginName;
        this.items         = this.$element.find('.aux-parallax-item');
        this.oldBreakPoint = null,
        this.loading       = false;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend( Plugin.prototype, {

        /**
         * Init Function
        */
        init: function() {
            this.showLoading();
            $window.on('load resize', this.initializeLayout.bind( this ) );
            setTimeout( function(){
                this.hideLoading();                
            }.bind(this), 1000);
        },

        /**
         * a function for transform the columns based on short column on scroll
        */
        update: function() {
            
            if ( this.items.length <= this.columns.length || this.items.length % this.columns.length === 0 ) {
                this.columns.css( window._jcsspfx + 'Transform', 'none' );
                this.element.style.marginBottom = 0;
                return;
            };

            var shortCol       = this.shortCol,
                shortColRect   = shortCol.getBoundingClientRect(),
                refDelta       = window.innerHeight - ( window.innerHeight * this.settings.offset ) - ( shortColRect.top ) ,
                refDeltaNormal = refDelta / ( shortColRect.height ) ;

            this.element.style.marginBottom = ( shortCol.offsetHeight * this.settings.insetOffset - this.element.offsetHeight ) + 'px';
            
            if ( refDeltaNormal >= 1 ) {
                refDeltaNormal = 1;
            } else if ( refDeltaNormal <= 0 ) {
                refDeltaNormal = 0;
            }

            this.columns.each( function( index, column ) {  
                var colTransform = 0;

                var columnOffBot = column.offsetHeight + column.offsetTop,
                    shortColOffBot = ( shortColRect.height * this.settings.insetOffset ) + shortCol.offsetTop;
                
                colTransform = -1 * ( columnOffBot - shortColOffBot ) * refDeltaNormal;


                column.style[window._jcsspfx + 'Transform'] = 'translateY(' + colTransform + 'px)';
            }.bind( this ) );

        },

        /**
         * a function for initialze the layout based on breakpoints
        */

        initializeLayout: function(){
            var columnsNum,
                currentBreakPoint;

            if ( $window.width() < 1024 && $window.width() > 768 ) {
                columnsNum = this.settings.tabletColumns;
                currentBreakPoint = 'tablet';
            } else if ( $window.width() < 768 ) {
                columnsNum = this.settings.mobileColumns;
                currentBreakPoint = 'mobile';
            } else {
                columnsNum = this.settings.columns;
                currentBreakPoint = 'desktop';
            }

            
            if ( this.oldBreakPoint === currentBreakPoint ) return;
            this.oldBreakPoint = currentBreakPoint;

            var colObject = this.initializeColumn( columnsNum ),
                columns = [],
                self = this,
                shortCol;
            
            if ( this.columns ) {
                this.columns.remove();
            }

            Object.keys( colObject ).forEach( function ( key ) {
                var columnNode = document.createElement('div');
                    columnNode.classList.add( self.settings.columnClass + '-' + key );

                    colObject[key]['posts'].forEach( function( item ) {
                        columnNode.appendChild( item );
                    })

                    self.element.appendChild( columnNode );
                    columns.push( columnNode );

                    if ( !shortCol || columnNode.offsetHeight < shortCol.offsetHeight ) {
                        shortCol = columnNode;
                    }
            });

            this.shortCol = shortCol;
            this.columns  = $(columns);
            $window.on('scroll resize', this.update.bind( this ) );
        },

        /**
         * a function for return an object of columns with their items
        */
        initializeColumn: function( columnsNum ){
            
            if ( this.settings.numItems !== this.items.length ) {
                this.settings.numItems = this.items.length;
            }

            var colObj        = {},
                numExtraItems = this.settings.numItems < columnsNum ? 0 : this.settings.numItems % columnsNum,
                orderdItems   = 0 !== numExtraItems ?  this.items.slice( 0, -1 * numExtraItems ): this.items, 
                extraItems    = 0 !== numExtraItems ? this.items.slice( -1 * numExtraItems )    : null;

            for( var i = 1; i <= columnsNum; i++ ) {

                colObj[i] = {
                    posts   : [],
                }

            }

            orderdItems.each( function( index, item ) {
                var currentIndex = index + 1,
                    columnIndex = currentIndex % columnsNum ;
                    columnIndex = 0 === columnIndex ? columnsNum : columnIndex ;
                    colObj[columnIndex].posts.push(item);
            }); 
            

            if ( extraItems ) {
                switch( columnsNum ) {
                    case 5:
                        if ( 1 === 5 - numExtraItems ) {
                            extraItems.each( function( index, item ) {
                                var currentIndex = index + 1;
                                colObj[currentIndex].posts.push(item);
                            }); 
                        } else if ( 2 === 5 - numExtraItems ) {
                            extraItems.each( function( index, item ) {
                                var currentIndex = index * 2 + 1;
                                colObj[currentIndex].posts.push(item);
                            }); 
                        } else if ( 3 === 5 - numExtraItems ) {
                            extraItems.each( function( index, item ) {
                                var currentIndex = ( index + 1 ) * 2 ;
                                colObj[currentIndex].posts.push(item);
                            });     
                        } else {
                            extraItems.each( function( index, item ) {
                                var currentIndex = index + 1;
                                colObj[currentIndex].posts.push(item);
                            });    
                        }
                        break;
                    
                    case 4: 
                        if ( 1 === 4 - numExtraItems ) {
                            extraItems.each( function( index, item ) {
                                var currentIndex = index + 1;
                                colObj[currentIndex].posts.push(item);
                            }); 
                        } else if ( 2 === 4 - numExtraItems ) {
                            extraItems.each( function( index, item ) {
                                var currentIndex = ( index + 1 ) * 2 ;
                                colObj[currentIndex].posts.push(item);
                            }); 
                        } else {
                            extraItems.each( function( index, item ) {
                                var currentIndex = index + 1;
                                colObj[currentIndex].posts.push(item);
                            });   
                        }
                        break;
                    
                    case 3:
                        if ( 1 === 3 - numExtraItems ) { 
                            extraItems.each( function( index, item ) {
                                var currentIndex = index * 2 + 1;
                                colObj[currentIndex].posts.push(item);
                            }); 
                        } else {
                            extraItems.each( function( index, item ) {
                                var currentIndex = ( index + 1 ) * 2 ;
                                colObj[currentIndex].posts.push(item);
                            }); 
                        }
                        break;
                    
                    case 2: 
                        extraItems.each( function( index, item ) {
                            var currentIndex = index + 1;
                            colObj[currentIndex].posts.push(item)
                        });
                        break;
                    default:
                        extraItems.each( function( index, item ) {
                            var currentIndex = index + 1;
                            colObj[currentIndex].posts.push(item)
                        });
                }

            }

            return colObj;
        },   

        /**
         * a function for showing the loading
        */
        showLoading: function() {
            this.$element.css({
                'height' : this.settings.minHeight,
                'overflow' : 'hidden'
            });
            this.$element.find('.aux-items-loading').addClass('aux-loading-hide');
        },
        
        /**
         * a function for hiding the loading
        */

        hideLoading: function() {
            this.$element.css({
                'height' : 'auto',
                'overflow' : 'visible'
            });

            this.$element.find('.aux-items-loading').removeClass('aux-loading-hide');
        },

        /**
         * a function for insert items
        */
        insertItem: function( items ) {
            this.oldBreakPoint = null;
            this.columns.remove();
            this.items = items;
            this.initializeLayout();
        }
    } );

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[ pluginName ] = function( options ) {
        var _arguments = arguments;
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                 $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            } else if ( typeof options === 'string' && options.indexOf(0) !== '_' )  {
                // access to public methods method
                var plugin = $.data( this, "plugin_" + pluginName);
                plugin[options].apply( plugin, Array.prototype.slice.call( _arguments, 1 ) );
            }
        });
    };

} )( jQuery, window, document );


/*! 
 * 
 * ================== auxin/js/libs/perfect-scrollbar/perfect-scrollbar.js =================== 
 **/ 

/*!
 * perfect-scrollbar v1.1.0
 * (c) 2017 Hyunje Jun
 * @license MIT
 */
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
	typeof define === 'function' && define.amd ? define(factory) :
	(global.PerfectScrollbar = factory());
}(this, (function () { 'use strict';

function get(element) {
  return getComputedStyle(element);
}

function set(element, obj) {
  for (var key in obj) {
    var val = obj[key];
    if (typeof val === 'number') {
      val = val + "px";
    }
    element.style[key] = val;
  }
  return element;
}

function div(className) {
  var div = document.createElement('div');
  div.className = className;
  return div;
}

var elMatches =
  Element.prototype.matches ||
  Element.prototype.webkitMatchesSelector ||
  Element.prototype.msMatchesSelector;

function matches(element, query) {
  if (!elMatches) {
    throw new Error('No element matching method supported');
  }

  return elMatches.call(element, query);
}

function remove(element) {
  if (element.remove) {
    element.remove();
  } else {
    if (element.parentNode) {
      element.parentNode.removeChild(element);
    }
  }
}

function queryChildren(element, selector) {
  return Array.prototype.filter.call(element.children, function (child) { return matches(child, selector); }
  );
}

var cls = {
  main: 'ps',
  element: {
    thumb: function (x) { return ("ps__thumb-" + x); },
    rail: function (x) { return ("ps__rail-" + x); },
    consuming: 'ps__child--consume',
  },
  state: {
    focus: 'ps--focus',
    active: function (x) { return ("ps--active-" + x); },
    scrolling: function (x) { return ("ps--scrolling-" + x); },
  },
};

/*
 * Helper methods
 */
var scrollingClassTimeout = { x: null, y: null };

function addScrollingClass(i, x) {
  var classList = i.element.classList;
  var className = cls.state.scrolling(x);

  if (classList.contains(className)) {
    clearTimeout(scrollingClassTimeout[x]);
  } else {
    classList.add(className);
  }
}

function removeScrollingClass(i, x) {
  scrollingClassTimeout[x] = setTimeout(
    function () { return i.element.classList.remove(cls.state.scrolling(x)); },
    i.settings.scrollingThreshold
  );
}

function setScrollingClassInstantly(i, x) {
  addScrollingClass(i, x);
  removeScrollingClass(i, x);
}

var EventElement = function EventElement(element) {
  this.element = element;
  this.handlers = {};
};

var prototypeAccessors$1 = { isEmpty: { configurable: true } };

EventElement.prototype.bind = function bind (eventName, handler) {
  if (typeof this.handlers[eventName] === 'undefined') {
    this.handlers[eventName] = [];
  }
  this.handlers[eventName].push(handler);
  this.element.addEventListener(eventName, handler, false);
};

EventElement.prototype.unbind = function unbind (eventName, target) {
    var this$1 = this;

  this.handlers[eventName] = this.handlers[eventName].filter(function (handler) {
    if (target && handler !== target) {
      return true;
    }
    this$1.element.removeEventListener(eventName, handler, false);
    return false;
  });
};

EventElement.prototype.unbindAll = function unbindAll () {
    var this$1 = this;

  for (var name in this$1.handlers) {
    this$1.unbind(name);
  }
};

prototypeAccessors$1.isEmpty.get = function () {
    var this$1 = this;

  return Object.keys(this.handlers).every(
    function (key) { return this$1.handlers[key].length === 0; }
  );
};

Object.defineProperties( EventElement.prototype, prototypeAccessors$1 );

var EventManager = function EventManager() {
  this.eventElements = [];
};

EventManager.prototype.eventElement = function eventElement (element) {
  var ee = this.eventElements.filter(function (ee) { return ee.element === element; })[0];
  if (!ee) {
    ee = new EventElement(element);
    this.eventElements.push(ee);
  }
  return ee;
};

EventManager.prototype.bind = function bind (element, eventName, handler) {
  this.eventElement(element).bind(eventName, handler);
};

EventManager.prototype.unbind = function unbind (element, eventName, handler) {
  var ee = this.eventElement(element);
  ee.unbind(eventName, handler);

  if (ee.isEmpty) {
    // remove
    this.eventElements.splice(this.eventElements.indexOf(ee), 1);
  }
};

EventManager.prototype.unbindAll = function unbindAll () {
  this.eventElements.forEach(function (e) { return e.unbindAll(); });
  this.eventElements = [];
};

EventManager.prototype.once = function once (element, eventName, handler) {
  var ee = this.eventElement(element);
  var onceHandler = function (evt) {
    ee.unbind(eventName, onceHandler);
    handler(evt);
  };
  ee.bind(eventName, onceHandler);
};

function createEvent(name) {
  if (typeof window.CustomEvent === 'function') {
    return new CustomEvent(name);
  } else {
    var evt = document.createEvent('CustomEvent');
    evt.initCustomEvent(name, false, false, undefined);
    return evt;
  }
}

var updateScroll = function(i, axis, value, useScrollingClass) {
  if ( useScrollingClass === void 0 ) useScrollingClass = true;

  var fields;
  if (axis === 'top') {
    fields = [
      'contentHeight',
      'containerHeight',
      'scrollTop',
      'y',
      'up',
      'down' ];
  } else if (axis === 'left') {
    fields = [
      'contentWidth',
      'containerWidth',
      'scrollLeft',
      'x',
      'left',
      'right' ];
  } else {
    throw new Error('A proper axis should be provided');
  }

  updateScroll$1(i, value, fields, useScrollingClass);
};

function updateScroll$1(
  i,
  value,
  ref,
  useScrollingClass
) {
  var contentHeight = ref[0];
  var containerHeight = ref[1];
  var scrollTop = ref[2];
  var y = ref[3];
  var up = ref[4];
  var down = ref[5];

  var element = i.element;

  var mitigated = false;

  // reset reach
  i.reach[y] = null;

  // don't allow negative scroll offset
  if (value <= 0) {
    value = 0;
    i.reach[y] = 'start';
  }

  // don't allow scroll past container
  if (value >= i[contentHeight] - i[containerHeight]) {
    value = i[contentHeight] - i[containerHeight];

    // mitigates rounding errors on non-subpixel scroll values
    if (value - element[scrollTop] <= 2) {
      mitigated = true;
    }

    i.reach[y] = 'end';
  }

  var diff = element[scrollTop] - value;

  if (diff) {
    element.dispatchEvent(createEvent(("ps-scroll-" + y)));

    if (diff > 0) {
      element.dispatchEvent(createEvent(("ps-scroll-" + up)));
    } else {
      element.dispatchEvent(createEvent(("ps-scroll-" + down)));
    }

    if (!mitigated) {
      element[scrollTop] = value;
    }

    if (i.reach[y]) {
      element.dispatchEvent(createEvent(("ps-" + y + "-reach-" + (i.reach[y]))));
    }

    if (useScrollingClass) {
      setScrollingClassInstantly(i, y);
    }
  }
}

function toInt(x) {
  return parseInt(x, 10) || 0;
}

function isEditable(el) {
  return (
    matches(el, 'input,[contenteditable]') ||
    matches(el, 'select,[contenteditable]') ||
    matches(el, 'textarea,[contenteditable]') ||
    matches(el, 'button,[contenteditable]')
  );
}

function outerWidth(element) {
  var styles = get(element);
  return (
    toInt(styles.width) +
    toInt(styles.paddingLeft) +
    toInt(styles.paddingRight) +
    toInt(styles.borderLeftWidth) +
    toInt(styles.borderRightWidth)
  );
}

var env = {
  isWebKit: document && 'WebkitAppearance' in document.documentElement.style,
  supportsTouch:
    window &&
    ('ontouchstart' in window ||
      (window.DocumentTouch && document instanceof window.DocumentTouch)),
  supportsIePointer: navigator && navigator.msMaxTouchPoints,
};

var updateGeometry = function(i) {
  var element = i.element;

  i.containerWidth = element.clientWidth;
  i.containerHeight = element.clientHeight;
  i.contentWidth = element.scrollWidth;
  i.contentHeight = element.scrollHeight;

  if (!element.contains(i.scrollbarXRail)) {
    // clean up and append
    queryChildren(element, cls.element.rail('x')).forEach(function (el) { return remove(el); }
    );
    element.appendChild(i.scrollbarXRail);
  }
  if (!element.contains(i.scrollbarYRail)) {
    // clean up and append
    queryChildren(element, cls.element.rail('y')).forEach(function (el) { return remove(el); }
    );
    element.appendChild(i.scrollbarYRail);
  }

  if (
    !i.settings.suppressScrollX &&
    i.containerWidth + i.settings.scrollXMarginOffset < i.contentWidth
  ) {
    i.scrollbarXActive = true;
    i.railXWidth = i.containerWidth - i.railXMarginWidth;
    i.railXRatio = i.containerWidth / i.railXWidth;
    i.scrollbarXWidth = getThumbSize(
      i,
      toInt(i.railXWidth * i.containerWidth / i.contentWidth)
    );
    i.scrollbarXLeft = toInt(
      (i.negativeScrollAdjustment + element.scrollLeft) *
        (i.railXWidth - i.scrollbarXWidth) /
        (i.contentWidth - i.containerWidth)
    );
  } else {
    i.scrollbarXActive = false;
  }

  if (
    !i.settings.suppressScrollY &&
    i.containerHeight + i.settings.scrollYMarginOffset < i.contentHeight
  ) {
    i.scrollbarYActive = true;
    i.railYHeight = i.containerHeight - i.railYMarginHeight;
    i.railYRatio = i.containerHeight / i.railYHeight;
    i.scrollbarYHeight = getThumbSize(
      i,
      toInt(i.railYHeight * i.containerHeight / i.contentHeight)
    );
    i.scrollbarYTop = toInt(
      element.scrollTop *
        (i.railYHeight - i.scrollbarYHeight) /
        (i.contentHeight - i.containerHeight)
    );
  } else {
    i.scrollbarYActive = false;
  }

  if (i.scrollbarXLeft >= i.railXWidth - i.scrollbarXWidth) {
    i.scrollbarXLeft = i.railXWidth - i.scrollbarXWidth;
  }
  if (i.scrollbarYTop >= i.railYHeight - i.scrollbarYHeight) {
    i.scrollbarYTop = i.railYHeight - i.scrollbarYHeight;
  }

  updateCss(element, i);

  if (i.scrollbarXActive) {
    element.classList.add(cls.state.active('x'));
  } else {
    element.classList.remove(cls.state.active('x'));
    i.scrollbarXWidth = 0;
    i.scrollbarXLeft = 0;
    updateScroll(i, 'left', 0);
  }
  if (i.scrollbarYActive) {
    element.classList.add(cls.state.active('y'));
  } else {
    element.classList.remove(cls.state.active('y'));
    i.scrollbarYHeight = 0;
    i.scrollbarYTop = 0;
    updateScroll(i, 'top', 0);
  }
};

function getThumbSize(i, thumbSize) {
  if (i.settings.minScrollbarLength) {
    thumbSize = Math.max(thumbSize, i.settings.minScrollbarLength);
  }
  if (i.settings.maxScrollbarLength) {
    thumbSize = Math.min(thumbSize, i.settings.maxScrollbarLength);
  }
  return thumbSize;
}

function updateCss(element, i) {
  var xRailOffset = { width: i.railXWidth };
  if (i.isRtl) {
    xRailOffset.left =
      i.negativeScrollAdjustment +
      element.scrollLeft +
      i.containerWidth -
      i.contentWidth;
  } else {
    xRailOffset.left = element.scrollLeft;
  }
  if (i.isScrollbarXUsingBottom) {
    xRailOffset.bottom = i.scrollbarXBottom - element.scrollTop;
  } else {
    xRailOffset.top = i.scrollbarXTop + element.scrollTop;
  }
  set(i.scrollbarXRail, xRailOffset);

  var yRailOffset = { top: element.scrollTop, height: i.railYHeight };
  if (i.isScrollbarYUsingRight) {
    if (i.isRtl) {
      yRailOffset.right =
        i.contentWidth -
        (i.negativeScrollAdjustment + element.scrollLeft) -
        i.scrollbarYRight -
        i.scrollbarYOuterWidth;
    } else {
      yRailOffset.right = i.scrollbarYRight - element.scrollLeft;
    }
  } else {
    if (i.isRtl) {
      yRailOffset.left =
        i.negativeScrollAdjustment +
        element.scrollLeft +
        i.containerWidth * 2 -
        i.contentWidth -
        i.scrollbarYLeft -
        i.scrollbarYOuterWidth;
    } else {
      yRailOffset.left = i.scrollbarYLeft + element.scrollLeft;
    }
  }
  set(i.scrollbarYRail, yRailOffset);

  set(i.scrollbarX, {
    left: i.scrollbarXLeft,
    width: i.scrollbarXWidth - i.railBorderXWidth,
  });
  set(i.scrollbarY, {
    top: i.scrollbarYTop,
    height: i.scrollbarYHeight - i.railBorderYWidth,
  });
}

var clickRail = function(i) {
  var element = i.element;

  i.event.bind(i.scrollbarY, 'mousedown', function (e) { return e.stopPropagation(); });
  i.event.bind(i.scrollbarYRail, 'mousedown', function (e) {
    var positionTop =
      e.pageY -
      window.pageYOffset -
      i.scrollbarYRail.getBoundingClientRect().top;
    var direction = positionTop > i.scrollbarYTop ? 1 : -1;

    updateScroll(i, 'top', element.scrollTop + direction * i.containerHeight);
    updateGeometry(i);

    e.stopPropagation();
  });

  i.event.bind(i.scrollbarX, 'mousedown', function (e) { return e.stopPropagation(); });
  i.event.bind(i.scrollbarXRail, 'mousedown', function (e) {
    var positionLeft =
      e.pageX -
      window.pageXOffset -
      i.scrollbarXRail.getBoundingClientRect().left;
    var direction = positionLeft > i.scrollbarXLeft ? 1 : -1;

    updateScroll(i, 'left', element.scrollLeft + direction * i.containerWidth);
    updateGeometry(i);

    e.stopPropagation();
  });
};

var dragThumb = function(i) {
  bindMouseScrollHandler(i, [
    'containerWidth',
    'contentWidth',
    'pageX',
    'railXWidth',
    'scrollbarX',
    'scrollbarXWidth',
    'scrollLeft',
    'left',
    'x' ]);
  bindMouseScrollHandler(i, [
    'containerHeight',
    'contentHeight',
    'pageY',
    'railYHeight',
    'scrollbarY',
    'scrollbarYHeight',
    'scrollTop',
    'top',
    'y' ]);
};

function bindMouseScrollHandler(
  i,
  ref
) {
  var containerHeight = ref[0];
  var contentHeight = ref[1];
  var pageY = ref[2];
  var railYHeight = ref[3];
  var scrollbarY = ref[4];
  var scrollbarYHeight = ref[5];
  var scrollTop = ref[6];
  var top = ref[7];
  var y = ref[8];

  var element = i.element;

  var startingScrollTop = null;
  var startingMousePageY = null;
  var scrollBy = null;

  function mouseMoveHandler(e) {
    updateScroll(
      i,
      top,
      startingScrollTop + scrollBy * (e[pageY] - startingMousePageY),
      false
    );
    addScrollingClass(i, y);
    updateGeometry(i);

    e.stopPropagation();
    e.preventDefault();
  }

  function mouseUpHandler() {
    removeScrollingClass(i, y);
    i.event.unbind(i.ownerDocument, 'mousemove', mouseMoveHandler);
  }

  i.event.bind(i[scrollbarY], 'mousedown', function (e) {
    startingScrollTop = element[scrollTop];
    startingMousePageY = e[pageY];
    scrollBy =
      (i[contentHeight] - i[containerHeight]) /
      (i[railYHeight] - i[scrollbarYHeight]);

    i.event.bind(i.ownerDocument, 'mousemove', mouseMoveHandler);
    i.event.once(i.ownerDocument, 'mouseup', mouseUpHandler);

    e.stopPropagation();
    e.preventDefault();
  });
}

var keyboard = function(i) {
  var element = i.element;

  var elementHovered = function () { return matches(element, ':hover'); };
  var scrollbarFocused = function () { return matches(i.scrollbarX, ':focus') || matches(i.scrollbarY, ':focus'); };

  function shouldPreventDefault(deltaX, deltaY) {
    var scrollTop = element.scrollTop;
    if (deltaX === 0) {
      if (!i.scrollbarYActive) {
        return false;
      }
      if (
        (scrollTop === 0 && deltaY > 0) ||
        (scrollTop >= i.contentHeight - i.containerHeight && deltaY < 0)
      ) {
        return !i.settings.wheelPropagation;
      }
    }

    var scrollLeft = element.scrollLeft;
    if (deltaY === 0) {
      if (!i.scrollbarXActive) {
        return false;
      }
      if (
        (scrollLeft === 0 && deltaX < 0) ||
        (scrollLeft >= i.contentWidth - i.containerWidth && deltaX > 0)
      ) {
        return !i.settings.wheelPropagation;
      }
    }
    return true;
  }

  i.event.bind(i.ownerDocument, 'keydown', function (e) {
    if (
      (e.isDefaultPrevented && e.isDefaultPrevented()) ||
      e.defaultPrevented
    ) {
      return;
    }

    if (!elementHovered() && !scrollbarFocused()) {
      return;
    }

    var activeElement = document.activeElement
      ? document.activeElement
      : i.ownerDocument.activeElement;
    if (activeElement) {
      if (activeElement.tagName === 'IFRAME') {
        activeElement = activeElement.contentDocument.activeElement;
      } else {
        // go deeper if element is a webcomponent
        while (activeElement.shadowRoot) {
          activeElement = activeElement.shadowRoot.activeElement;
        }
      }
      if (isEditable(activeElement)) {
        return;
      }
    }

    var deltaX = 0;
    var deltaY = 0;

    switch (e.which) {
      case 37: // left
        if (e.metaKey) {
          deltaX = -i.contentWidth;
        } else if (e.altKey) {
          deltaX = -i.containerWidth;
        } else {
          deltaX = -30;
        }
        break;
      case 38: // up
        if (e.metaKey) {
          deltaY = i.contentHeight;
        } else if (e.altKey) {
          deltaY = i.containerHeight;
        } else {
          deltaY = 30;
        }
        break;
      case 39: // right
        if (e.metaKey) {
          deltaX = i.contentWidth;
        } else if (e.altKey) {
          deltaX = i.containerWidth;
        } else {
          deltaX = 30;
        }
        break;
      case 40: // down
        if (e.metaKey) {
          deltaY = -i.contentHeight;
        } else if (e.altKey) {
          deltaY = -i.containerHeight;
        } else {
          deltaY = -30;
        }
        break;
      case 32: // space bar
        if (e.shiftKey) {
          deltaY = i.containerHeight;
        } else {
          deltaY = -i.containerHeight;
        }
        break;
      case 33: // page up
        deltaY = i.containerHeight;
        break;
      case 34: // page down
        deltaY = -i.containerHeight;
        break;
      case 36: // home
        deltaY = i.contentHeight;
        break;
      case 35: // end
        deltaY = -i.contentHeight;
        break;
      default:
        return;
    }

    if (i.settings.suppressScrollX && deltaX !== 0) {
      return;
    }
    if (i.settings.suppressScrollY && deltaY !== 0) {
      return;
    }

    updateScroll(i, 'top', element.scrollTop - deltaY);
    updateScroll(i, 'left', element.scrollLeft + deltaX);
    updateGeometry(i);

    if (shouldPreventDefault(deltaX, deltaY)) {
      e.preventDefault();
    }
  });
};

var wheel = function(i) {
  var element = i.element;

  function shouldPreventDefault(deltaX, deltaY) {
    var scrollTop = element.scrollTop;
    if (deltaX === 0) {
      if (!i.scrollbarYActive) {
        return false;
      }
      if (
        (scrollTop === 0 && deltaY > 0) ||
        (scrollTop >= i.contentHeight - i.containerHeight && deltaY < 0)
      ) {
        return !i.settings.wheelPropagation;
      }
    }

    var scrollLeft = element.scrollLeft;
    if (deltaY === 0) {
      if (!i.scrollbarXActive) {
        return false;
      }
      if (
        (scrollLeft === 0 && deltaX < 0) ||
        (scrollLeft >= i.contentWidth - i.containerWidth && deltaX > 0)
      ) {
        return !i.settings.wheelPropagation;
      }
    }
    return true;
  }

  function getDeltaFromEvent(e) {
    var deltaX = e.deltaX;
    var deltaY = -1 * e.deltaY;

    if (typeof deltaX === 'undefined' || typeof deltaY === 'undefined') {
      // OS X Safari
      deltaX = -1 * e.wheelDeltaX / 6;
      deltaY = e.wheelDeltaY / 6;
    }

    if (e.deltaMode && e.deltaMode === 1) {
      // Firefox in deltaMode 1: Line scrolling
      deltaX *= 10;
      deltaY *= 10;
    }

    if (deltaX !== deltaX && deltaY !== deltaY /* NaN checks */) {
      // IE in some mouse drivers
      deltaX = 0;
      deltaY = e.wheelDelta;
    }

    if (e.shiftKey) {
      // reverse axis with shift key
      return [-deltaY, -deltaX];
    }
    return [deltaX, deltaY];
  }

  function shouldBeConsumedByChild(target, deltaX, deltaY) {
    // FIXME: this is a workaround for <select> issue in FF and IE #571
    if (!env.isWebKit && element.querySelector('select:focus')) {
      return true;
    }

    if (!element.contains(target)) {
      return false;
    }

    var cursor = target;

    while (cursor && cursor !== element) {
      if (cursor.classList.contains(cls.element.consuming)) {
        return true;
      }

      var style = get(cursor);
      var overflow = [style.overflow, style.overflowX, style.overflowY].join(
        ''
      );

      // if scrollable
      if (overflow.match(/(scroll|auto)/)) {
        var maxScrollTop = cursor.scrollHeight - cursor.clientHeight;
        if (maxScrollTop > 0) {
          if (
            !(cursor.scrollTop === 0 && deltaY > 0) &&
            !(cursor.scrollTop === maxScrollTop && deltaY < 0)
          ) {
            return true;
          }
        }
        var maxScrollLeft = cursor.scrollLeft - cursor.clientWidth;
        if (maxScrollLeft > 0) {
          if (
            !(cursor.scrollLeft === 0 && deltaX < 0) &&
            !(cursor.scrollLeft === maxScrollLeft && deltaX > 0)
          ) {
            return true;
          }
        }
      }

      cursor = cursor.parentNode;
    }

    return false;
  }

  function mousewheelHandler(e) {
    var ref = getDeltaFromEvent(e);
    var deltaX = ref[0];
    var deltaY = ref[1];

    if (shouldBeConsumedByChild(e.target, deltaX, deltaY)) {
      return;
    }

    var shouldPrevent = false;
    if (!i.settings.useBothWheelAxes) {
      // deltaX will only be used for horizontal scrolling and deltaY will
      // only be used for vertical scrolling - this is the default
      updateScroll(
        i,
        'top',
        element.scrollTop - deltaY * i.settings.wheelSpeed
      );
      updateScroll(
        i,
        'left',
        element.scrollLeft + deltaX * i.settings.wheelSpeed
      );
    } else if (i.scrollbarYActive && !i.scrollbarXActive) {
      // only vertical scrollbar is active and useBothWheelAxes option is
      // active, so let's scroll vertical bar using both mouse wheel axes
      if (deltaY) {
        updateScroll(
          i,
          'top',
          element.scrollTop - deltaY * i.settings.wheelSpeed
        );
      } else {
        updateScroll(
          i,
          'top',
          element.scrollTop + deltaX * i.settings.wheelSpeed
        );
      }
      shouldPrevent = true;
    } else if (i.scrollbarXActive && !i.scrollbarYActive) {
      // useBothWheelAxes and only horizontal bar is active, so use both
      // wheel axes for horizontal bar
      if (deltaX) {
        updateScroll(
          i,
          'left',
          element.scrollLeft + deltaX * i.settings.wheelSpeed
        );
      } else {
        updateScroll(
          i,
          'left',
          element.scrollLeft - deltaY * i.settings.wheelSpeed
        );
      }
      shouldPrevent = true;
    }

    updateGeometry(i);

    shouldPrevent = shouldPrevent || shouldPreventDefault(deltaX, deltaY);
    if (shouldPrevent) {
      e.stopPropagation();
      e.preventDefault();
    }
  }

  if (typeof window.onwheel !== 'undefined') {
    i.event.bind(element, 'wheel', mousewheelHandler);
  } else if (typeof window.onmousewheel !== 'undefined') {
    i.event.bind(element, 'mousewheel', mousewheelHandler);
  }
};

var touch = function(i) {
  if (!env.supportsTouch && !env.supportsIePointer) {
    return;
  }

  var element = i.element;

  function shouldStopOrPrevent(deltaX, deltaY) {
    var scrollTop = element.scrollTop;
    var scrollLeft = element.scrollLeft;
    var magnitudeX = Math.abs(deltaX);
    var magnitudeY = Math.abs(deltaY);

    if (magnitudeY > magnitudeX) {
      // user is perhaps trying to swipe up/down the page

      if (
        (deltaY < 0 && scrollTop === i.contentHeight - i.containerHeight) ||
        (deltaY > 0 && scrollTop === 0)
      ) {
        // set prevent for mobile Chrome refresh
        return {
          stop: !i.settings.swipePropagation,
          prevent: window.scrollY === 0,
        };
      }
    } else if (magnitudeX > magnitudeY) {
      // user is perhaps trying to swipe left/right across the page

      if (
        (deltaX < 0 && scrollLeft === i.contentWidth - i.containerWidth) ||
        (deltaX > 0 && scrollLeft === 0)
      ) {
        return { stop: !i.settings.swipePropagation, prevent: true };
      }
    }

    return { stop: true, prevent: true };
  }

  function applyTouchMove(differenceX, differenceY) {
    updateScroll(i, 'top', element.scrollTop - differenceY);
    updateScroll(i, 'left', element.scrollLeft - differenceX);

    updateGeometry(i);
  }

  var startOffset = {};
  var startTime = 0;
  var speed = {};
  var easingLoop = null;
  var inGlobalTouch = false;
  var inLocalTouch = false;

  function globalTouchStart() {
    inGlobalTouch = true;
  }
  function globalTouchEnd() {
    inGlobalTouch = false;
  }

  function getTouch(e) {
    if (e.targetTouches) {
      return e.targetTouches[0];
    } else {
      // Maybe IE pointer
      return e;
    }
  }

  function shouldHandle(e) {
    if (e.pointerType && e.pointerType === 'pen' && e.buttons === 0) {
      return false;
    }
    if (e.targetTouches && e.targetTouches.length === 1) {
      return true;
    }
    if (
      e.pointerType &&
      e.pointerType !== 'mouse' &&
      e.pointerType !== e.MSPOINTER_TYPE_MOUSE
    ) {
      return true;
    }
    return false;
  }

  function touchStart(e) {
    if (!shouldHandle(e)) {
      return;
    }

    inLocalTouch = true;

    var touch = getTouch(e);

    startOffset.pageX = touch.pageX;
    startOffset.pageY = touch.pageY;

    startTime = new Date().getTime();

    if (easingLoop !== null) {
      clearInterval(easingLoop);
    }

    e.stopPropagation();
  }

  function touchMove(e) {
    if (!inLocalTouch && i.settings.swipePropagation) {
      touchStart(e);
    }
    if (!inGlobalTouch && inLocalTouch && shouldHandle(e)) {
      var touch = getTouch(e);

      var currentOffset = { pageX: touch.pageX, pageY: touch.pageY };

      var differenceX = currentOffset.pageX - startOffset.pageX;
      var differenceY = currentOffset.pageY - startOffset.pageY;

      applyTouchMove(differenceX, differenceY);
      startOffset = currentOffset;

      var currentTime = new Date().getTime();

      var timeGap = currentTime - startTime;
      if (timeGap > 0) {
        speed.x = differenceX / timeGap;
        speed.y = differenceY / timeGap;
        startTime = currentTime;
      }

      var ref = shouldStopOrPrevent(differenceX, differenceY);
      var stop = ref.stop;
      var prevent = ref.prevent;
      if (stop) { e.stopPropagation(); }
      if (prevent) { e.preventDefault(); }
    }
  }
  function touchEnd() {
    if (!inGlobalTouch && inLocalTouch) {
      inLocalTouch = false;

      if (i.settings.swipeEasing) {
        clearInterval(easingLoop);
        easingLoop = setInterval(function() {
          if (i.isInitialized) {
            clearInterval(easingLoop);
            return;
          }

          if (!speed.x && !speed.y) {
            clearInterval(easingLoop);
            return;
          }

          if (Math.abs(speed.x) < 0.01 && Math.abs(speed.y) < 0.01) {
            clearInterval(easingLoop);
            return;
          }

          applyTouchMove(speed.x * 30, speed.y * 30);

          speed.x *= 0.8;
          speed.y *= 0.8;
        }, 10);
      }
    }
  }

  if (env.supportsTouch) {
    i.event.bind(window, 'touchstart', globalTouchStart);
    i.event.bind(window, 'touchend', globalTouchEnd);
    i.event.bind(element, 'touchstart', touchStart);
    i.event.bind(element, 'touchmove', touchMove);
    i.event.bind(element, 'touchend', touchEnd);
  } else if (env.supportsIePointer) {
    if (window.PointerEvent) {
      i.event.bind(window, 'pointerdown', globalTouchStart);
      i.event.bind(window, 'pointerup', globalTouchEnd);
      i.event.bind(element, 'pointerdown', touchStart);
      i.event.bind(element, 'pointermove', touchMove);
      i.event.bind(element, 'pointerup', touchEnd);
    } else if (window.MSPointerEvent) {
      i.event.bind(window, 'MSPointerDown', globalTouchStart);
      i.event.bind(window, 'MSPointerUp', globalTouchEnd);
      i.event.bind(element, 'MSPointerDown', touchStart);
      i.event.bind(element, 'MSPointerMove', touchMove);
      i.event.bind(element, 'MSPointerUp', touchEnd);
    }
  }
};

var defaultSettings = function () { return ({
  handlers: ['click-rail', 'drag-thumb', 'keyboard', 'wheel', 'touch'],
  maxScrollbarLength: null,
  minScrollbarLength: null,
  scrollingThreshold: 1000,
  scrollXMarginOffset: 0,
  scrollYMarginOffset: 0,
  suppressScrollX: false,
  suppressScrollY: false,
  swipePropagation: true,
  swipeEasing: true,
  useBothWheelAxes: false,
  wheelPropagation: false,
  wheelSpeed: 1,
}); };

var handlers = {
  'click-rail': clickRail,
  'drag-thumb': dragThumb,
  keyboard: keyboard,
  wheel: wheel,
  touch: touch,
};

var PerfectScrollbar = function PerfectScrollbar(element, userSettings) {
  var this$1 = this;
  if ( userSettings === void 0 ) userSettings = {};

  if (typeof element === 'string') {
    element = document.querySelector(element);
  }

  if (!element || !element.nodeName) {
    throw new Error('no element is specified to initialize PerfectScrollbar');
  }

  this.element = element;

  element.classList.add(cls.main);

  this.settings = defaultSettings();
  for (var key in userSettings) {
    this$1.settings[key] = userSettings[key];
  }

  this.containerWidth = null;
  this.containerHeight = null;
  this.contentWidth = null;
  this.contentHeight = null;

  var focus = function () { return element.classList.add(cls.state.focus); };
  var blur = function () { return element.classList.remove(cls.state.focus); };

  this.isRtl = get(element).direction === 'rtl';
  this.isNegativeScroll = (function () {
    var originalScrollLeft = element.scrollLeft;
    var result = null;
    element.scrollLeft = -1;
    result = element.scrollLeft < 0;
    element.scrollLeft = originalScrollLeft;
    return result;
  })();
  this.negativeScrollAdjustment = this.isNegativeScroll
    ? element.scrollWidth - element.clientWidth
    : 0;
  this.event = new EventManager();
  this.ownerDocument = element.ownerDocument || document;

  this.scrollbarXRail = div(cls.element.rail('x'));
  element.appendChild(this.scrollbarXRail);
  this.scrollbarX = div(cls.element.thumb('x'));
  this.scrollbarXRail.appendChild(this.scrollbarX);
  this.scrollbarX.setAttribute('tabindex', 0);
  this.event.bind(this.scrollbarX, 'focus', focus);
  this.event.bind(this.scrollbarX, 'blur', blur);
  this.scrollbarXActive = null;
  this.scrollbarXWidth = null;
  this.scrollbarXLeft = null;
  var railXStyle = get(this.scrollbarXRail);
  this.scrollbarXBottom = parseInt(railXStyle.bottom, 10);
  if (isNaN(this.scrollbarXBottom)) {
    this.isScrollbarXUsingBottom = false;
    this.scrollbarXTop = toInt(railXStyle.top);
  } else {
    this.isScrollbarXUsingBottom = true;
  }
  this.railBorderXWidth =
    toInt(railXStyle.borderLeftWidth) + toInt(railXStyle.borderRightWidth);
  // Set rail to display:block to calculate margins
  set(this.scrollbarXRail, { display: 'block' });
  this.railXMarginWidth =
    toInt(railXStyle.marginLeft) + toInt(railXStyle.marginRight);
  set(this.scrollbarXRail, { display: '' });
  this.railXWidth = null;
  this.railXRatio = null;

  this.scrollbarYRail = div(cls.element.rail('y'));
  element.appendChild(this.scrollbarYRail);
  this.scrollbarY = div(cls.element.thumb('y'));
  this.scrollbarYRail.appendChild(this.scrollbarY);
  this.scrollbarY.setAttribute('tabindex', 0);
  this.event.bind(this.scrollbarY, 'focus', focus);
  this.event.bind(this.scrollbarY, 'blur', blur);
  this.scrollbarYActive = null;
  this.scrollbarYHeight = null;
  this.scrollbarYTop = null;
  var railYStyle = get(this.scrollbarYRail);
  this.scrollbarYRight = parseInt(railYStyle.right, 10);
  if (isNaN(this.scrollbarYRight)) {
    this.isScrollbarYUsingRight = false;
    this.scrollbarYLeft = toInt(railYStyle.left);
  } else {
    this.isScrollbarYUsingRight = true;
  }
  this.scrollbarYOuterWidth = this.isRtl ? outerWidth(this.scrollbarY) : null;
  this.railBorderYWidth =
    toInt(railYStyle.borderTopWidth) + toInt(railYStyle.borderBottomWidth);
  set(this.scrollbarYRail, { display: 'block' });
  this.railYMarginHeight =
    toInt(railYStyle.marginTop) + toInt(railYStyle.marginBottom);
  set(this.scrollbarYRail, { display: '' });
  this.railYHeight = null;
  this.railYRatio = null;

  this.reach = {
    x:
      element.scrollLeft <= 0
        ? 'start'
        : element.scrollLeft >= this.contentWidth - this.containerWidth
          ? 'end'
          : null,
    y:
      element.scrollTop <= 0
        ? 'start'
        : element.scrollTop >= this.contentHeight - this.containerHeight
          ? 'end'
          : null,
  };

  this.settings.handlers.forEach(function (handlerName) { return handlers[handlerName](this$1); });

  this.event.bind(this.element, 'scroll', function () { return updateGeometry(this$1); });
  updateGeometry(this);
};

var prototypeAccessors = { isInitialized: { configurable: true } };

prototypeAccessors.isInitialized.get = function () {
  return this.element.classList.contains(cls.main);
};

PerfectScrollbar.prototype.update = function update () {
  if (!this.isInitialized) {
    return;
  }

  // Recalcuate negative scrollLeft adjustment
  this.negativeScrollAdjustment = this.isNegativeScroll
    ? this.element.scrollWidth - this.element.clientWidth
    : 0;

  // Recalculate rail margins
  set(this.scrollbarXRail, { display: 'block' });
  set(this.scrollbarYRail, { display: 'block' });
  this.railXMarginWidth =
    toInt(get(this.scrollbarXRail).marginLeft) +
    toInt(get(this.scrollbarXRail).marginRight);
  this.railYMarginHeight =
    toInt(get(this.scrollbarYRail).marginTop) +
    toInt(get(this.scrollbarYRail).marginBottom);

  // Hide scrollbars not to affect scrollWidth and scrollHeight
  set(this.scrollbarXRail, { display: 'none' });
  set(this.scrollbarYRail, { display: 'none' });

  updateGeometry(this);

  set(this.scrollbarXRail, { display: '' });
  set(this.scrollbarYRail, { display: '' });
};

PerfectScrollbar.prototype.destroy = function destroy () {
  if (!this.isInitialized) {
    return;
  }

  this.event.unbindAll();
  remove(this.scrollbarX);
  remove(this.scrollbarY);
  remove(this.scrollbarXRail);
  remove(this.scrollbarYRail);
  this.removePsClasses();

  // unset elements
  this.element = null;
  this.scrollbarX = null;
  this.scrollbarY = null;
  this.scrollbarXRail = null;
  this.scrollbarYRail = null;
};

PerfectScrollbar.prototype.removePsClasses = function removePsClasses () {
  this.element.className = this.element.className
    .split(' ')
    .filter(function (name) { return !name.match(/^ps([-_].+|)$/); })
    .join(' ');
};

Object.defineProperties( PerfectScrollbar.prototype, prototypeAccessors );

return PerfectScrollbar;

})));


/*! 
 * 
 * ================== js/libs/plugins/averta/averta-js.mastercarousel.js =================== 
 **/ 

/*!
 *  Master Carousel - v1.2.6 (2018-01-17)
 *  http://www.averta.net
 *
 *  A flexible, touch and lightweight carousel script for Auxin
 *
 *  Copyright (c) 2010-2018 averta <www.averta.net>
 *  License: All rights reserved.
 */


/* -------------------- src/MasterCarousel.js -------------------- */


;(function ( $, window, document, undefined ) {

    "use strict";


    /**
     * Master Carousel constructor
     * @param {jQueryObject|jQuerySelector} target
     * @param {Object}                      options
     */
    var MasterCarousel = function ( target , options ) {

        // carousel default options.
        this.defaultOptions = {
            viewClass           : 'mc-view',               // view css class name
            containerClass      : 'mc-view-container',     // view items container css class name
            itemClass           : 'mc-item',               // carousel item class name
            loop                : true,                    // enables loop navigation
            space               : 2,                       // specifies the space between items in pixels
            dir                 : 'h',                     // specifies the direction of navigation
            columns             : 4,                       // numbers of columns in view
            navigation          : 'scroll',                // navigation type: 'scroll', 'perpage', 'peritem'
            center              : false,                   // aligns items to the center of carousel
            speed               : 12,                      // the scrolling speed
            minSnappingSpeed    : 0.51,                    // minimum snapping speed
            swipe               : true,                    // enables the swipe gesture
            mouseSwipe          : true,                    // enables swiping navigation with mouse
            startItem           : null,                    // specifies the starting item after view initialization
            rtl                 : false,                   // switches to RTL direction
            view                : 'basic',                 // specifies type of appearing items in carousel
            item                : 'basic',                 // specifies the type of item class in carousel
            disablePlugins      : []                       // disables plugins for this instance of carousel (list of plugin names)
        };

        if ( typeof target === 'Array' ) {
            this.$element = target;
        } else {
            this.$element = $(target);
        }

        // user defined options
        this.options = options;

        // carousel view
        this.view = null;

        // carousel items
        this.items = [];

        // active ui controls
        this.controls = [];

        // list of activated plugins for carousel
        this.plugins = [];

        // call event dispatcher constructor
        averta.EventDispatcher.call(this);
    };

    /*---------------------------------------------------------------------------------*/
    // Static methods and properties

    // master carousel plugins list
    // @private
    MasterCarousel._plugins = [];

    // available carousel views
    // @private
    MasterCarousel._views = {};

    // available carousel items
    // @private
    MasterCarousel._items = {};

    // available carousel controls
    // @private
    MasterCarousel._controls = {};

    /**
     * registers new plugin to the carousel
     * @param  {CarouselPlugin} plugin
     */
    MasterCarousel.registerPlugin = function ( plugin ) {
        // is the plugins already registered?
        if ( MasterCarousel._plugins.indexOf(plugin) !== -1 ) {
            return;
        }

        MasterCarousel._plugins.push(plugin);
    };

    /**
     * registers new view to the carousel
     * @param  {String}         name
     * @param  {CarouselView}   view
     */
    MasterCarousel.registerView = function ( name, view ) {
        // is it already exists
        if ( MasterCarousel._views[name] ) {
            return;
        };

        MasterCarousel._views[name] = view;
    };

    /**
     * regsiters new UI control to the carousel
     * @param  {String}             name
     * @param  {CarouselControl}    control
     */
    MasterCarousel.registerControl = function ( name, control ) {
        // is it already registered?
        if ( MasterCarousel._controls[name] ) {
            return;
        }

        MasterCarousel._controls[name] = control;
    };

    /**
     * regsiters new UI item to the carousel
     * @param  {String}         name
     * @param  {CarouselItem}   control
     */
    MasterCarousel.registerItem = function ( name, item ) {
        // is it already registered?
        if ( MasterCarousel._items[name] ) {
            return;
        }

        MasterCarousel._items[name] = item;
    };


    /* ------------------------------------------------------------------------------ */
    // cache the prototype
    var p = MasterCarousel.prototype;

    /*---------------------------------------------------------------------------------*/
    // Public methods

    /**
     * setups the carousel
     */
    p.setup = function () {

        if ( this._setup ) {
            return;
        }

        this._setup = true;

        var self = this;

        // create plugins
        $.each(MasterCarousel._plugins, function(index, plugin) {
            self.plugins.push(new plugin(self));
        });

         // carousel options
        this.options = $.extend(this.defaultOptions, this.options);

        this._callPluginsMethod('aftereSetup');

        $(document).ready(function() {
            self._init();
        });

        return this;
    };


    /**
     * adds control to the carousel instance
     * @param  {String} name    control name
     * @param  {Object} options control options
     * @return {MasterCarousel}
     */
    p.control = function ( name, options ) {

        // create new instance from control
        var controlClass = MasterCarousel._controls[name];

        if ( !controlClass ) {
            console.log('Master Carousel Warning: The "' + name + '" UI control is not defined.');
            return this;
        }

        var control = new controlClass(this, options);
        this.controls.push(control);

        return this;
    };

    /**
     * goto next item or page
     * @param {Boolean} animate
     * @param {Number}  speed
     */
    p.next = function ( animate, speed ) {
        if ( this.view ) {
            this.view.next(animate, speed);
        }
    };

    /**
     * goto previous item or page
     * @param {Boolean} animate
     * @param {Number}  speed
     */
    p.previous = function ( animate, speed ) {
        if ( this.view ) {
            this.view.previous(animate, speed);
        }
    };

    /**
     * moves to the specified index
     * @param  {Number}  index   target item index
     * @param  {Boolean} animate
     * @param  {Number}  speed   speed of animation
     */
    p.gotoIndex = function ( index, animate, speed ) {
        if ( this.view ) {
            this.view.gotoItem(index, animate, speed);
        }
    };

    /**
     * moves to the specified page or item
     * @param  {Number}  index   target page or item
     * @param  {Boolean} animate
     * @param  {Number}  speed   speed of animation
     */
    p.goto = function ( target, animate, speed ) {
        if ( this.view ) {
            this.view.goto( target, animate, speed );
        }
    };

    /**
     * returns current page or item index
     */
    p.current = function() {
        if ( this.view ) {
            if ( this.options.navigation === 'perpage' ) {
                return this.view.page;
            }

            return this.view.index + 1;
        }
    };

    /**
     * returns the current item index
     */
    p.index = function () {
        if ( this.view ) {
            return this.view.index;
        }
    };

    /**
     * returns the total number of items or pages in carousel
     */
    p.count = function () {
        if ( this.view ) {
            if ( this.options.navigation === 'perpage' ) {
                return this.view.totalPages;
            }
            return this.view.itemsCount;
        }
    };

    /**
     * gets items list
     */
    p.items = function() {
        if ( this.view ) {
            return this.view.items;
        }
    };

    /**
     * return current item
     * @return {CarouselItem}
     */
    p.currentItem = function () {
        if ( this.view ) {
            return this.view.currentItem;
        }
    };

    /**
     * updates an option of carousel
     * @param {String}  name  option name
     * @param {*}       value option value
     */
    p.setOption = function ( name, value ) {
        this.setOptions(({})[name] = value);
    };

    /**
     * updates the carousel options
     * @param {Object}  options
     */
    p.setOptions = function ( options ) {
        $.extend(this.options, options);
        this._readOptions();
    };

    /**
     * destroy the carousel
     */
    p.destroy = function () {
        $.each(this.plugins, function(index, plugin) { plugin.destroy(); });
        $.each(this.controls, function(index, control) { control.destroy(); });
        this.plugins = null;
        this.controls = null;
        this.view.destroy();
        this.view = null;
        this.$element.remove();
        this.dispatchEvent(new MCEvents(MCEvents.DESTROY));
    };


    /*---------------------------------------------------------------------------------*/
    // Private methods

    /**
     * initializes the carousel after document ready
     */
    p._init = function () {
        this._callPluginsMethod('beforeInit');

        var op = this.options;

        // setup carousel view
        var viewClass = MasterCarousel._views[op.view];
        if ( !viewClass ) {
            console.log('Master Carousel Error: The "' + op.view + '" view is not defined in carousel.');
            viewClass = MasterCarousel._views.basic;
        }

        this.view = new viewClass(op);

        // add items
        this.$element.find('>.' + op.itemClass).each($.proxy(this._addItem, this));

        // setup controls
        $.each(this.controls, function(index, control) {
            control.view = self.view;
            control.carousel = self;
            control.setup();
        });

        this.$element.append(this.view.$element);
        this.view.init();

        this._callPluginsMethod('afterInit');
        this._readOptions();

        this.dispatchEvent(new MCEvents(MCEvents.INIT));
    };

    /**
     * adds items to the carousel
     * @param {Number}  index     location of item in list
     * @param {Element} element   item dom element
     * @private
     */
    p._addItem = function ( index, element ) {
        var $element = $(element),
            itemType = $element.data('item-type') || this.options.item;

        var itemClass = MasterCarousel._items[itemType];
        if ( !itemClass ) {
            console.log('Master Carousel Error: The "' + itemType + '" item is not defined in carousel.');
            itemClass = MasterCarousel._items.basic;
        }

        var item = new itemClass($element, this.view);
        item.carousel = this;
        this.items.push(item);

        // add item to view
        this.view.appendItem(item);

        item.setup();
    };

    /**
     * reads carousel options and applies changes
     */
    p._readOptions = function () {
        this.view._readOptions();
        this._callPluginsMethod('readOptions');
    };

    /**
     * calls method in all activated plugins
     * @param  {String} methodName
     * @param  {Array}  params
     */
    p._callPluginsMethod = function ( methodName, params ) {
        $.each(this.plugins, function(index, plugin) {
            if ( !plugin.disabled && plugin[methodName] ) {
                plugin[methodName].apply(plugin, params);
            }
        });
    };

    // add event dispatcher
    averta.EventDispatcher.extend(p);

    window.MasterCarousel = MasterCarousel;

})(jQuery, window, document);


/* -------------------- src/events/carouselEvents.js -------------------- */


;(function ( $, window, document, undefined ) {
    "use strict";
    window.MCEvents = function (type, data){
        this.type = type;
        this.data = data;
    };

    MCEvents.CHANGE_END            = 'mc_changeend';
    MCEvents.WAITING               = 'mc_waiting';
    MCEvents.AUTOPLAY_PAUSE        = 'mc_autoplaypause';
    MCEvents.AUTOPLAY_RESUME       = 'mc_autoplayresume';
    MCEvents.INIT                  = 'mc_init';
    MCEvents.HEIGHT_CHANGE         = 'mc_height_change';
    MCEvents.DESTROY               = 'mc_destroy';
    MCEvents.SWIPE_START           = 'mc_swipeStart';
    MCEvents.SWIPE_END             = 'mc_swipeEnd';
    MCEvents.SWIPE_MOVE            = 'mc_swipeMove';
    MCEvents.SWIPE_CANCEL          = 'mc_swipeCancel';
    MCEvents.SCROLL                = 'mc_scroll';
    MCEvents.OPTIONS_CHANGED       = 'mc_onOptionsChanged';

})(jQuery, window, document);


/* -------------------- src/view/carouselView.js -------------------- */


;(function ( $, window, document, undefined ) {

    "use strict";

    /**
     * Carousel View constructor
     * @param {Object} options  view options
     */
    var CarouselView = function ( options ) {

        // merge options
        this.options = options;

        // view element
        this.$element = $('<div></div>').addClass(this.options.viewClass);
        this.$container = $('<div></div>').addClass(this.options.containerClass).appendTo(this.$element);

        // stores all items in it
        this.items = [];

        // stores all active items
        this.activeItems = [];

        // stores current position in view
        this.index = 0;

        // specifies the delay duration on updating view after window resize
        this.resizeDelayTime = 1;

        // page index
        this.page = 1;
        this.totalPages = 0;

        // current item
        this.currentItem = null;

        // private properties
        this._initilized = false;

        // this used to control of scrolling in RTL direction
        this._reverse = 1;

        // is css3 supported?
        this._css3 = window._cssanim;
        this._translatePostfix = window._css3d ? ' translateZ(0px)' : '';

        // creates a new scroll controller
        this.scroller = new SlickController(0, 0, {});
        this.scroller.snappingCallback(this._onSnappingUpdate , this);
        this.scroller.snapCompleteCallback(this._onSnappingCompelet , this);
        this.scroller.renderCallback(this._scroll, this);

        // override get snap num
        this.scroller.getSnapNum = $.proxy(this._getSnapNum, this);
        this.scroller.gotoSnap = $.proxy(this._gotoSnap, this);
        this.scroller._calculateExtraMove = $.proxy(this._calculateExtraMove, this);

        // empty space before items for loop navigation
        // the _reset() removes the space every time swipe done.
        this._spaceBuffer = 0;

        // call event dispatcher constructor
        averta.EventDispatcher.call(this);
    };

    /* ------------------------------------------------------------------------------ */
    var p = CarouselView.prototype;

    /* ------------------------------------------------------------------------------ */
    // public methods

    /**
     * append new item to the view
     * @param {CarouselItem} item
     */
    p.appendItem = function ( item ) {
        this._setupItem(item);
        this.items.push(item);

        if ( this._initilized ) {
            this._updateView();
        }
    };

    /**
     * prepends new item to the view
     * @param  {CarouselItem} item
     */
    p.prependItem = function ( item ) {
        this._setupItem(item);
        this.items.shift(item);

        if ( this._initilized ) {
            this._updateView();
        }
    };

    /**
     * adds new item at specific index
     * @param {CareouselItem} item
     * @param {Number} index
     */
    p.addItemAt = function ( item, index ) {
        this._setupItem(item);

        if ( index >= this.items.length ) {
            this.appendItem(item);
        } else {
            this.items.splice(index, 0, item);
            if ( this._initilized ) {
                this._updateView();
            }
        }
    };

    /**
     * adds new item exactly after the specified item in view
     * @param {CareouselItem} item
     * @param {CareouselItem} after
     */
    p.addAfter = function ( item, after ) {
        var index = this.items.indexOf(after);
        if ( index === -1 ) {
            return false;
        }

        this.addItemAt(item, index);
    };

    /**
     * Initializes the view
     */
    p.init = function () {

        if ( this._initilized ) {
            return;
        }

        this._initilized = true;

        $(window).resize($.proxy(this._resize, this));

    };


    /**
     * changes the view options on runtime
     * TODO: improvement requires changing some options causes unexpected actions
     * @param  {object} options
     */
    p.changeOption = function ( options ) {
        if ( !this._initilized ) {
            return;
        }

        $.extend(this.options, options);
        this._readOptions();
    };

    /**
     * Moves to the specific item index
     * @param  {Number}  index      destination item index
     * @param  {Boolean} animate    whether animate or not
     * @param  {Number}  speed      animation speed
     */
    p.gotoItem = function ( index, animate, speed ) {
        var item = this.items[index];
        if ( item && this.scroller ) {

           /* if ( this.options.loop ) {
                // update index and current item
                this.index = index;
                this.currentItem = item;
                // relocate items
                this._updateView();
            }
            */

            // moves scroller to the destination item
            this.scroller.changeTo(item.position, animate, speed);
        }
    };

    /**
     * moves to next item in view
     * @param  {Boolean} animate  whether animate to target
     * @param  {Number}  speed    animation speed
     * @param  {Boolean} bounce   bounce at last or stating item, it doesn't have effect in loop or perpage navigation.
     */
    p.next = function ( animate, speed, bounce ) {
        if ( this.options.navigation === 'perpage' ) {
            this.scroller.nextSnap(animate !== false, speed || this.scroller.options.friction);
            return;
        }

        if ( this.options.loop ) {
            this.gotoItem((this.index + 1) % this.itemsCount, animate !== false, speed || this.options.speed);
        } else if ( this.index + 1 < this.itemsCount ) {
            this.gotoItem(this.index + 1, animate !== false, speed || this.scroller.options.friction);
        } else if ( bounce !== false ) {
            this.scroller.bounce(10);
        }
    };

    /**
     * moves to previous item in view
     * @param  {Boolean} bounce   bounce at last or stating item, it doesn't have effect in loop or perpage navigation.
     * @param  {Boolean} animate  whether animate to target
     * @param  {Number}  speed    animation speed
     */
    p.previous = function ( animate, speed, bounce ) {
        if ( this.options.navigation === 'perpage' ) {
            this.scroller.prevSnap(animate !== false, speed || this.scroller.options.friction);
            return;
        }

        if ( this.options.loop ) {
            var targetIndex = (this.index - 1) % this.itemsCount;
            if ( targetIndex < 0 ) {
                targetIndex += this.itemsCount;
            }
            this.gotoItem( targetIndex, animate !== false, speed || this.scroller.options.friction);
        } else if ( this.index - 1 >= 0 ) {
            this.gotoItem(this.index - 1, animate !== false, speed || this.scroller.options.friction);
        } else if ( bounce !== false ) {
            this.scroller.bounce(-10);
        }
    };

    /**
     * moves to target page or item
     * @param  {Number} target  page or item index
     * @param  {Boolean} animate
     * @param  {Number} speed
     */
    p.goto = function ( target, animate, speed ) {
        if ( this.options.navigation === 'perpage' ) {
            var value = this.scroller.value + ( ( target - this.page ) * this.scroller.options.snapsize );
            this._gotoSnap( this._getSnapNum( value ), animate !== false, speed );
        } else {
            this.gotoItem( target - 1, animate !== false, speed );
        }
    };

    /**
     * destroys the view
     */
    p.destroy = function () {
        for ( var i = 0; i !== this.itemsCount; i++ ) {
            this.items[i].destroy();
        }

        this.$container.remove();
        this.$element.remove();
        this.scroller.destroy();
        this.swipeController = null;
        this.items = null;
        this.currentItem = null;
        this.options = null;

        $(window).off('resize', this._resize);
    };

    /* ------------------------------------------------------------------------------ */
    // private methods

    /**
     * updates the dimensions and updates the view
     */
    p._resize = function ( update ) {
        var self = this;
        self.width = self.$element.width();
        self.height = self.$element.height();
        self.oneColumnSize = self[self._dimension] / self.options.columns;

        clearTimeout(self._resizeDelay);
        if ( update !== false ) {
            self._resizeDelay = setTimeout(function(){
                    self._updateView();
                    self.gotoItem(self.index);
            }, this.resizeDelayTime);
        }

        this.dispatchEvent(new MCEvents(MCEvents.RESIZE));
    };

    /**
     * reads view options and updates required variables then calls `_updateView` to update items location
     */
    p._readOptions = function () {
        var op = this.options;

        if ( op.dir === 'h' ) {
            this._dimension = 'width';
            this._offset = 'left';
            this._transAxis = 'translateX';
        } else {
            this._dimension = 'height';
            this._offset = 'top';
            this._transAxis = 'translateY';
        }

        this._resize(false); // update view dimension values

        // update scroller options.
        var so = this.scroller.options;

        // paging and snapping should be disabled in scroll navigation
        if ( op.navigation === 'scroll' ) {
            so.paging = false;
            so.snapping = false;
        } else {
            so.snapping = true;

            // only snapping navigation disables the paging option
            so.paging = ( op.navigation !== 'snapping' );

            if ( op.navigation === 'perpage' ) {
                // in perpage navigation style all snaps locations has same size and equal to view dimension
                so.snapsize = this[this._dimension] + this.options.space ;
            }
        }

        so.endless = op.loop; // we need an end less scroller for loop navigation
        so.friction = (100 - op.speed * 0.5) / 100; // TODO should be better
        so.snappingMinSpeed = op.minSnappingSpeed;

        // setup or enable/disable the swipe controller
        if ( op.swipe && (window._touch || op.mouseSwipe) ) {
            // is it already created?
            if ( this.swipeController ) {
                this.swipeController.enable();
            } else {
                // create new instance of touch swipe controller
                this.swipeController = new averta.TouchSwipe(this.$element);
                this.swipeController.onSwipe = $.proxy(this._swipeMove, this);
            }

            // change swipe controller options based on view direction
            if ( op.dir === 'h' ) {
                this.swipeController.swipeType = 'horizontal';
                this._swipeMoveDir = 'moveX';
                this._swipeMoveDistance = 'distanceX';
                this._scrollTransitin = ''
            } else {
                this.swipeController.swipeType = 'vertical';
                this._swipeMoveDir = 'moveY';
                this._swipeMoveDistance = 'distanceY';
            }

        } else if ( this.swipeController ) {
            // disable the touch swipe controller
            this.swipeController.disable();
        }


        this._balancingItems = Math.floor(op.columns / 2);

        if ( op.rtl ) {
           this._offset = 'right';
           this._reverse = -1;
        }

        // reset items in view if they are already positioned in view
        if ( !this._firstInit ) {
            this._resetItems();
        }

        this._updateView();

        if ( this._initilized ) {
            this._reset();
        }

        // update total page value
        this.totalPages = Math.ceil(this.itemsCount / op.columns);

        // change to start item.
        this.gotoItem(op.startItem - 1)
        this._findActiveItems();

        // move to nearest snap if snapping
        this.scroller.cancel();

        this._firstInit = false;
       // this.dispatchEvent(new MCEvents(MCEvents.OPTIONS_CHANGED));
    };

    /**
     * resets items in view and removes extra styles
     */
    p._resetItems = function () {
        var item;
        for ( var i = 0, l = this.items.length; i !== l; i++ ){
            item = this.items[i];
            item.position = 0;
            item.$element.attr('style', '');
        }
    };

    /**
     * setups and prepares item for adding in view.
     */
    p._setupItem = function ( item ) {
        item.view = this;
        item.$container = this.$container;
        item.size = 0;
        item.position = 0;
        item.sleep();
    };

    /**
     * updates the view and relocates items
     */
    p._updateView = function () {
        var item, $item,
            l = this.items.length,
            before = 0,
            op = this.options,
            space = op.space,
            middle = 0;
        this.itemsCount = l;

        // select first item
        if ( !this.currentItem ) {
            this.currentItem = this.items[0];
        }

        // update snap size for perpage navigation
        if ( op.navigation === 'perpage' ) {
            // in perpage navigation style all snaps locations has same size and equal to view dimension
            this.scroller.options.snapsize = this[this._dimension] + op.space;
        }

        if ( op.loop ) {
            middle = Math.ceil(l / 2) + this.index + this._balancingItems;
        }

        for ( var i = 0; i !== l; i++ ) {

            // cache the item.
            // the selecting order changes relative to loop option and current view index.
            item = this.items[ (i + middle) % l];
            // update item position value
            item.position = before;

            // calculate item size
            item.size = (this[this._dimension] - space * (op.columns -  1)) * (item.merge / op.columns) + space * (item.merge - 1);

            before += item.size + space;
        }

        var middlePosition = this.currentItem.position;

        if ( !op.loop ) {
            this.scroller._max_value = before - space - this[this._dimension];
            middlePosition = 0;
            this._spaceBuffer = 0;

            // TODO: center and merged items not working correctly
            if ( op.center ) {
                this.scroller._max_value = before - this[this._dimension]/2 + this.items[0].size;
            }
        }

        // locate items in container
        for ( i = 0; i !== l; i++ ) {
            item = this.items[i];
            item.position = this._spaceBuffer + item.position - middlePosition;
            item.$element[0].style[this._offset] =  item.position + 'px';
            item.$element[0].style[this._dimension] = item.size + 'px';
        }

    };

    /**
     * returns the shortest path to the target index
     * negative values means backward.
     * @param  {Number} targetIndex
     * @return {Number}
     */
    p._getShortestPath = function ( targetIndex ) {
        var right = (targetIndex < this.index)?  this.itemsCount - this.index + targetIndex : targetIndex - this.index;
        var left  = Math.abs(this.itemsCount - right);

        return (right < left)? right : -left;
    }

    /**
     * relocates items in view
     */
    p._reset = function () {
        this._spaceBuffer = 0;
        var diff = this.scroller.value - this.currentItem.position;
        this._updateView();
        this.scroller.changeTo(this.currentItem.position + diff, false, null, null, false);
    };

    /**
     * checks items in view and actives or inactives items depending on locating in view port or not.
     */
    p._findActiveItems = function () {
        var item;
        this.activeItems = [];
        for ( var i = 0; i !== this.itemsCount; i++ ) {
            item = this.items[i];
            if ( item.position < this.scroller.value + this[this._dimension] && item.position + item.size > this.scroller.value) {
                // active item
                item.active();
                this.activeItems.push(item);
            } else {
                // inactive item
                item.inactive();
            }
        }
    };

    /* ------------------------------------------------------------------------------ */
    // scroller

    p._onSnappingCompelet = function ( snap, type ) {
       if ( this.options.loop ) {
            this._reset();
       }

       this.dispatchEvent(new MCEvents(MCEvents.CHANGE_END));
    };

    p._onSnappingUpdate = function ( scroller, snap, change ) {
        //console.log('update',scroller, snap, change )
    };

    p._scroll = function ( scroller, value ) {

        // find the current item index
        var op = this.options,
            loop = op.loop,
            item,
            currentItemIndex = this._findItemIndexAtValue ( value, true ),
            steps = this._getShortestPath(currentItemIndex);

        // update loop buffer space
        if ( steps !== 0 ){

            this.index = currentItemIndex;
            this.currentItem = this.items[this.index];
            this.page = Math.floor(this.index / this.options.columns) + 1;
            // only required in loop navigation
            if ( loop ) {

                // calculates the spacing buffer value.
                for ( var i = 0, l = Math.min(Math.abs(steps), Math.floor(this.itemsCount / 2)); i < l; i++ ){
                    if ( steps > 0 ) {
                        var index = this.index - i - 1;
                        if ( index < 0 ) {
                            index = this.itemsCount + index;
                        }
                        this._spaceBuffer += this.items[index].size + this.options.space;
                    } else {
                        this._spaceBuffer -= this.items[(this.index + i) % this.itemsCount].size + this.options.space;
                    }
                }

                this._updateView();
            }
        }

        // align center items
        if ( op.center ) {
            value -= (this[this._dimension] - this.items[0].size) / 2;
        }

        if ( this._css3 ) {
            this.$container[0].style[window._jcsspfx + 'Transform'] = this._transAxis + '(' + -value * this._reverse + 'px)' + this._translatePostfix;
        } else {
            this.$container[0].style[this._offset] = -value + 'px';
        }


        this._findActiveItems();

        this.dispatchEvent(new MCEvents(MCEvents.SCROLL));
    };

    /**
     * Finds the current item at scroller value and returns the item index
     * @param  {Number}     value       Scroller value
     * @param  {Boolean}    fromMiddle  returns next item if it passed from middle
     * @return {Number}     Item index
     */
    p._findItemIndexAtValue = function ( value, fromMiddle ) {
        var item, size;

        for ( var i = 0, l = this.itemsCount; i !== l; i++ ) {
           item = this.items[i];
           size = fromMiddle ?  this.oneColumnSize / 2 : 0;
           if ( item.position - size <= value && item.position + item.size + this.options.space - size > value ) {
               return i;
           }
        }

        return this.index;
    };

    /**
     * Overrides the getSnapNum method of scroller
     *
     * @override
     * @param  {Number}     value   Scroller position
     * @return {Number}
     */
    p._getSnapNum = function ( value ) {

        var op = this.options;

        if ( op.navigation === 'perpage' || op.navigation === 'scroll' ) {
            return Math.floor(( value + this.scroller.options.snapsize / 2 ) / this.scroller.options.snapsize);
        } else {
            return this._findItemIndexAtValue(value, true);
        }

        return 0;
    };

    /**
     * overrides the gotoSnap method of scroller
     * @param  {Number} snapNum target snap number
     * @param  {Boolean} animate
     * @param  {Number} speed
     */
    p._gotoSnap = function ( snapNum, animate, speed ) {
        var scroller = this.scroller, op = this.options;

        if ( op.navigation === 'perpage' || op.navigation === 'scroll' ) {
            scroller.changeTo(snapNum * scroller.options.snapsize , animate , speed , snapNum);
        } else {
            var loop = this.options.loop,
                count = this.itemsCount;
            if ( snapNum < 0 ) {
                snapNum = ( loop ? count + snapNum : 0 );
            } else if ( !loop && snapNum >= count ) {
                snapNum = count - 1;
            }

            scroller.changeTo(this.items[snapNum % this.itemsCount].position, animate , speed , snapNum);
        }
    };

    /**
     * overrides the _calculateExtraMove method of scroller
     * @param  {Number} values
     * @return {Number}
     */
    p._calculateExtraMove = function ( value ) {
        var op = this.options,
            sceroller = this.scroller,
            snapsize, m;

        if ( op.navigation === 'perpage' || op.navigation === 'scroll' ) {
            snapsize = scroller.options.snapsize;
            m = value % snapsize;
        } else {
            if ( op.loop ) {
                value = this.currentItem.position + value - this._spaceBuffer;
            }

            var item = this.items[this._findItemIndexAtValue(value, true)];
            snapsize = item.size + op.space;
            m = this._spaceBuffer + value - item.position;
        }

        return m < snapsize / 2  ? -m : snapsize - m;
    };

    /* ------------------------------------------------------------------------------ */
    // touch swipe

    /**
     * on swipe move callback
     * @param  {Object} status  swipe status object
     */
    p._swipeMove = function ( status ) {
        var phase = status.phase;

        if ( phase === 'start' ) {
            this.scroller.stop();
            this.dispatchEvent(new MCEvents(MCEvents.SWIPE_START, status));
        } else if ( phase === 'move' ) {
            this.scroller.drag(status[this._swipeMoveDir] * this._reverse);
            this.dispatchEvent(new MCEvents(MCEvents.SWIPE_MOVE, status));
        } else if ( phase === 'end' || phase === 'cancel' ) {
            var speed = status[this._swipeMoveDistance] / status.duration * 50 / 3;

            if ( Math.abs(speed) > 0.1 ) {
                this.scroller.push(-speed * this._reverse);

                if ( speed > this.scroller.options.snappingMinSpeed ) {
                    this.dispatchEvent(new MCEvents(MCEvents.SWIPE_END, status));
                }
            }else {
                this.scroller.cancel();
                this.dispatchEvent(new MCEvents(MCEvents.SWIPE_CANCEL, status));
            }

        }
    };

    // add event dispatcher
    averta.EventDispatcher.extend(p);

    // register view
    MasterCarousel.registerView('basic', CarouselView);

})(jQuery, window, document);


/* -------------------- src/item/carouselItem.js -------------------- */


;(function ( $, window, document, undefined ) {

    "use strict";

    /**
     * carousel item constructor
     * @param  {jQueryElement} $element
     * @param  {CarouselView} view
     */
    var item = function ( $element, view ) {
        this.$element = $element;
        this.view = view;

        // how many columns should be covered in view by this item
        this.merge = $element.data('merge') || 1;
    };

    /* ------------------------------------------------------------------------------ */
    var p = item.prototype;

    /* ------------------------------------------------------------------------------ */
    // public methods

    /**
     * deactivates the item and removes it from DOM
     */
    p.sleep = function () {
        if ( !this.detached ) {
            this.$element.detach();
            this.detached = true;
        }
    };

    /**
     * activate the item and retrieves it to the DOM
     */
    p.wakeup = function () {
        if ( this.detached ) {
            this.view.$container.append(this.$element);
            this.detached = false;
        }
    };

    /**
     * setups the items
     */
    p.setup = function () {
        this.view.$container.append(this.$element);
    };

    /**
     * activates the item
     */
    p.active = function () {
        this.$element.addClass('mc-item-active');
    };

    /**
     * deactivates the item
     */
    p.inactive = function () {
        this.$element.removeClass('mc-item-active');
    };


    /**
     * destroys the item
     */
    p.destroy = function () {
        this.view = null;
        this.$element.remove();
    };

    // register item
    MasterCarousel.registerItem('basic', item);

})(jQuery, window, document);


/* -------------------- src/plugins/mastercarousel.inview.js -------------------- */


;(function ( $, window, document, undefined ) {
    "use strict";

    /**
     * inview controller plugin contractor
     * @param  {MasterCarousel} carousel
     */
    var inViewController = function ( carousel ) {
        this.carousel = carousel;

        // adds inview default value to carousel options
        this.carousel.defaultOptions.inView = 10;
        // the percentage of view size which used to check every time for controlling items
        this.carousel.defaultOptions.inViewMargin = 30;

    };

    /* ------------------------------------------------------------------------------ */
    var p = inViewController.prototype;

    /* ------------------------------------------------------------------------------ */
    // callbacks

    /**
     * calls by carousel exactly after setting up
     */
    //p.afterSetup = function () {};

    /**
     * calls before carousel initialization
     */
    //p.beforeInit = function () {};

    /**
     * calls after carousel initialization
     */
    //p.afterInit = function () {};

    /**
     * reads options and applies changes
     */
    p.readOptions = function () {
        // disabled prevents calling plugin callback
        this.disabled = this.carousel.view.itemsCount <= this.carousel.options.inView;

        // is it already disabled, so reset the view items
        if ( this.disabled ) {
            this._reset();
            // remove scrolling event
            this.carousel.view.removeEventListener(MCEvents.SCROLL, this._onScroll, this);
        } else {
            // add scrolling event
            this.carousel.view.addEventListener(MCEvents.SCROLL, this._onScroll, this);
            this._onScroll();
        }
    };

    /**
     * remove all events and destroys the plugin
     */
    p.destroy = function () {
        if ( this.carousel.view ) {
            this.carousel.view.removeEventListener(MCEvents.SCROLL, this._onScroll, this);
        }

        this.carousel = null;
    };

    /* ------------------------------------------------------------------------------ */
    // private methods

    /**
     * carousel view scrolling event
     */
    p._onScroll = function () {
        var view = this.carousel.view,
            items = view.items,
            scrollerVal = view.scroller.value,
            viewSize = view[view._dimension],
            margin = viewSize * this.carousel.options.inViewMargin / 100,
            item;

        for ( var i = 0; i !== view.itemsCount; i++ ) {
            item = items[i];
            if ( item.position + item.size >= scrollerVal - margin && item.position < viewSize + margin + scrollerVal ) {
                item.wakeup();
            } else {
                item.sleep();
            }
        }
    };

    /**
     * resets items inview control
     */
    p._reset = function () {
        var view = this.carousel.view;
        for ( var i = 0; i !== view.itemsCount; i++ ) {
            view.items[i].wakeup();
        }
    };

    /* ------------------------------------------------------------------------------ */
    // register the plugin
    MasterCarousel.registerPlugin(inViewController);

})(jQuery, window, document);


/* -------------------- src/plugins/mastercarousel.autoplay.js -------------------- */


;(function ( $, window, document, undefined ) {
    "use strict";

    var pluginId = 0;


    /**
     * autoplay plugin contractor
     * @param  {MasterCarousel} carousel
     */
    var Autoplay = function ( carousel ) {
        this.carousel = carousel;

        // adds autoplay default values in options
        $.extend(this.carousel.defaultOptions, {
            autoplay        : false,       // enables auto play option
            pauseOnHover    : true,        // pause when mouse cursoer moves over carousel
            autoplayDelay   : 2            // the delay duration of between in seconds.
        });


        // create the timer
        this.timer = new averta.Timer(100);
        this.timer.onTimer     = this._onTimer;
        this.timer.refrence     = this;


        // the persentage of passed delay duration
        this._delayProgress = 0;

        this._id = pluginId++;

        // extend carousel and adds pause and resume methods.

        /**
         * pauses carousel autoplay
         */
        this.carousel.pause = function () {
            if ( this.options.autoplay ) {
                this.setOptions({autoplay: false});
                this.carousel.dispatchEvent(new MCEvents(MCEvents.AUTOPLAY_PAUSE));
            }
        };

        /**
         * resumes autplay timer
         */
        this.carousel.resume = function () {
            if ( !this.options.autoplay ) {
                this.setOptions({autoplay: true});
                this.carousel.dispatchEvent(new MCEvents(MCEvents.AUTOPLAY_RESUME));
            }
        };

        /**
         * returns the current progress of autplay delay
         */
        this.carousel.getTimeProgress = function () {
            return this._delayProgress;
        };

    };

    /* ------------------------------------------------------------------------------ */
    var p = Autoplay.prototype;

    /* ------------------------------------------------------------------------------ */
    // callbacks

    /**
     * calls by carousel exactly after setting up
     */
    //p.afterSetup = function () {};

    /**
     * calls before carousel initialization
     */
    //p.beforeInit = function () {};

    /**
     * calls after carousel initialization
     */
    p.afterInit = function ( ) {
        this.view = this.carousel.view;
    };

    /**
     * reads options and applies changes
     */
    p.readOptions = function () {
        var op = this.carousel.options,
            self = this;

        if ( op.autoplay ) {
            this.view.addEventListener(MCEvents.SWIPE_START, this._stopTimer, this);
            this.view.addEventListener(MCEvents.CHANGE_END, this._onChangeEnd, this);
            this._startTimer();

            if ( op.pauseOnHover ) {
                this.carousel.$element.on('mouseenter.mc-timer-' + this._id, function(){
                    self._mouseIsOver = true;
                    self._stopTimer();
                }).on('mouseleave.mc-timer-' + this._id, function(){
                    self._mouseIsOver = false;
                    if ( op.autoplay ) {
                        self._startTimer();
                    }
                });
            } else {
                this.carousel.$element.off('mouseenter.mc-timer-' + this._id, 'mouseleave.mc-timer-' + this._id);
            }

        } else {
            this.view.removeEventListener(MCEvents.SWIPE_START, this._stopTimer, this);
            this.view.removeEventListener(MCEvents.CHANGE_END, this._onChangeEnd, this);
            this.carousel.$element.off('mouseenter.mc-timer-' + this._id, 'mouseleave.mc-timer-' + this._id);
            this._resetTimer();
            this._stopTimer();
        }

        this._delayProgress = 0;
    };

    /**
     * remove all events and destroys the plugin
     */
    p.destroy = function () {
        this.view.removeEventListener(MCEvents.SWIPE_START, this._stopTimer, this);
        this.view.removeEventListener(MCEvents.CHANGE_END, this._onChangeEnd, this);
        this.carousel.$element.off('mouseenter.mc-timer-' + this._id, 'mouseleave.mc-timer-' + this._id);
        this._resetTimer();
        this._stopTimer();

        this.view = null;
        this.carousel = null;
    };

    /* ------------------------------------------------------------------------------ */
    // private methods

    /**
     * listener for on change end event of carousel view, it used to resume the timer after changing ends.
     */
    p._onChangeEnd = function () {
        if ( this.carousel.options.autoplay ) {
            this._startTimer();
        }
    };

    /**
     * checks the possiblity of starting timer then starts it
     */
    p._startTimer = function () {
        var op = this.carousel.options;

        // doesnt moves further in non-loop carousel if it reachs the last item.
        if ( !this._mouseIsOver && (op.loop || this.view.index + op.columns < this.view.itemsCount)) {
            this.timer.start();
        }
    };

    p._stopTimer = function () {
        this.timer.stop();
    };

    /**
     * timer interval listener
     */
    p._onTimer = function () {

        var time = this.timer.getTime();
        this._delayProgress = time / (this.carousel.options.autoplayDelay * 10);

        if ( time >= this.carousel.options.autoplayDelay * 1000 ) {
            this.carousel.next();
            this._resetTimer();
        }

        // dispatch event
        this.carousel.dispatchEvent(new MCEvents(MCEvents.WAITING));
    }

    /**
     * reset timer
     */
    p._resetTimer = function () {
        this.timer.reset();
        this._delayProgress = 0;
    };


    /* ------------------------------------------------------------------------------ */
    // register the plugin
    MasterCarousel.registerPlugin(Autoplay);

})(jQuery, window, document);


/* -------------------- src/plugins/mastercarousel.betterresp.js -------------------- */


;(function ( $, window, document, undefined ) {
    "use strict";

    var pluginId = 0;


    /**
     * autoplay plugin contractor
     * @param  {MasterCarousel} carousel
     */
    var BetterResponsive = function ( carousel ) {
        this.carousel = carousel;
        this.$window = $(window);

        // active breakpoint position
        this._activePos = 0;

        // extends carousel default options
        $.extend(this.carousel.defaultOptions, {
            autoWidth: false            // disables changing columns number in browser resize
        });

    };

    /* ------------------------------------------------------------------------------ */
    var p = BetterResponsive.prototype;

    /* ------------------------------------------------------------------------------ */
    // callbacks

    /**
     * calls by carousel exactly after setting up
     */
    //p.afterSetup = function () {};

    /**
     * calls before carousel initialization
     */
    //p.beforeInit = function () {};

    /**
     * calls after carousel initialization
     */
    p.afterInit = function ( ) {
        this.view = this.carousel.view;
    };

    /**
     * reads options and applies changes
     */
    p.readOptions = function () {

        // prevents to moving in endless loop
        if ( this._internalChange ) {
            this._internalChange = false;
            return;
        }

        var op = this.carousel.options,
            self = this;

        this._copyOptions = $.extend({}, op);

        if ( op.autoWidth ) {
            this.$window.off('resize', this._onResize);
        } else if ( op.responsive ) {
            this.$window.on('resize', $.proxy(this._onResize, this));
            this._onResize();
        }


    };

    /**
     * remove all events and destroys the plugin
     */
    p.destroy = function () {
        this.$window.off('resize', this._onResize);
        this.view = null;
        this.carousel = null;
        this.$window = null;
    };

    /* ------------------------------------------------------------------------------ */
    // private methods

    p._onResize = function () {
        var op = this.carousel.options,
            size = this.$window[this.view._dimension](), // gets the window size based on carousel direction
            pos, respOptions, lastPos;

        for ( var key in op.responsive ) {
            pos = Number(key);

            if ( size <= pos && (!lastPos || pos < lastPos) ){
                respOptions = op.responsive[key];
                lastPos = pos;
            }
        }

        if ( respOptions && this._activePos !== lastPos ) {
            this._internalChange = true;
            this._activePos = lastPos;
            this.carousel.setOptions($.extend({}, this._copyOptions, respOptions));
        } else if ( !respOptions && this._activePos ) {
            this._internalChange = true;
            this.carousel.setOptions(this._copyOptions);
            this._activePos = null;
        }

    };

    /* ------------------------------------------------------------------------------ */
    // register the plugin
    MasterCarousel.registerPlugin(BetterResponsive);

})(jQuery, window, document);


/* -------------------- src/plugins/mastercarousel.preloader.js -------------------- */


;(function ( $, window, document, undefined ) {
    "use strict";

    /**
     * inview controller plugin contractor
     * @param  {MasterCarousel} carousel
     */
    var Preloader = function ( carousel ) {
        this.carousel = carousel;

        // adds preload default value to carousel options
       $.extend(this.carousel.defaultOptions, {
            preload: false,
            prealoadAttr: 'data-src',
            insertPreloadClass : true
        });

    };

    /* ------------------------------------------------------------------------------ */
    var p = Preloader.prototype;

    /* ------------------------------------------------------------------------------ */
    // callbacks

    /**
     * calls by carousel exactly after setting up
     */
    //p.afterSetup = function () {};

    /**
     * calls before carousel initialization
     */
    //p.beforeInit = function () {};

    /**
     * calls after carousel initialization
     */
    //p.afterInit = function () {};

    /**
     * reads options and applies changes
     */
    p.readOptions = function () {
        var preload = this.carousel.options.preload;

        // is it already disabled, so reset the view items
        if ( !preload ) {
            // remove scrolling event
            this.carousel.view.removeEventListener(MCEvents.SCROLL, this._onScroll, this);
        } else {
            if ( this.carousel.options.insertPreloadClass ) {
                this.carousel.$element.find('.' + this.carousel.options.itemClass).addClass('mc-preloading');
            }
            // add scrolling event
            this.carousel.view.addEventListener(MCEvents.SCROLL, this._onScroll, this);
            this._onScroll();
        }
    };

    /**
     * remove all events and destroys the plugin
     */
    p.destroy = function () {
        if ( this.carousel.view ) {
            this.carousel.view.removeEventListener(MCEvents.SCROLL, this._onScroll, this);
        }

        this.carousel = null;
    };

    /* ------------------------------------------------------------------------------ */
    // private methods

    /**
     * carousel view scrolling event
     */
    p._onScroll = function () {
        var view = this.carousel.view,
            actives = view.activeItems,
            item;
        for ( var i = 0, l = actives.length; i !== l; i++ ) {
            item = actives[i];
            if ( !item.preloading ) {
                this._startPreloadItem(item);
            }
        }
    };

    /**
     * preloads all images in the specified item
     * @param  {CarouselItem} item
     */
    p._startPreloadItem = function ( item ) {
        item.preloading = true;
        var attr = this.carousel.options.prealoadAttr,
            imgs = item.$element.find('img[' + attr + ']'),
            preloadCount = imgs.length;

        if ( preloadCount === 0 ) {
            item.$element.removeClass('mc-preloading');
            return;
        }

        imgs.each(function(index){
            var $this = $(this);
            $this.preloadImg($this.attr(attr), function ( event ) {
                preloadCount--;
                if ( preloadCount === 0 ) {
                    item.$element.removeClass('mc-preloading');
                }
            }).removeAttr(attr);
        });
    };

    /* ------------------------------------------------------------------------------ */
    // register the plugin
    MasterCarousel.registerPlugin(Preloader);

})(jQuery, window, document);


/* -------------------- src/plugins/mastercarousel.height-controller.js -------------------- */


;(function ( $, window, document, undefined ) {
    "use strict";

    /**
     * height controller plugin contractor
     * @param  {MasterCarousel} carousel
     */
    var HeightController = function ( carousel ) {
        this.carousel = carousel;

        // adds autoHeight default value to carousel options
        this.carousel.defaultOptions.autoHeight = false;

        // use this value if there is no element to measure height (0 value disables it)
        this.carousel.defaultOptions.emptyHeight = 450;

        // stores the maximum height amount of items
        this._maxHeight = 0;

    };

    /* ------------------------------------------------------------------------------ */
    var p = HeightController.prototype;

    /* ------------------------------------------------------------------------------ */
    // callbacks

    /**
     * calls by carousel exactly after setting up
     */
    //p.afterSetup = function () {};

    /**
     * calls before carousel initialization
     */
    //p.beforeInit = function () {};

    /**
     * calls after carousel initialization
     */
    p.afterInit = function () {
        var items = this.carousel.view.items,
            item, self = this;

        for ( var i = 0, l = items.length; i !== l; i++ ){
            item = items[i];
            item.$element.find('img').on('load', $.proxy(this._updateHeight, this));
        }

        $(window).on('resize', $.proxy(this._updateHeight, this));
        this._updateHeight({type:'resize'}); // call by delay

    };

    /**
     * reads options and applies changes
     */
    p.readOptions = function () {
        this.autoHeight = this.carousel.options.autoHeight;

        if ( this.autoHeight ) {
            this.carousel.view.addEventListener(MCEvents.SCROLL, this._updateHeight, this);
            this._maxHeight = 0;
            this._updateHeight();
        } else {
            this.carousel.view.removeEventListener(MCEvents.SCROLL, this._updateHeight, this);
        }
    };

    /**
     * remove all events and destroys the plugin
     */
    p.destroy = function () {
        if ( this.carousel.view ) {
            this.carousel.view.removeEventListener(MCEvents.SCROLL, this._updateHeight, this);
        }

        var items = this.carousel.view.items;
        for ( var i = 0, l = items.length; i !== l; i++ ){
            items[i].$element.find('img').off('load');
        }

        $(window).off('resize', this._updateHeight);

        this.carousel = null;
    };

    /* ------------------------------------------------------------------------------ */
    // private methods

    /**
     * updates the carousel height
     * @param  {Event} e
     */
    p._updateHeight = function ( e ) {

        clearTimeout(this._resizeTo);
        if ( e && e.type === 'resize' ) {
            this._resizeTo = setTimeout($.proxy(this._updateHeight, this), 150);
        }

        var autoHeight = this.carousel.options.autoHeight,
            items = (autoHeight ? this.carousel.view.activeItems : this.carousel.view.items);

        var oldHeight = this._maxHeight;
        this._maxHeight = 0;

        for ( var i = 0, l = items.length; i !== l; i++ ) {
            this._maxHeight = Math.max(items[i].$element.height(), this._maxHeight);
        }

        if ( this._maxHeight === 0 ) {
            this._maxHeight = this.carousel.options.emptyHeight;
        }

        this.carousel.$element[0].style.height = this._maxHeight + 'px';

        if ( oldHeight !== this._maxHeight ) {
            this.carousel.dispatchEvent( new MCEvents( MCEvents.HEIGHT_CHANGE ) );
        }
    };

    /* ------------------------------------------------------------------------------ */
    // register the plugin
    MasterCarousel.registerPlugin(HeightController);

})(jQuery, window, document);


/* -------------------- src/plugins/mastercarousel.link-disabler.js -------------------- */


/**
 * Disables links on carousel when the carousel is swiping
 */
;(function ( $, window, document, undefined ) {
    "use strict";


    /**
     * disable links plugin contractor
     * @param  {MasterCarousel} carousel
     */
    var disableLinksOnSwipe = function ( carousel ) {
        this.carousel = carousel;

        // whether disable the links on swiping the carousel or not
        this.carousel.defaultOptions.disableLinksOnSwipe = true;
        this.carousel.defaultOptions.disableBubbling = true;
        this.carousel.defaultOptions.disableOnLiveEvents = false;

    };

    /* ------------------------------------------------------------------------------ */
    var p = disableLinksOnSwipe.prototype;

    /* ------------------------------------------------------------------------------ */
    // callbacks

    /**
     * calls by carousel exactly after setting up
     */
    //p.afterSetup = function () {};

    /**
     * calls before carousel initialization
     */
    //p.beforeInit = function () {};

    /**
     * calls after carousel initialization
     */
    //p.afterInit = function () {};

    /**
     * reads options and applies changes
     */
    p.readOptions = function () {
        var op = this.carousel.options;

        if ( op.disableLinksOnSwipe ) {
            this.carousel.view.addEventListener(MCEvents.SWIPE_START, this._swipeIntraction, this);
            this.carousel.view.addEventListener(MCEvents.SWIPE_MOVE, this._swipeIntraction, this);
            this.carousel.view.addEventListener(MCEvents.SWIPE_CANCEL, this._swipeIntraction, this);
            this.carousel.view.addEventListener(MCEvents.SWIPE_END, this._swipeIntraction, this);

            if ( op.disableOnLiveEvents ) {
                this.carousel.$element.on( 'click', 'a', this._checkLink.bind( this ) );
            } else {
                this.carousel.$element.find( 'a' ).on( 'click', this._checkLink.bind( this ) );
            }

        } else {
            this.carousel.view.removeEventListener(MCEvents.SWIPE_START, this._swipeIntraction, this);
            this.carousel.view.removeEventListener(MCEvents.SWIPE_MOVE, this._swipeIntraction, this);
            this.carousel.view.removeEventListener(MCEvents.SWIPE_CANCEL, this._swipeIntraction, this);
            this.carousel.view.removeEventListener(MCEvents.SWIPE_END, this._swipeIntraction, this);

            if ( op.disableOnLiveEvents ) {
                this.carousel.$element.off( 'click', 'a', this._checkLink.bind( this ) );
            } else {
                this.carousel.$element.find( 'a' ).off( 'click', this._checkLink.bind( this ) );
            }
        }
    };

    /**
     * remove all events and destroys the plugin
     */
    p.destroy = function () {
        if ( this.carousel.view ) {
            this.carousel.view.removeEventListener(MCEvents.SWIPE_START, this._swipeIntraction, this);
            this.carousel.view.removeEventListener(MCEvents.SWIPE_MOVE, this._swipeIntraction, this);
            this.carousel.view.removeEventListener(MCEvents.SWIPE_CANCEL, this._swipeIntraction, this);
            this.carousel.view.removeEventListener(MCEvents.SWIPE_END, this._swipeIntraction, this);
        }
        this.carousel.$element.off( 'click', 'a', this._checkLink.bind( this ) );
        this.carousel = null;
    };

    /* ------------------------------------------------------------------------------ */
    // private methods

    p._swipeIntraction = function( e ) {
        clearTimeout( this._to );
        if ( e.type === MCEvents.SWIPE_START ) {
            this._linksAreDisabled = true;
            this._hadMove = false;
        } else if ( e.type === MCEvents.SWIPE_MOVE ) {
            this._hadMove = true;
        } else {
            if ( this._hadMove ) {
                this._hadMove = false;
                this._to = setTimeout( function(){ this._linksAreDisabled = false; }.bind( this ), 5 );
            } else {
                this._linksAreDisabled = false;
            }
        }
    };

    p._checkLink = function( e ) {
        if ( this._linksAreDisabled ) {
            if ( this.carousel.options.disableBubbling ) {
                e.stopImmediatePropagation();
            }

            e.preventDefault();
        }
    };

    /* ------------------------------------------------------------------------------ */
    // register the plugin
    MasterCarousel.registerPlugin(disableLinksOnSwipe);

})(jQuery, window, document);


/* -------------------- src/plugins/mastercarousel.autoscroll.js -------------------- */


;(function ( $, window, document, undefined ) {
    "use strict";

    /**
     * autoScroll controller plugin contractor
     * @param  {MasterCarousel} carousel
     */
    var autoScrollController = function ( carousel ) {
        this.carousel = carousel;

        // adds autoScroll default value to carousel options
        this.carousel.defaultOptions.autoScroll = false;
        this.carousel.defaultOptions.autoScrollSpeed = 1;

    };

    /* ------------------------------------------------------------------------------ */
    var p = autoScrollController.prototype;

    /* ------------------------------------------------------------------------------ */
    // callbacks

    /**
     * calls by carousel exactly after setting up
     */
    //p.afterSetup = function () {};

    /**
     * calls before carousel initialization
     */
    //p.beforeInit = function () {};

    /**
     * calls after carousel initialization
     */
    //p.afterInit = function () {};

    /**
     * reads options and applies changes
     */
    p.readOptions = function () {
        this._scroll = this._scroll.bind( this );

        // add new methods to the carousel API
        $.extend( this.carousel, {

            startAutoScroll: function() {
                if ( !this._stop ) {
                    return;
                }

                this._stop = false;
                this.carousel.view.addEventListener(MCEvents.SWIPE_START, this._onSwipe, this);
                this.carousel.view.addEventListener(MCEvents.CHANGE_END, this._onSwipe, this);
                this.carousel.view.addEventListener(MCEvents.SWIPE_END, this._onSwipe, this);
                this.carousel.view.addEventListener(MCEvents.SWIPE_CANCEL, this._onSwipe, this);

                this._scroll();
            }.bind(this),

            stopAutoScroll: function() {
                if ( this._stop ) {
                    return;
                }

                this._stop = true;
                this.carousel.view.removeEventListener(MCEvents.SWIPE_START, this._onSwipe, this);
                this.carousel.view.removeEventListener(MCEvents.CHANGE_END, this._onSwipe, this);
                this.carousel.view.removeEventListener(MCEvents.SWIPE_END, this._onSwipe, this);
                this.carousel.view.removeEventListener(MCEvents.SWIPE_CANCEL, this._onSwipe, this);
            }.bind(this)
        });

        // is it already disabled, so reset the view items
        if ( this.carousel.options.autoScroll ) {
            this.carousel.startAutoScroll();
        } else {
            this.carousel.stopAutoScroll();
        }
    };

    /**
     * remove all events and destroys the plugin
     */
    p.destroy = function () {
        if ( this.carousel.view ) {
            this.carousel.view.removeEventListener(MCEvents.SWIPE_START, this._onSwipe, this);
            this.carousel.view.removeEventListener(MCEvents.SWIPE_END, this._onSwipe, this);
            this.carousel.view.removeEventListener(MCEvents.SWIPE_CANCEL, this._onSwipe, this);
            this.carousel.view.removeEventListener(MCEvents.CHANGE_END, this._onSwipe, this);
        }

        this.carousel = null;
    };

    /* ------------------------------------------------------------------------------ */
    // private methods

    p._onSwipe = function( event ) {
        var oldState = this._stop;
        this._stop = event.type === MCEvents.SWIPE_START;

        if ( !this._stop && this._stop !== oldState ) {
            this._scroll();
        }
    };

    /**
     * Scrolls the carousel
     */
    p._scroll = function() {
        if ( !this._stop ) {
            window.requestAnimationFrame( this._scroll );
        }

        this.carousel.view.scroller.drag( -this.carousel.options.autoScrollSpeed );
    };

    /* ------------------------------------------------------------------------------ */
    // register the plugin
    MasterCarousel.registerPlugin(autoScrollController);

})(jQuery, window, document);


/*! 
 * 
 * ================== js/libs/plugins/averta/averta-jquery.mastermenu.js =================== 
 **/ 

/*!
 * MasterMenu - Averta's exclusive responsive menu and megamenu jQuery plugin
 *
 * @version 	0.1.0
 * @requires 	jQuery 1.9+
 * @author 		Averta [averta.net]
 * @package 	Auxin Framework
 * @copyright 	Copyright © 2015 Averta, all rights reserved
 */

(function ( $, window, document ) {

	"use strict";

	var pluginName = "mastermenu",
		id = 1,
		isTouch = 'ontouchstart' in document,
		//isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
		defaults = {

			menuItem		  	: 'aux-menu-item', 			// Menu items class name
            menuItemContent     : 'aux-item-content',       // Menu item text content element
  			submenu	 		  	: 'aux-submenu',			// Submenu container class name
  			subIndicator 		: 'aux-submenu-indicator',	// Submenu indicator arrow
  			hover 	 		  	: 'aux-hover',				// It adds or removes from menu item when mouse moves over it
  			open 			  	: 'aux-open',				// Adds to opened menu items
  			noJS			  	: 'aux-no-js',				// No js class name, it removes by the menu after initialization
            tabs                : 'aux-menu-tabs',          // Tabs element in megamenu
            tab                 : 'aux-menu-tab',           // Tab item
            narrow              : 'aux-narrow',             // specifies the narrow menu layout, in default toggle and accordion menu appears as narrow menu
            wide                : 'aux-wide',               // specifies the wide layout of the menu, in default horizontal and vertical menus has this class name
            submenuHeader       : 'aux-submenu-header',     // Submenu header class name it only appears in cover menu
            submenuBack         : 'aux-submenu-back',       // Submenu back menu item class name, it only appears in cover menu type.

			type 			  	: 'horizontal',				// Type of the menu  'horizontal', 'vertical', 'toggle', 'accordion', 'cover'
			openOn 			  	: 'over', 					// Specifies the way of opening submenus "press" or "over"
			openDelay 		  	: 100, 						// Specifies delay amount before opening submenu [ms]
			closeDelay  	  	: 50,						// Specifies delay amount before closing submenu [ms]
			autoSwitch 		  	: 600, 						// Auto change menu type relative to window width it's useful for creating responsive layouts
			autoSwitchType	  	: 'accordion',				    // Specifies the type of auto-switching [usually toggle or accordion but other types are accepted]
			autoSwitchParent 	: null,						// Specifies the parent element of menu when it auto switches to another type.
			addSubIndicator  	: true, 					// Inserts indicator element to each menu item that has submenu.
			useSubIndicator		: true, 					// Use sub indicator element for opening or closing submenus instead of menu item. It only affects with 'toggle' or 'accordion' type.
            skipDelayForTabs    : true,                     // Whether skip the opening menu delay for the tabs or not.
            keepSubmenuInView   : true,                     // Whether check the submenu position in browser window and always keeps it in view, it changes submenu alignment if it requires.

            // cover menu options
            insertHeaderInSubs   : true,                     // Whether insert the parent menu name at top of the submenu.
            backLabel           : 'Back',                   // back menu item label in cover menu

			// This map will be used to adding type class names to the main element of MasterMenu
			typeMap : {
						toggle 		: 'aux-toggle',
						accordion 	: 'aux-toggle aux-accordion',
						vertical 	: 'aux-vertical',
						horizontal 	: 'aux-horizontal',
                        cover       : 'aux-toggle aux-cover'
					},

            submenuAlignMap : {
                        left   : 'aux-temp-left',
                        right  : 'aux-temp-right',
                        bottom : 'aux-temp-bottom',
                        top    : 'aux-temp-top',
                        pattern: /aux-temp-\w+/g
            }
		},

		attributeDataMap = {
			'type' 			: 'type',
			'open-on' 		: 'openOn',
			'open-delay' 	: 'openDelay',
			'close-delay'	: 'closeDelay',
			'switch-width'	: 'autoSwitch',
			'switch-type'	: 'autoSwitchType',
			'switch-parent'	: 'autoSwitchParent',
			'indicator'		: 'addSubIndicator'
		};

	function MasterMenuPlugin (element, options) {
		this.element = element;
		this.$element = $(element);

		// create element attribute options object
		var elementData = {},
			tempData;
		for ( var attribute in attributeDataMap ) {
			tempData = this.$element.data(attribute);
			if ( tempData !== undefined ) {
				elementData[attributeDataMap[attribute]] = tempData;
			}
		}

		this.settings = $.extend( {}, defaults, options, elementData );
		this._defaults = defaults;
		this._name = pluginName;
		this._uniqueId = this._name + '_' + id++;
		this.init();
	}

	$.extend(MasterMenuPlugin.prototype, {

		/**
		 * MasterMenu initialization method
		 * @private
		 */
		init : function () {
			var self = this,
				st = this.settings;


			self.$element.removeClass(st.noJS);

			// store initial parent element and prev element
			// it will be used to locating menu element in initial location in dom tree
			self.lastLocation  = 'defautlt';
			self.defaultParent = self.$element.parent();
			self.defaultPrev   = self.$element.prev();


            // cache menu items
            self.$menuItems = self.$element.find('.' + st.menuItem);

            self.pressEvent = 'click'  + '.' + self._uniqueId;

            // add submenu indicator if required
            if ( st.addSubIndicator ) {
                self.$menuItems.has('.' + st.submenu).find('>.' + st.menuItemContent).append('<span class="' + st.subIndicator + '"></span>');
                self.$subIndicators = self.$menuItems.find('.' + st.subIndicator);
            }

            // mouse interactions
            self.handlerProxy = $.proxy(self._menuInteract, self);
            self.$menuItems.on('mouseenter'  + '.' + self._uniqueId, self.handlerProxy)
                           .on('focusin'     + '.' + self._uniqueId, self.handlerProxy)
                           .on('mouseleave'  + '.' + self._uniqueId, self.handlerProxy)
                           .on('focusout'    + '.' + self._uniqueId, self.handlerProxy);

            // init slider type
			self.changeType(st.type);

			if ( st.autoSwitch > 0 ){
				$(window).on('resize' + '.' + self._uniqueId, $.proxy(self._autoSwitch, self));
				self._autoSwitch();
			}

		},

		/**
		 * Prepare interaction events based on new menu type
		 * @private
		 */
		_onTypeChanged : function () {

			if ( this.lastType === this.type ) {
				return;
			}

			var self = this,
				type = self.type,
				st = self.settings;

			// remove listeners
			if ( self.lastType ) {
				self.$menuItems.off(self.pressEvent, self.handlerProxy);
				if ( st.useSubIndicator ) {
					self.$subIndicators.off(self.pressEvent, self.handlerProxy);
				}
				if ( st.openOn === 'press' ) {
					$(document).off(self.pressEvent, self.handlerProxy);
				}
			}

			self._closeAll(false);


            if ( type === 'horizontal' || type === 'vertical' ) {

                self.$element.removeClass(st.narrow)
                             .addClass(st.wide);

                self.isNarrow = false;

                if ( st.openOn === 'over' ) {
                    self.openOnOver = true;
                } else if ( st.openOn === 'press' ) {
                    $(document).on(self.pressEvent, self.handlerProxy);
                    self.$menuItems.on(self.pressEvent, self.handlerProxy);
                }

                // keep open tabs
                self.keepTabs = true;

                // open first tabs
                self.$element.find('.' + st.tabs + '>.' + st.tab + ':first-child').addClass(st.open);

                // if last type was cover, remove not requierd elements
                if ( self.lastType === 'cover' ) {
                    self._removeCoverMenuElements();
                }

            } else { // 'accordion', 'toggle', 'cover'

                self.openOnOver = false;
                self.isNarrow = true;

                self.$element.addClass(st.narrow)
                             .removeClass(st.wide);

                if ( st.useSubIndicator && st.addSubIndicator ) {
                    self.$subIndicators.on(self.pressEvent, self.handlerProxy);
                } else {
                    self.$menuItems.on(self.pressEvent, self.handlerProxy);
                }
                // disable tabbing function in toggle or accordion
                self.keepTabs = false;

                if ( type === 'cover' ) {
                    self._insertCoverMenuElements();
                } else {
                    self._removeCoverMenuElements();
                }
            }

            self.lastType = type;

            self.$element.trigger( 'typeChanged' );
		},

		/**
		 * Controls all interactions over the menu
		 * @private
		 * @param 	{jQuery Evenr} event
		 * @since 	v1.0
		 */
		_menuInteract : function ( event ) {
			var $this = $(event.currentTarget),
				$menuItem = $this,
				self = this,
				st = self.settings,
				etype = event.type;

			// target is a submenu indicator
			if ( $this.hasClass(st.subIndicator) ) {
				$menuItem = $this.parents('.' + st.menuItem).eq(0);
			} else if ( $this.hasClass(st.submenuBack) ) {
                $menuItem = $this.parents('.' + st.menuItem).eq(0);
            }

			var	hasSubmenu = $menuItem.find('>.' + st.submenu).length !== 0;

			switch ( etype ) {
				case 'mouseenter':
                case 'focusin':
					$menuItem.addClass(st.hover);
					if ( hasSubmenu && self.openOnOver ) {
						self._openMenu($menuItem, st.openDelay);
					}
					break;
				case 'mouseleave':
                case 'focusout':
					$menuItem.removeClass(st.hover);
					if ( hasSubmenu && self.openOnOver ) {
						self._closeMenu($menuItem, st.closeDelay);
					}
					break;
                case 'mouseup':
				case 'click':
					if ( $menuItem.is(document) ) {
						self._closeAll();
					} else if ( $menuItem.hasClass(st.open) ) {
						// already opened? Ok close it
						self._closeMenu($menuItem, 0);
						// prevent clicking on menu item link
                        event.preventDefault();
                        // prevent bobbling
                        event.stopPropagation();
					} else {

						if ( self.type !== 'toggle' ) {
							// close others
							self._closeOthers($menuItem);
						}

                        if ( hasSubmenu ) {
                            self._openMenu($menuItem, 0);
                            // prevent clicking on menu item link
                            event.preventDefault();
                        }
                        // prevent bobbling
                        event.stopPropagation();
					}
			}
		},

		/**
		 * Auto switch handler, it checks window width value and if it comes lower than
		 * options.autoSwitch value transform the menu to another type.
		 * @private
		 * @param  {jQuery Event} event
		 */
		_autoSwitch : function (event) {
			var autoSwitchType = this.settings.autoSwitchType;

			if ( this.type !== autoSwitchType && window.innerWidth <= this.settings.autoSwitch ) {
                this.changeType(autoSwitchType);
                if ( this.settings.autoSwitchParent ) {
                    this.changeLocation(this.settings.autoSwitchParent);
                }
			} else if ( this.type !== this.settings.type && window.innerWidth > this.settings.autoSwitch ) { // is not default type
				this.changeType('default');
				if ( this.settings.autoSwitchParent ) {
					this.changeLocation('default');
				}
			}
		},

        /**
         * Adds required elements of cover menu to submenus.
         * @private
         */
        _insertCoverMenuElements : function () {

            var self = this,
                st = self.settings;

            self.$element.find('.' + st.submenu).each(function () {
                var $this = $(this),

                // add back element
                backItem = $('<li></li>').html('<div class="' + st.menuItemContent + '">' + st.backLabel + '</div>')
                                         .addClass(st.menuItem)
                                         .addClass(st.submenuBack)
                                         .prependTo($this)
                                         .on(self.pressEvent, self.handlerProxy);

                if ( st.insertHeaderInSubs ) {
                    var headerContent = $this.parent().find('>.' + st.menuItemContent).eq(0).clone();

                    headerContent.find('.' + st.subIndicator).remove();

                    $('<li></li>').append(headerContent)
                                  .prependTo($this)
                                  .addClass(st.menuItem)
                                  .addClass(st.submenuHeader);
                }
            });
        },

        /**
         * Removes the added cover menu elements from markup.
         * @private
         */
        _removeCoverMenuElements : function () {
            var st = this.settings;

            // remove backElements
            this.$element.find('.' + st.submenuBack).remove();

            // remove submebu titles
            if ( st.insertHeaderInSubs ) {
                this.$element.find('.' + st.submenuHeader).remove();
            }
        },


        /**
         * Checkes the position of opening submenu and keeps it in view.
         * @private
         * @param  {jQuery Object} $menuItem
         */
        _checkSubmenuPosition: function ( $menuItem ) {
            var st = this.settings,
                submenu = $menuItem.find('>.' + st.submenu),
                $window = $(window);

            // it's not required for megamenu submenus
            if ( $menuItem.parent().hasClass(st.megamenu) ) {
                return;
            }

            // remove last added aligning classnames
            submenu.attr('class', submenu.attr('class').replace(st.submenuAlignMap.pattern, ''));

            // cache boundaries
            var offset = submenu.offset(),
                offsetTop = offset.top - $window.scrollTop(),
                offsetLeft = offset.left - $window.scrollLeft(),
                offsetRight = offsetLeft + submenu.width(),
                offsetBottom = offsetTop + submenu.height();

             // is it menu root item?
             if ( $menuItem.parent().is( this.$element) ) {

                if ( offsetRight > $window.width() ) {

                    var lastShift = submenu.data( 'menu-shift' ) || 0,
                    shift = $window.width() - offsetRight + lastShift;

                    if ( $( 'body' ).hasClass( 'rtl' ) ) {
                        submenu.css( 'right', Math.min( 0, shift ) );
                    } else {
                        submenu.css( 'left', Math.min( 0, shift ) );
                    }

                    submenu.data( 'menu-shift', shift );

                    return;
                }

            }

            if ( offsetRight > $window.width() ) {
                submenu.addClass(st.submenuAlignMap.left);
            } else if ( offsetLeft < 0 ) {
                submenu.addClass(st.submenuAlignMap.right);
            }

            // if ( offsetTop < 0 ) {
            //     submenu.addClass(st.submenuAlignMap.bottom);
            // } else if ( offsetBottom > $window.height() ) {
            //     submenu.addClass(st.submenuAlignMap.top);
            // }

        },

		/**
		 * Open submenu
		 * @private
		 * @param  {jQuery Object} $menuItem
		 * @param  {Number} delay
		 */
		_openMenu : function ($menuItem, delay){
            var st = this.settings;

			// Remove last timeout if exists
			clearTimeout($menuItem.data('openTo'));
			clearTimeout($menuItem.data('closeTo'));

            // remove opening delay for the tabs
            if ( st.skipDelayForTabs && $menuItem.hasClass(st.tab) ) {
                delay = 0;
            }

			if ( delay === 0 ) {
                this.$element.trigger( { type: 'beforeOpen', item: $menuItem } );

                $menuItem.addClass(this.settings.open);

                if ( !this.isNarrow && st.keepSubmenuInView ) {
                    this._checkSubmenuPosition($menuItem);
                }

                // close sibling tabs
                if ( this.keepTabs && $menuItem.hasClass(st.tab) ) {
                    this._closeOthers($menuItem, false);
                }

                this.$element.trigger( { type: 'afterOpen', item: $menuItem } );
                return;
            }

            var openTo = setTimeout($.proxy(this._openMenu, this), delay, $menuItem, 0);
            $menuItem.data('openTo', openTo);
        },

        /**
         * close submenu
         * @private
         * @param  {jQuery Object} $menuItem
         * @param  {Number}        delay
         * @param  {Boolean}       notTabs     whether close tab items or not
         */
        _closeMenu : function($menuItem, delay, notTabs) {
            var st = this.settings;

            if ( notTabs === undefined ) {
                notTabs = this.keepTabs;
            }

            // Remove last timeout if exists
            clearTimeout($menuItem.data('closeTo'));
            clearTimeout($menuItem.data('openTo'));

            if ( delay === 0 ) {
                this.$element.trigger( { type: 'beforeClose', item: $menuItem } );

                if ( !notTabs || !$menuItem.hasClass(st.tab) ){
                    $menuItem.removeClass(st.open);
                }

                // close children menus
                $menuItem.find('.' + st.menuItem + '.' + st.open + (notTabs ? ':not(.' + st.tab + ')' : ''))
                         .removeClass(st.open);


                this.$element.trigger( { type: 'afterClose', item: $menuItem } );
                return;
            }


            var closeTo = setTimeout($.proxy(this._closeMenu, this), delay, $menuItem, 0, notTabs);
            $menuItem.data('closeTo', closeTo);
        },

        /**
         * Close other opened menus
         * @private
         * @param  {jQuery Object}  $menuItem
         * @param  {Boolean}        notTabs     whether close tab items or not
         */
        _closeOthers : function ($menuItem, notTabs) {

            if ( notTabs === undefined ) {
                notTabs = this.keepTabs;
            }

            this._closeMenu($menuItem.siblings(), 0, notTabs);

        },

        /**
         * Close all opened menu items
         * @param {Boolean} notTabs     whether close tab items or not
		 * @private
		 */
		_closeAll : function (notTabs){

            if ( notTabs === undefined ) {
                notTabs = this.keepTabs;
            }

            this.$element.find('.' + this.settings.open + (notTabs ? ':not(.' + this.settings.tab + ')' : '')).removeClass(this.settings.open);
		},

		/*-----------------------------------------------------------*\
			Public API
		\*-----------------------------------------------------------*/

		/**
		 * Transforms Menu to toggle menu, vertical menu, accordion menu and horizontal
		 * @public
		 * @param  {string} type
		 *          values: toggle
		 *         		    horizontal
		 *         		    vertical
		 *         		    accordion
         *                  cover
		 *         		    default
		 */
		changeType: function (type) {

			if ( this.type !== undefined ) {
				this.$element.removeClass(this.settings.typeMap[this.type]);
			} else {
                // remove all probable type classnames
                for ( var typeKey in this.settings.typeMap ) {
                    this.$element.removeClass( this.settings.typeMap[typeKey] );
                }
            }

			// change type to initial value
			if ( type === 'default' ) {
				type = this.settings.type;
			}

			// update menu type
			this.type = type;
			this.$element.addClass(this.settings.typeMap[this.type]);

			this._onTypeChanged();
        },

        /**
         * Changes location of menu in dom tree it also restore the menu to the initial location if
         * location with "default" value passed.
         * @public
         * @param  {String} location jQuery selector or "default" value
         */
        changeLocation: function (location) {
            if ( this.lastLocation === location ) {
                return;
            }

            if ( location === 'default' ) {
                this.locationChanged = false;
                if ( this.defaultPrev.length === 0 ) {
                    this.$element.prependTo(this.defaultParent[0]);
                } else {
                    this.defaultPrev[0].after(this.$element);
                }
            } else {
                this.locationChanged = true;
                this.$element.appendTo(location);
            }

            this.lastLocation = location;

            this.$element.trigger( 'locationChanged' );
		}

	});


    // enable public access
    window.MasterMenuPlugin = window.MasterMenuPlugin || MasterMenuPlugin;

	$.fn[pluginName] = function (options) {
		var args = arguments,
			plugin = 'plugin_' + pluginName;

		// Is the first parameter an object (options), or was omitted,
		// instantiate a new instance of the plugin.
		if (options === undefined || typeof options === 'object') {
			return this.each(function () {

				// Only allow the plugin to be instantiated once,
				// so we check that the element has no plugin instantiation yet
				if (!$.data(this, plugin)) {
					$.data(this, plugin, new MasterMenuPlugin( this, options ));
				}
			});

		// If the first parameter is a string and it doesn't start
		// with an underscore or "contains" the `init`-function,
		// treat this as a call to a public method.
		} else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {

			// Cache the method call
			// to make it possible
			// to return a value
			var returns;

			this.each(function () {
				var instance = $.data(this, plugin);

				// Tests that there's already a plugin-instance
				// and checks that the requested public method exists
				if (instance instanceof MasterMenuPlugin && typeof instance[options] === 'function') {

					// Call the method of our plugin instance,
					// and pass it the supplied arguments.
					returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
				}

				// Allow instances to be destroyed via the 'destroy' method
				if (options === 'destroy') {
				  $.data(this, plugin, null);
				}
			});

			// If the earlier cached method
			// gives a value back return the value,
			// otherwise return this to preserve chainability.
			return returns !== undefined ? returns : this;
		}
	};

})( jQuery, window, document );


/*! 
 * 
 * ================== js/src/plugins/auxin-jquery-mastermenu-toggle-animate.js =================== 
 **/ 

/**
 * Add animation effect for toggle master menu
 */
;(function ( $, window, document, undefined ) {

    if ( !window.MasterMenuPlugin || !window.CTween ) {
        return;
    }

    var p = MasterMenuPlugin.prototype;

    /**
     * Override the init method of Master Menu Plugin
     */
    var superInit = p.init;
    p.init = function() {
        superInit.apply( this, arguments );
        if ( this.settings.toggleAnimation !== false ) {
            this.$element.on( 'typeChanged', this._checkForToggle.bind( this ) );
            this.settings.toggleAnimationDuration = this.settings.toggleAnimationDuration || 600;
            this._checkForToggle();
        }
    };

    /**
     * enable animation if type is toggle or accordion
     */
    p._checkForToggle = function() {
        if ( this.type === 'toggle' || this.type === 'accordion' ) {
            this.$element.on( 'beforeOpen', this._openAnimate.bind( this ) );
            this.$element.on( 'beforeClose', this._closeAnimate.bind( this ) );
        } else {
            this.$element.off( 'beforeOpen beforeClose' );
            this.$element.find( '.aux-submenu' ).css( 'height', '' );
        }
    };

    /**
     * starts the open animation
     * @param  {Event} e
     */
    p._openAnimate = function( e ) {
        var $submenu = e.item.find( '>.aux-submenu' ).eq(0),
            lastTween = $submenu.data( 'tween' );
            subHeight = 0;

        // figure the height
        $submenu.find( '>*' ).each( function( index, item ) {
            subHeight += $(item).outerHeight();
        } );


        if ( lastTween ) {
            lastTween.stop( true );
        }

        lastTween = CTween.animate( $submenu, this.settings.toggleAnimationDuration, {
            height: subHeight + 'px'
        }, {
            ease: 'easeInOutQuart',
            complete: function() {
                $submenu.css( 'height', 'auto' );
            }
        });

        $submenu.data( 'tween', lastTween );
    };

    /**
     * starts the close animation
     * @param  {Event} e
     */
    p._closeAnimate = function( e ) {

        var $submenus = e.item.find( '>.aux-submenu' ),
            lastTween = $submenus.data( 'tween' ),
            self = this;

        if ( lastTween ) {
            lastTween.stop( true );
        }

        $submenus.each( function( index, submenu) {
            var subHeight = 0;

            $(submenu).find( '>*' ).each( function( index, item ) {
                subHeight = $(item).outerHeight();
            })

            if ( $(submenu).height() === 0 ) {
                return;
            } else {
                $(submenu).height( subHeight );  
            }

            lastTween = CTween.animate( $(submenu), self.settings.toggleAnimationDuration, {
                height: '0'
            }, {
                ease: 'easeInOutQuart',
                complete: function() {
                    $(submenu).find( '.aux-submenu' ).css( 'height', '' );
                }
            });
    
            $(submenu).data( 'tween', lastTween );

        } ) 

    };

})( jQuery, window, document );


/*! 
 * 
 * ================== js/libs/plugins/averta/averta-jquery.livetabs.js =================== 
 **/ 

/*
 *  Averta LiveTabs - v1.6.0 (2014-11-22)
 *  https://bitbucket.org/averta/averta-livetabs/
 *
 *  A jQuery plugin for enabling tabs.
 *
 *  Copyright (c) 2010-2014  <>
 *  License: 
 */
/**
 * USAGE : 
 * -----------------------------------------------------------------------------------------------------
 * HTML:
   <div id="container">
      <ul class="tabs">
        <li class="active"><a href="#s1">Tab1</a></li>
        <li><a href="#s2">Tab2</a></li>
        <li><a href="#s3">Tab3</a></li>
      </ul>
   
      <ul class="tabs-content">
        <li id="s1">Contnt1</li>
        <li id="s2">Contnt2</li>
        <li id="s3">Contnt3</li>
      </ul> 
   </div>
 * 
 * JS:
   $('#container').avertaLiveTabs({
      tabs:            'ul.tabs > li',            // Tabs selector
      tabsActiveClass: 'active',                  // A Class that indicates active tab
      contents:        'ul.tabs-content > li',    // Tabs content selector    
      contentsActiveClass: 'active',              // A Class that indicates active tab-content    
      transition:      'fade',                    // Animation type white swiching tabs
      duration :       '500',                     // Animation duration in mili seconds
      connectType:     'index',                   // connect tabs and contents by 'index' or 'id'
      enableHash:      false ,                    // check to select initial tab based on hash address
      updateHash:      false ,                    // update hash in browser while switching between tabs
      hashSuffix:      '-tab'                     // suffix to add at the end of hash url to prevent page scroll
   });
 
 * ---------------------------------------------------------------------------------------------------------
 **/

 if( typeof Object.create !== 'function' ){ Object.create = function (obj){ function F(){} F.prototype = obj; return new F();}; }

;(function($){

    var Container = {

        init : function(el, options){
            //cache this
            var self        = this;
            self.options    = $.extend({} ,$.fn.avertaLiveTabs.defaultOptions, options || {} );
            
            // Access to jQuery and DOM versions of element
            self.$el        = $(el);
            self.el         = el;
            
            self.$tabs      = self.$el.find(self.options.tabs);
            self.$contents  = self.$el.find(self.options.contents);
            
            self.setup();
        },
        
        setup: function(){
            var self = this,
                $activeTab;
            // click event when new tab selected
            self.$tabs.on('click', {self:self}, self.onTabClicked);

            // if hash is enabled in options get current hash and select related tab
            if(self.options.enableHash && window.location.hash !== '') {
                var id      = self.trimID( window.location.hash );
                $activeTab = self.getTabById(id);
            } else {
                // find the tab with tabsActiveClass
                $activeTab = self.$tabs.filter('.'+self.options.tabsActiveClass);
            }
            // validate to select the active tab for start
            $activeTab     = ($activeTab.length)?$activeTab:self.$tabs.first();
            $activeTab.trigger('click', true);
            
        },
        
        onTabClicked:function(event, fromSetup){
            event.preventDefault();
            var self   = event.data.self,
                $this  = $(this),
                $tabContent,
                activeId;

            if( !fromSetup && $this.hasClass('active') ){
                return;
            } 
            
            self.$tabs.removeClass(self.options.tabsActiveClass);
            $this.addClass(self.options.tabsActiveClass);
            
            self.$contents.hide();
            if( self.options.connectType === 'id' ){
                activeId     = self.getIdByTab( $this );
                $tabContent = self.getContentById( activeId );
            } else {
                $tabContent = self.$contents.eq( $this.index() );
            }
            $tabContent.fadeIn(self.options.duration);

            // update hash in page address if updateHash is enabled
            if( self.options.updateHash ){
                activeId  = self.getIdByTab( $this );
                activeId  = self.trimID( activeId );
                activeId  = activeId ? activeId + self.options.hashSuffix : '';

                if( window.history && window.history.pushState )
                    window.history.pushState(null, null, window.location.href.split('#')[0]+'#'+activeId);
                else
                    window.location.hash = activeId;
            }

            // trigger custom event
            self.$el.trigger('avtTabChange', $tabContent.attr('id'));

        },

        getTabById:function(id){
            // remove hashSuffix (if exist) from id hash to get real element id
            id = id.split(this.options.hashSuffix)[0];
            // search for hash in tabs markup - generaly should be direct children of tab
            // check for href="#id" format
            var $activeTab = this.$tabs.find('[href="#'+ id +'"]').eq(0);
            // if no match found, check for href="id" format too
            if(!$activeTab.length)
                $activeTab = this.$tabs.find('[href="'+ id +'"]').eq(0);
            // get the tab if hash found in it
            return $activeTab.length ? $activeTab.parent() : $activeTab;
        },

        getContentById:function(id){
            return this.$contents.filter( '#'+ this.trimID(id) );
        },

        trimID:function(id){
            return id.replace( /^\s+|\s+$|#/g, '' );
        },

        getIdByTab:function($tab){
            var $anchor = $tab.find('[href]').eq(0);
            return $anchor.length?$anchor.attr('href'):false;
        }
    };
    
    
     $.fn.avertaLiveTabs = function(options){
        return this.each(function(){
            var container = Object.create(Container);
            container.init(this, options);
        });
    };
    
    $.fn.avertaLiveTabs.defaultOptions = {
        tabs:            'ul.tabs > li',            // Tabs selector
        tabsActiveClass: 'active',                  // A Class that indicates active tab
        contents:        'ul.tabs-content > li',    // Tabs content selector    
        contentsActiveClass: 'active',              // A Class that indicates active tab-content    
        transition:      'fade',                    // Animation type white swiching tabs
        duration :       '500',                     // Animation duration in mili seconds
        connectType:     'index',                   // connect tabs and contents by 'index' or 'id'
        enableHash:      false ,                    // check to select initial tab based on hash address
        updateHash:      false ,                    // update hash in browser while switching between tabs
        hashSuffix:      '-tab'                     // suffix to add at the end of hash url to prevent page scroll
    };
    
})(jQuery);


/*! 
 * 
 * ================== js/libs/plugins/averta/averta-jquery.accordion.js =================== 
 **/ 

/**
 * Averta.Accordion v2.0
 * An jQuery for Accordion and toggles
 * Copyright (c) averta | http://averta.net | 2016
 * licensed under the MIT license
 **/

/**
 * USAGE :
 * -----------------------------------------------------------------------------------------------------
 * HTML:
   <dl id="container">
        <section class="active">
            <dt><i>-</i>Nam ante quam, venenatis</dt>
            <dd>Lorem ipsum dolor isus. Ut neque.</dd>
        </section>

        <section>
            <dt><i>-</i>Nam ante quam, venenatis</dt>
            <dd>Lorem ipsum dolor isus. Ut neque.</dd>
        </section>
   </dl>
 *
 * JS:
   $('#container').avertaAccordion({
        items:            'section',    // accordion item selector
        itemActiveClass:  'active',     // A Class that indicates active item
        itemHeader:       'dt',         // item header selector
        itemContent:      'dd',         // item content selector
        transition:       'fade',       // Animation type white swiching tabs
        hideDuration :    '300' ,       // Hiding duration in mili seconds
        showDuration :    '500' ,       // Showing duration in mili seconds
        hideEase :        'linear' ,    // Ease for hiding transition
        showEase :        'linear' ,    // Ease for showing transition
        oneVisible:        true  ,      // Always just one item can be open or not
        collapseOnInit:    true         // collapse all items on accordion init
        onExpand:          function(){},// callback that fires on expanding item  - param: item
        onCollapse:        function(){} // callback that fires on collapsing item - param: item
   });
 *
 * ---------------------------------------------------------------------------------------------------------
 **/
if( typeof Object.create !== 'function' ){ Object.create = function (obj){ function F(){} F.prototype = obj; return new F();}; }

;( function($){

    var Container = {

        init : function(el, options){
            //cache this
            var self        = this;
            self.options    = $.extend({} ,$.fn.avertaAccordion.defaultOptions, options || {} );

            // Access to jQuery and DOM versions of element
            self.$el        = $(el);
            self.el         = el;

            self.$items     = self.$el.find(self.options.items);
            // skip if no item found
            if( ! self.$items.length ) {
                return;
            }

            self.$items.find(self.options.itemContent).wrap( '<div class="' + self.options.contentWrapClass + '"></div>' );

            self.$headers   = self.$items.find(self.options.itemHeader);
            self.$contents  = self.$items.find( '.' + self.options.contentWrapClass );
            self.setup();
        },

        setup: function(){
            var self = this;

            // add click handler on each item's header'
            self.$headers.on('click', {self:self}, self.onHeaderClicked);


            // collapse all elements on start
            if( self.options.collapseOnInit || self.options.oneVisible ) {
                self._closeContent( self.$contents, 0 );
                self.options.onCollapse(self.$items);
            }

            // if oneVisible is true, expand the active element
            if( self.options.oneVisible ){
                var $actives = self.$items.filter('.'+self.options.itemActiveClass).first();
                // if active is not defined, get first element as active item
                $actives = $actives.length?$actives:self.$items.first().addClass(self.options.itemActiveClass);
                // expand active element
                self._openContent( $actives.find( '.' + self.options.contentWrapClass ), 0 );
                self.options.onExpand($actives);

            }else if( self.options.collapseOnInit ){
                // remove active class if active item is collapsed
                self.$items.removeClass(self.options.itemActiveClass);
            }

            // get hash id and expand the item
            if( window.location.hash && this.options.expandHashItem ){
                self.expandHashItem();
            }

            if ( this.options.expandHashItem ){
                $(window).on('hashchange', self.expandHashItem);
            }
            
        },

        expandHashItem: function(){
            var self   = this;
            var $hashHead = $(window.location.hash).find(self.options.itemHeader);
            $hashHead.trigger('click', {self:self}, self.onHeaderClicked);
        },

        onHeaderClicked:function(event){
            event.preventDefault();
            var self     = event.data.self;
            var $header  = $(this);
            var $item    = $header.closest(self.options.items);

            // skip if the target is active item
            if( $item.hasClass( self.options.itemActiveClass ) && self.options.oneVisible ) {
                return;
            }

            var $content = $item.find( '.' + self.options.contentWrapClass );


            if( self.options.oneVisible ){
                // remove active class from all items and add to current item
                self.$items.removeClass(self.options.itemActiveClass);
                $item.addClass(self.options.itemActiveClass);

                // collapse all items and expand current item
                self._closeContent( self.$contents, self.options.hideDuration, $content );

                self.options.onCollapse(self.$items);

                self._openContent( $content, self.options.showDuration );

                self.options.onExpand($item);

            } else {

                if ( $item.hasClass( self.options.itemActiveClass ) ) {
                    self._closeContent( $content, self.options.hideDuration );
                    $item.removeClass(self.options.itemActiveClass);
                    self.options.onCollapse($item);
                } else {
                    self._openContent( $content, self.options.showDuration );
                    $item.addClass(self.options.itemActiveClass);
                    self.options.onExpand($item);
                }
            }

        },

        _openContent: function( $contents, duration, $exclude ) {
            var self = this;
            if ( !$contents.length ) {
                $contents = [$contents];
            }


            $.each( $contents,  function( index, content ){
                var $content = $(content);

                if ( $exclude && $content === $exclude ) {
                    return;
                }

                clearTimeout( $content.data( 'toggle-to' ) );
                if ( duration === 0 ) {
                    $content.css( 'height', 'auto' );
                } else {
                    $content.css( 'height', $content.find( self.options.itemContent ).outerHeight() + 'px' );
                    $content.data( 'toggle-to', setTimeout( function(){ $content.css( 'height', 'auto' ); }, duration ) );
                }

            } );
        },

        _closeContent: function( $contents, duration, $exclude ) {
            var self = this;
            if ( !$contents.length ) {
                $contents = [$contents];
            }

            $.each( $contents, function( index, content ){
                var $content = $(content);

                if ( $exclude && $content === $exclude ) {
                    return;
                }

                clearTimeout( $content.data( 'toggle-to' ) );
                if ( duration === 0 ) {
                    $content.css( 'height', '0' );
                } else {
                    $content.css( 'height', $content.find( self.options.itemContent ).outerHeight() + 'px' );
                    $content.data( 'toggle-to', setTimeout( function(){ $content.css( 'height', '0' ); }, 1 ) );
                }
            } );
        }

    };

     $.fn.avertaAccordion = function(options){
        return this.each(function(){
            var container = Object.create(Container);
            container.init(this, options);
        });
    };

    $.fn.avertaAccordion.defaultOptions = {
        items:            'section',           // accordion item selector
        itemActiveClass:  'active',            // A Class that indicates active item
        contentWrapClass: 'acc-content-wrap',  // content wrap element classname
        itemHeader:       'dt',                // item header selector
        itemContent:      'dd',                // item content selector
        transition:       'fade',              // Animation type white swiching tabs
        hideDuration :    '300' ,              // Hiding duration in mili seconds
        showDuration :    '500' ,              // Showing duration in mili seconds
        hideEase :        'linear' ,           // Ease for hiding transition
        showEase :        'linear' ,           // Ease for showing transition
        oneVisible:        true  ,             // Always just one item can be open or not
        collapseOnInit:    true  ,             // collapse all items on accordion init
        expandHashItem:    true,               // expand the item by hash id 
        onExpand:          function(){},       // callback that fires on expanding item  - param: item
        onCollapse:        function(){}        // callback that fires on collapsing item - param: item
    };


})(jQuery);


/*! 
 * 
 * ================== js/libs/plugins/averta/jquery.appearl.js =================== 
 **/ 

/**
 * A super simple jQuery plugin checks if element is visible on scroll.
 *
 *  @author Averta
 */
;( function( $, window, document, undefined ) {

  "use strict";

  var pluginName = "appearl",
      defaults = {
        offset: 0,
        insetOffset: '50%'
      },
      attributesMap = {
        'offset': 'offset',
        'inset-offset': 'insetOffset'
    },
    $window = $(window);

  // The actual plugin constructor 
  function Plugin ( element, options ) {
      this.element   = element;
      this.$element  = $(element);
      this.settings  = $.extend( {}, defaults, options );

      // read attributes
      for ( var key in attributesMap ) {
        var value = attributesMap[ key ],
            dataAttr = this.$element.data( key );

        if ( dataAttr === undefined ) {
            continue;
        }

        this.settings[ value ] = dataAttr;
      }

      this.init();
  }

  // Avoid Plugin.prototype conflicts
  $.extend( Plugin.prototype, {
      init: function() {
        if ( typeof this.settings.offset === 'object' ) {
          this._offsetTop = this.settings.offset.top;
          this._offsetBottom = this.settings.offset.bottom;
        } else {
          this._offsetTop = this._offsetBottom = this.settings.offset;
        }
        
        this._appeared = false;
        this._lastScroll = 0;
        
        $window.on( 'scroll resize', this.update.bind( this ) );
        setTimeout( this.update.bind(this) );
      },
        
      update: function( event ) {
        var rect = this.element.getBoundingClientRect(),
        areaTop = this._parseOffset( this._offsetTop ),
        areaBottom = window.innerHeight - this._parseOffset( this._offsetBottom ),
        insetOffset = this._parseOffset( this.settings.insetOffset, true );

        if ( rect.top + insetOffset <= areaBottom && rect.bottom - insetOffset >= areaTop ) {
          !this._appeared && this.$element.trigger( 'appear', [{ from: ( this._lastScroll <= $window.scrollTop() ? 'bottom' : 'top' ) }] );
          this._appeared = true;
        } else if ( this._appeared ) {
          this.$element.trigger( 'disappear', [{ from: ( rect.top < areaTop ? 'top' : 'bottom' ) }] );
          this._appeared = false;
        }

        this._lastScroll = $window.scrollTop();
      },

      _parseOffset: function( value, inset ) {
        var percentage = typeof value === 'string' && value.indexOf( '%' ) !== -1;
        value = parseInt( value );
        
        return !percentage ? value : ( inset ? this.element.offsetHeight : window.innerHeight ) * value / 100;
      }
        
  } );

  $.fn[ pluginName ] = function( options ) {
      return this.each( function() {
          if ( !$.data( this, "plugin_" + pluginName ) ) {
              $.data( this, "plugin_" +
                  pluginName, new Plugin( this, options ) );
          }
      } );
  };

} )( jQuery, window, document );


/*! 
 * 
 * ================== js/libs/plugins/objectFitPolyfill.min.js =================== 
 **/ 

!function(){"use strict";if("undefined"!=typeof window){var t=window.navigator.userAgent.match(/Edge\/(\d{2})\./),e=!!t&&parseInt(t[1],10)>=16;if("objectFit"in document.documentElement.style!=!1&&!e)return void(window.objectFitPolyfill=function(){return!1});var i=function(t){var e=window.getComputedStyle(t,null),i=e.getPropertyValue("position"),n=e.getPropertyValue("overflow"),o=e.getPropertyValue("display");i&&"static"!==i||(t.style.position="relative"),"hidden"!==n&&(t.style.overflow="hidden"),o&&"inline"!==o||(t.style.display="block"),0===t.clientHeight&&(t.style.height="100%"),-1===t.className.indexOf("object-fit-polyfill")&&(t.className=t.className+" object-fit-polyfill")},n=function(t){var e=window.getComputedStyle(t,null),i={"max-width":"none","max-height":"none","min-width":"0px","min-height":"0px",top:"auto",right:"auto",bottom:"auto",left:"auto","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px"};for(var n in i){e.getPropertyValue(n)!==i[n]&&(t.style[n]=i[n])}},o=function(t,e,i){var n,o,l,a,d;if(i=i.split(" "),i.length<2&&(i[1]=i[0]),"x"===t)n=i[0],o=i[1],l="left",a="right",d=e.clientWidth;else{if("y"!==t)return;n=i[1],o=i[0],l="top",a="bottom",d=e.clientHeight}return n===l||o===l?void(e.style[l]="0"):n===a||o===a?void(e.style[a]="0"):"center"===n||"50%"===n?(e.style[l]="50%",void(e.style["margin-"+l]=d/-2+"px")):n.indexOf("%")>=0?(n=parseInt(n),void(n<50?(e.style[l]=n+"%",e.style["margin-"+l]=d*(n/-100)+"px"):(n=100-n,e.style[a]=n+"%",e.style["margin-"+a]=d*(n/-100)+"px"))):void(e.style[l]=n)},l=function(t){var e=t.dataset?t.dataset.objectFit:t.getAttribute("data-object-fit"),l=t.dataset?t.dataset.objectPosition:t.getAttribute("data-object-position");e=e||"cover",l=l||"50% 50%";var a=t.parentNode;i(a),n(t),t.style.position="absolute",t.style.height="100%",t.style.width="auto","scale-down"===e&&(t.style.height="auto",t.clientWidth<a.clientWidth&&t.clientHeight<a.clientHeight?(o("x",t,l),o("y",t,l)):(e="contain",t.style.height="100%")),"none"===e?(t.style.width="auto",t.style.height="auto",o("x",t,l),o("y",t,l)):"cover"===e&&t.clientWidth>a.clientWidth||"contain"===e&&t.clientWidth<a.clientWidth?(t.style.top="0",t.style.marginTop="0",o("x",t,l)):"scale-down"!==e&&(t.style.width="100%",t.style.height="auto",t.style.left="0",t.style.marginLeft="0",o("y",t,l))},a=function(t){if(void 0===t)t=document.querySelectorAll("[data-object-fit]");else if(t&&t.nodeName)t=[t];else{if("object"!=typeof t||!t.length||!t[0].nodeName)return!1;t=t}for(var i=0;i<t.length;i++)if(t[i].nodeName){var n=t[i].nodeName.toLowerCase();"img"!==n||e?"video"===n&&(t[i].readyState>0?l(t[i]):t[i].addEventListener("loadedmetadata",function(){l(this)})):t[i].complete?l(t[i]):t[i].addEventListener("load",function(){l(this)})}return!0};document.addEventListener("DOMContentLoaded",function(){a()}),window.addEventListener("resize",function(){a()}),window.objectFitPolyfill=a}}();


/*! 
 * 
 * ================== js/libs/plugins/dialog-polyfill.js =================== 
 **/ 

(function() {

  // nb. This is for IE10 and lower _only_.
  var supportCustomEvent = window.CustomEvent;
  if (!supportCustomEvent || typeof supportCustomEvent === 'object') {
    supportCustomEvent = function CustomEvent(event, x) {
      x = x || {};
      var ev = document.createEvent('CustomEvent');
      ev.initCustomEvent(event, !!x.bubbles, !!x.cancelable, x.detail || null);
      return ev;
    };
    supportCustomEvent.prototype = window.Event.prototype;
  }

  /**
   * @param {Element} el to check for stacking context
   * @return {boolean} whether this el or its parents creates a stacking context
   */
  function createsStackingContext(el) {
    while (el && el !== document.body) {
      var s = window.getComputedStyle(el);
      var invalid = function(k, ok) {
        return !(s[k] === undefined || s[k] === ok);
      }
      if (s.opacity < 1 ||
          invalid('zIndex', 'auto') ||
          invalid('transform', 'none') ||
          invalid('mixBlendMode', 'normal') ||
          invalid('filter', 'none') ||
          invalid('perspective', 'none') ||
          s['isolation'] === 'isolate' ||
          s.position === 'fixed' ||
          s.webkitOverflowScrolling === 'touch') {
        return true;
      }
      el = el.parentElement;
    }
    return false;
  }

  /**
   * Finds the nearest <dialog> from the passed element.
   *
   * @param {Element} el to search from
   * @return {HTMLDialogElement} dialog found
   */
  function findNearestDialog(el) {
    while (el) {
      if (el.localName === 'dialog') {
        return /** @type {HTMLDialogElement} */ (el);
      }
      el = el.parentElement;
    }
    return null;
  }

  /**
   * Blur the specified element, as long as it's not the HTML body element.
   * This works around an IE9/10 bug - blurring the body causes Windows to
   * blur the whole application.
   *
   * @param {Element} el to blur
   */
  function safeBlur(el) {
    if (el && el.blur && el !== document.body) {
      el.blur();
    }
  }

  /**
   * @param {!NodeList} nodeList to search
   * @param {Node} node to find
   * @return {boolean} whether node is inside nodeList
   */
  function inNodeList(nodeList, node) {
    for (var i = 0; i < nodeList.length; ++i) {
      if (nodeList[i] === node) {
        return true;
      }
    }
    return false;
  }

  /**
   * @param {HTMLFormElement} el to check
   * @return {boolean} whether this form has method="dialog"
   */
  function isFormMethodDialog(el) {
    if (!el || !el.hasAttribute('method')) {
      return false;
    }
    return el.getAttribute('method').toLowerCase() === 'dialog';
  }

  /**
   * @param {!HTMLDialogElement} dialog to upgrade
   * @constructor
   */
  function dialogPolyfillInfo(dialog) {
    this.dialog_ = dialog;
    this.replacedStyleTop_ = false;
    this.openAsModal_ = false;

    // Set a11y role. Browsers that support dialog implicitly know this already.
    if (!dialog.hasAttribute('role')) {
      dialog.setAttribute('role', 'dialog');
    }

    dialog.show = this.show.bind(this);
    dialog.showModal = this.showModal.bind(this);
    dialog.close = this.close.bind(this);

    if (!('returnValue' in dialog)) {
      dialog.returnValue = '';
    }

    if ('MutationObserver' in window) {
      var mo = new MutationObserver(this.maybeHideModal.bind(this));
      mo.observe(dialog, {attributes: true, attributeFilter: ['open']});
    } else {
      // IE10 and below support. Note that DOMNodeRemoved etc fire _before_ removal. They also
      // seem to fire even if the element was removed as part of a parent removal. Use the removed
      // events to force downgrade (useful if removed/immediately added).
      var removed = false;
      var cb = function() {
        removed ? this.downgradeModal() : this.maybeHideModal();
        removed = false;
      }.bind(this);
      var timeout;
      var delayModel = function(ev) {
        if (ev.target !== dialog) { return; }  // not for a child element
        var cand = 'DOMNodeRemoved';
        removed |= (ev.type.substr(0, cand.length) === cand);
        window.clearTimeout(timeout);
        timeout = window.setTimeout(cb, 0);
      };
      ['DOMAttrModified', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument'].forEach(function(name) {
        dialog.addEventListener(name, delayModel);
      });
    }
    // Note that the DOM is observed inside DialogManager while any dialog
    // is being displayed as a modal, to catch modal removal from the DOM.

    Object.defineProperty(dialog, 'open', {
      set: this.setOpen.bind(this),
      get: dialog.hasAttribute.bind(dialog, 'open')
    });

    this.backdrop_ = document.createElement('div');
    this.backdrop_.className = 'backdrop';
    this.backdrop_.addEventListener('click', this.backdropClick_.bind(this));
  }

  dialogPolyfillInfo.prototype = {

    get dialog() {
      return this.dialog_;
    },

    /**
     * Maybe remove this dialog from the modal top layer. This is called when
     * a modal dialog may no longer be tenable, e.g., when the dialog is no
     * longer open or is no longer part of the DOM.
     */
    maybeHideModal: function() {
      if (this.dialog_.hasAttribute('open') && document.body.contains(this.dialog_)) { return; }
      this.downgradeModal();
    },

    /**
     * Remove this dialog from the modal top layer, leaving it as a non-modal.
     */
    downgradeModal: function() {
      if (!this.openAsModal_) { return; }
      this.openAsModal_ = false;
      this.dialog_.style.zIndex = '';

      // This won't match the native <dialog> exactly because if the user set top on a centered
      // polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's
      // possible to polyfill this perfectly.
      if (this.replacedStyleTop_) {
        this.dialog_.style.top = '';
        this.replacedStyleTop_ = false;
      }

      // Clear the backdrop and remove from the manager.
      this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_);
      dialogPolyfill.dm.removeDialog(this);
    },

    /**
     * @param {boolean} value whether to open or close this dialog
     */
    setOpen: function(value) {
      if (value) {
        this.dialog_.hasAttribute('open') || this.dialog_.setAttribute('open', '');
      } else {
        this.dialog_.removeAttribute('open');
        this.maybeHideModal();  // nb. redundant with MutationObserver
      }
    },

    /**
     * Handles clicks on the fake .backdrop element, redirecting them as if
     * they were on the dialog itself.
     *
     * @param {!Event} e to redirect
     */
    backdropClick_: function(e) {
      if (!this.dialog_.hasAttribute('tabindex')) {
        // Clicking on the backdrop should move the implicit cursor, even if dialog cannot be
        // focused. Create a fake thing to focus on. If the backdrop was _before_ the dialog, this
        // would not be needed - clicks would move the implicit cursor there.
        var fake = document.createElement('div');
        this.dialog_.insertBefore(fake, this.dialog_.firstChild);
        fake.tabIndex = -1;
        fake.focus();
        this.dialog_.removeChild(fake);
      } else {
        this.dialog_.focus();
      }

      var redirectedEvent = document.createEvent('MouseEvents');
      redirectedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, window,
          e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey,
          e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);
      this.dialog_.dispatchEvent(redirectedEvent);
      e.stopPropagation();
    },

    /**
     * Focuses on the first focusable element within the dialog. This will always blur the current
     * focus, even if nothing within the dialog is found.
     */
    focus_: function() {
      // Find element with `autofocus` attribute, or fall back to the first form/tabindex control.
      var target = this.dialog_.querySelector('[autofocus]:not([disabled])');
      if (!target && this.dialog_.tabIndex >= 0) {
        target = this.dialog_;
      }
      if (!target) {
        // Note that this is 'any focusable area'. This list is probably not exhaustive, but the
        // alternative involves stepping through and trying to focus everything.
        var opts = ['button', 'input', 'keygen', 'select', 'textarea'];
        var query = opts.map(function(el) {
          return el + ':not([disabled])';
        });
        // TODO(samthor): tabindex values that are not numeric are not focusable.
        query.push('[tabindex]:not([disabled]):not([tabindex=""])');  // tabindex != "", not disabled
        target = this.dialog_.querySelector(query.join(', '));
      }
      safeBlur(document.activeElement);
      target && target.focus();
    },

    /**
     * Sets the zIndex for the backdrop and dialog.
     *
     * @param {number} dialogZ
     * @param {number} backdropZ
     */
    updateZIndex: function(dialogZ, backdropZ) {
      if (dialogZ < backdropZ) {
        throw new Error('dialogZ should never be < backdropZ');
      }
      this.dialog_.style.zIndex = dialogZ;
      this.backdrop_.style.zIndex = backdropZ;
    },

    /**
     * Shows the dialog. If the dialog is already open, this does nothing.
     */
    show: function() {
      if (!this.dialog_.open) {
        this.setOpen(true);
        this.focus_();
      }
    },

    /**
     * Show this dialog modally.
     */
    showModal: function() {
      if (this.dialog_.hasAttribute('open')) {
        throw new Error('Failed to execute \'showModal\' on dialog: The element is already open, and therefore cannot be opened modally.');
      }
      if (!document.body.contains(this.dialog_)) {
        throw new Error('Failed to execute \'showModal\' on dialog: The element is not in a Document.');
      }
      if (!dialogPolyfill.dm.pushDialog(this)) {
        throw new Error('Failed to execute \'showModal\' on dialog: There are too many open modal dialogs.');
      }

      if (createsStackingContext(this.dialog_.parentElement)) {
        console.warn('A dialog is being shown inside a stacking context. ' +
            'This may cause it to be unusable. For more information, see this link: ' +
            'https://github.com/GoogleChrome/dialog-polyfill/#stacking-context');
      }

      this.setOpen(true);
      this.openAsModal_ = true;

      // Optionally center vertically, relative to the current viewport.
      if (dialogPolyfill.needsCentering(this.dialog_)) {
        dialogPolyfill.reposition(this.dialog_);
        this.replacedStyleTop_ = true;
      } else {
        this.replacedStyleTop_ = false;
      }

      // Insert backdrop.
      this.dialog_.parentNode.insertBefore(this.backdrop_, this.dialog_.nextSibling);

      // Focus on whatever inside the dialog.
      this.focus_();
    },

    /**
     * Closes this HTMLDialogElement. This is optional vs clearing the open
     * attribute, however this fires a 'close' event.
     *
     * @param {string=} opt_returnValue to use as the returnValue
     */
    close: function(opt_returnValue) {
      if (!this.dialog_.hasAttribute('open')) {
        throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.');
      }
      this.setOpen(false);

      // Leave returnValue untouched in case it was set directly on the element
      if (opt_returnValue !== undefined) {
        this.dialog_.returnValue = opt_returnValue;
      }

      // Triggering "close" event for any attached listeners on the <dialog>.
      var closeEvent = new supportCustomEvent('close', {
        bubbles: false,
        cancelable: false
      });
      this.dialog_.dispatchEvent(closeEvent);
    }

  };

  var dialogPolyfill = {};

  dialogPolyfill.reposition = function(element) {
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2;
    element.style.top = Math.max(scrollTop, topValue) + 'px';
  };

  dialogPolyfill.isInlinePositionSetByStylesheet = function(element) {
    for (var i = 0; i < document.styleSheets.length; ++i) {
      var styleSheet = document.styleSheets[i];
      var cssRules = null;
      // Some browsers throw on cssRules.
      try {
        cssRules = styleSheet.cssRules;
      } catch (e) {}
      if (!cssRules) { continue; }
      for (var j = 0; j < cssRules.length; ++j) {
        var rule = cssRules[j];
        var selectedNodes = null;
        // Ignore errors on invalid selector texts.
        try {
          selectedNodes = document.querySelectorAll(rule.selectorText);
        } catch(e) {}
        if (!selectedNodes || !inNodeList(selectedNodes, element)) {
          continue;
        }
        var cssTop = rule.style.getPropertyValue('top');
        var cssBottom = rule.style.getPropertyValue('bottom');
        if ((cssTop && cssTop !== 'auto') || (cssBottom && cssBottom !== 'auto')) {
          return true;
        }
      }
    }
    return false;
  };

  dialogPolyfill.needsCentering = function(dialog) {
    var computedStyle = window.getComputedStyle(dialog);
    if (computedStyle.position !== 'absolute') {
      return false;
    }

    // We must determine whether the top/bottom specified value is non-auto.  In
    // WebKit/Blink, checking computedStyle.top == 'auto' is sufficient, but
    // Firefox returns the used value. So we do this crazy thing instead: check
    // the inline style and then go through CSS rules.
    if ((dialog.style.top !== 'auto' && dialog.style.top !== '') ||
        (dialog.style.bottom !== 'auto' && dialog.style.bottom !== '')) {
      return false;
    }
    return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog);
  };

  /**
   * @param {!Element} element to force upgrade
   */
  dialogPolyfill.forceRegisterDialog = function(element) {
    if (window.HTMLDialogElement || element.showModal) {
      console.warn('This browser already supports <dialog>, the polyfill ' +
          'may not work correctly', element);
    }
    if (element.localName !== 'dialog') {
      throw new Error('Failed to register dialog: The element is not a dialog.');
    }
    new dialogPolyfillInfo(/** @type {!HTMLDialogElement} */ (element));
  };

  /**
   * @param {!Element} element to upgrade, if necessary
   */
  dialogPolyfill.registerDialog = function(element) {
    if (!element.showModal) {
      dialogPolyfill.forceRegisterDialog(element);
    }
  };

  /**
   * @constructor
   */
  dialogPolyfill.DialogManager = function() {
    /** @type {!Array<!dialogPolyfillInfo>} */
    this.pendingDialogStack = [];

    var checkDOM = this.checkDOM_.bind(this);

    // The overlay is used to simulate how a modal dialog blocks the document.
    // The blocking dialog is positioned on top of the overlay, and the rest of
    // the dialogs on the pending dialog stack are positioned below it. In the
    // actual implementation, the modal dialog stacking is controlled by the
    // top layer, where z-index has no effect.
    this.overlay = document.createElement('div');
    this.overlay.className = '_dialog_overlay';
    this.overlay.addEventListener('click', function(e) {
      this.forwardTab_ = undefined;
      e.stopPropagation();
      checkDOM([]);  // sanity-check DOM
    }.bind(this));

    this.handleKey_ = this.handleKey_.bind(this);
    this.handleFocus_ = this.handleFocus_.bind(this);

    this.zIndexLow_ = 100000;
    this.zIndexHigh_ = 100000 + 150;

    this.forwardTab_ = undefined;

    if ('MutationObserver' in window) {
      this.mo_ = new MutationObserver(function(records) {
        var removed = [];
        records.forEach(function(rec) {
          for (var i = 0, c; c = rec.removedNodes[i]; ++i) {
            if (!(c instanceof Element)) {
              continue;
            } else if (c.localName === 'dialog') {
              removed.push(c);
            }
            removed = removed.concat(c.querySelectorAll('dialog'));
          }
        });
        removed.length && checkDOM(removed);
      });
    }
  };

  /**
   * Called on the first modal dialog being shown. Adds the overlay and related
   * handlers.
   */
  dialogPolyfill.DialogManager.prototype.blockDocument = function() {
    document.documentElement.addEventListener('focus', this.handleFocus_, true);
    document.addEventListener('keydown', this.handleKey_);
    this.mo_ && this.mo_.observe(document, {childList: true, subtree: true});
  };

  /**
   * Called on the first modal dialog being removed, i.e., when no more modal
   * dialogs are visible.
   */
  dialogPolyfill.DialogManager.prototype.unblockDocument = function() {
    document.documentElement.removeEventListener('focus', this.handleFocus_, true);
    document.removeEventListener('keydown', this.handleKey_);
    this.mo_ && this.mo_.disconnect();
  };

  /**
   * Updates the stacking of all known dialogs.
   */
  dialogPolyfill.DialogManager.prototype.updateStacking = function() {
    var zIndex = this.zIndexHigh_;

    for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) {
      dpi.updateZIndex(--zIndex, --zIndex);
      if (i === 0) {
        this.overlay.style.zIndex = --zIndex;
      }
    }

    // Make the overlay a sibling of the dialog itself.
    var last = this.pendingDialogStack[0];
    if (last) {
      var p = last.dialog.parentNode || document.body;
      p.appendChild(this.overlay);
    } else if (this.overlay.parentNode) {
      this.overlay.parentNode.removeChild(this.overlay);
    }
  };

  /**
   * @param {Element} candidate to check if contained or is the top-most modal dialog
   * @return {boolean} whether candidate is contained in top dialog
   */
  dialogPolyfill.DialogManager.prototype.containedByTopDialog_ = function(candidate) {
    while (candidate = findNearestDialog(candidate)) {
      for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) {
        if (dpi.dialog === candidate) {
          return i === 0;  // only valid if top-most
        }
      }
      candidate = candidate.parentElement;
    }
    return false;
  };

  dialogPolyfill.DialogManager.prototype.handleFocus_ = function(event) {
    if (this.containedByTopDialog_(event.target)) { return; }

    event.preventDefault();
    event.stopPropagation();
    safeBlur(/** @type {Element} */ (event.target));

    if (this.forwardTab_ === undefined) { return; }  // move focus only from a tab key

    var dpi = this.pendingDialogStack[0];
    var dialog = dpi.dialog;
    var position = dialog.compareDocumentPosition(event.target);
    if (position & Node.DOCUMENT_POSITION_PRECEDING) {
      if (this.forwardTab_) {  // forward
        dpi.focus_();
      } else {  // backwards
        document.documentElement.focus();
      }
    } else {
      // TODO: Focus after the dialog, is ignored.
    }

    return false;
  };

  dialogPolyfill.DialogManager.prototype.handleKey_ = function(event) {
    this.forwardTab_ = undefined;
    if (event.keyCode === 27) {
      event.preventDefault();
      event.stopPropagation();
      var cancelEvent = new supportCustomEvent('cancel', {
        bubbles: false,
        cancelable: true
      });
      var dpi = this.pendingDialogStack[0];
      if (dpi && dpi.dialog.dispatchEvent(cancelEvent)) {
        dpi.dialog.close();
      }
    } else if (event.keyCode === 9) {
      this.forwardTab_ = !event.shiftKey;
    }
  };

  /**
   * Finds and downgrades any known modal dialogs that are no longer displayed. Dialogs that are
   * removed and immediately readded don't stay modal, they become normal.
   *
   * @param {!Array<!HTMLDialogElement>} removed that have definitely been removed
   */
  dialogPolyfill.DialogManager.prototype.checkDOM_ = function(removed) {
    // This operates on a clone because it may cause it to change. Each change also calls
    // updateStacking, which only actually needs to happen once. But who removes many modal dialogs
    // at a time?!
    var clone = this.pendingDialogStack.slice();
    clone.forEach(function(dpi) {
      if (removed.indexOf(dpi.dialog) !== -1) {
        dpi.downgradeModal();
      } else {
        dpi.maybeHideModal();
      }
    });
  };

  /**
   * @param {!dialogPolyfillInfo} dpi
   * @return {boolean} whether the dialog was allowed
   */
  dialogPolyfill.DialogManager.prototype.pushDialog = function(dpi) {
    var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1;
    if (this.pendingDialogStack.length >= allowed) {
      return false;
    }
    if (this.pendingDialogStack.unshift(dpi) === 1) {
      this.blockDocument();
    }
    this.updateStacking();
    return true;
  };

  /**
   * @param {!dialogPolyfillInfo} dpi
   */
  dialogPolyfill.DialogManager.prototype.removeDialog = function(dpi) {
    var index = this.pendingDialogStack.indexOf(dpi);
    if (index === -1) { return; }

    this.pendingDialogStack.splice(index, 1);
    if (this.pendingDialogStack.length === 0) {
      this.unblockDocument();
    }
    this.updateStacking();
  };

  dialogPolyfill.dm = new dialogPolyfill.DialogManager();
  dialogPolyfill.formSubmitter = null;
  dialogPolyfill.useValue = null;

  /**
   * Installs global handlers, such as click listers and native method overrides. These are needed
   * even if a no dialog is registered, as they deal with <form method="dialog">.
   */
  if (window.HTMLDialogElement === undefined) {

    /**
     * If HTMLFormElement translates method="DIALOG" into 'get', then replace the descriptor with
     * one that returns the correct value.
     */
    var testForm = document.createElement('form');
    testForm.setAttribute('method', 'dialog');
    if (testForm.method !== 'dialog') {
      var methodDescriptor = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, 'method');
      if (methodDescriptor) {
        // nb. Some older iOS and older PhantomJS fail to return the descriptor. Don't do anything
        // and don't bother to update the element.
        var realGet = methodDescriptor.get;
        methodDescriptor.get = function() {
          if (isFormMethodDialog(this)) {
            return 'dialog';
          }
          return realGet.call(this);
        };
        var realSet = methodDescriptor.set;
        methodDescriptor.set = function(v) {
          if (typeof v === 'string' && v.toLowerCase() === 'dialog') {
            return this.setAttribute('method', v);
          }
          return realSet.call(this, v);
        };
        Object.defineProperty(HTMLFormElement.prototype, 'method', methodDescriptor);
      }
    }

    /**
     * Global 'click' handler, to capture the <input type="submit"> or <button> element which has
     * submitted a <form method="dialog">. Needed as Safari and others don't report this inside
     * document.activeElement.
     */
    document.addEventListener('click', function(ev) {
      dialogPolyfill.formSubmitter = null;
      dialogPolyfill.useValue = null;
      if (ev.defaultPrevented) { return; }  // e.g. a submit which prevents default submission

      var target = /** @type {Element} */ (ev.target);
      if (!target || !isFormMethodDialog(target.form)) { return; }

      var valid = (target.type === 'submit' && ['button', 'input'].indexOf(target.localName) > -1);
      if (!valid) {
        if (!(target.localName === 'input' && target.type === 'image')) { return; }
        // this is a <input type="image">, which can submit forms
        dialogPolyfill.useValue = ev.offsetX + ',' + ev.offsetY;
      }

      var dialog = findNearestDialog(target);
      if (!dialog) { return; }

      dialogPolyfill.formSubmitter = target;
    }, false);

    /**
     * Replace the native HTMLFormElement.submit() method, as it won't fire the
     * submit event and give us a chance to respond.
     */
    var nativeFormSubmit = HTMLFormElement.prototype.submit;
    var replacementFormSubmit = function () {
      if (!isFormMethodDialog(this)) {
        return nativeFormSubmit.call(this);
      }
      var dialog = findNearestDialog(this);
      dialog && dialog.close();
    };
    HTMLFormElement.prototype.submit = replacementFormSubmit;

    /**
     * Global form 'dialog' method handler. Closes a dialog correctly on submit
     * and possibly sets its return value.
     */
    document.addEventListener('submit', function(ev) {
      var form = /** @type {HTMLFormElement} */ (ev.target);
      if (!isFormMethodDialog(form)) { return; }
      ev.preventDefault();

      var dialog = findNearestDialog(form);
      if (!dialog) { return; }

      // Forms can only be submitted via .submit() or a click (?), but anyway: sanity-check that
      // the submitter is correct before using its value as .returnValue.
      var s = dialogPolyfill.formSubmitter;
      if (s && s.form === form) {
        dialog.close(dialogPolyfill.useValue || s.value);
      } else {
        dialog.close();
      }
      dialogPolyfill.formSubmitter = null;
    }, true);
  }

  dialogPolyfill['forceRegisterDialog'] = dialogPolyfill.forceRegisterDialog;
  dialogPolyfill['registerDialog'] = dialogPolyfill.registerDialog;

  if (typeof define === 'function' && 'amd' in define) {
    // AMD support
    define(function() { return dialogPolyfill; });
  } else if (typeof module === 'object' && typeof module['exports'] === 'object') {
    // CommonJS support
    module['exports'] = dialogPolyfill;
  } else {
    // all others
    window['dialogPolyfill'] = dialogPolyfill;
  }
})();


/*! 
 * 
 * ================== js/libs/plugins/averta/auxin-jquery.timeline.js =================== 
 **/ 

/*!
 * Auxin Timeline Element
 * @author Averta [www.averta.net]
 */

;(function ( $, window, document, undefined ) {

    "use strict";

        // Create the defaults once
        var pluginName = "AuxinTimeline",
            defaults = {
                layout: 'center',
                responsive: {
                    760: 'left'
                },

                layoutMap: {
                    'left' : 'aux-left',
                    'right': 'aux-right',
                    'middle': 'aux-middle',
                    'center': 'aux-center'
                }

        }, $window = $(window);

        // The actual plugin constructor
        function Plugin ( element, options ) {
                this.element = element;
                this.$element = $(element);
                // future instances of the plugin
                this.settings = $.extend( {}, defaults, options );
                this._defaults = defaults;
                this._name = pluginName;
                this.init();
        }

        // Avoid Plugin.prototype conflicts
        $.extend(Plugin.prototype, {
                init: function () {
                    // read layout from attribute
                    if ( this.$element.data( 'layout' ) !== undefined ) {
                        this.settings.layout = this.$element.data( 'layout' );
                    }

                    $window.on( 'resize', $.proxy( this._onResize, this ) );
                    this._onResize();
                },

                _onResize: function ( e ) {
                    var width = $window.width(),
                        layout = this.settings.layout;

                    for ( var bp in this.settings.responsive ) {
                        if ( width < bp ) {
                            layout = this.settings.responsive[bp];
                        }
                    }

                    this._update( layout );
                },

                _update: function ( newLayout ) {
                    if ( this._currentLayout !== newLayout ) {
                        this._currentLayout = newLayout;

                        // remove old class names
                        for ( var key in this.settings.layoutMap ) {
                            this.$element.removeClass( this.settings.layoutMap[key] );
                        }

                        this.$element.addClass( this.settings.layoutMap[newLayout] );
                    }

                }
        });

        // A really lightweight plugin wrapper around the constructor,
        // preventing against multiple instantiations
        $.fn[ pluginName ] = function ( options ) {
                return this.each(function() {
                        if ( !$.data( this, "plugin_" + pluginName ) ) {
                                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
                        }
                });
        };

})( jQuery, window, document );