/**
 * Functionality to send events to plausible.io analytics.
 * Currently sending property analytics, we could add WL Order Form analytics.
 */

(function($, Drupal, undefined) {
  Drupal.behaviors.plausibleAnalytics =  {
    attach: function(context, settings) {

      function sendPlausibleEvent(eventName, params) {
        if (typeof plausible !== 'undefined') {
          // Per the devs at Plausible, we can add props the the core pageview
          // event. This is the only way to get the actual pageview count from
          // their API. Useing a custom event name and trying to filter by props
          // doesnt work.
          plausible('pageview', {props: params});
        }
      }

      if (!$.isEmptyObject(Drupal.settings.relaAnalyticsPlausible)) {
        $.each(Drupal.settings.relaAnalyticsPlausible, function(eventName, params) {
          sendPlausibleEvent(eventName, params);
          delete Drupal.settings.relaAnalyticsPlausible[eventName];
        });
      }
    }
  }

})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
(function ($) {
  Drupal.behaviors.improved_multi_select = {
    attach: function(context, settings) {
      if (settings.improved_multi_select && settings.improved_multi_select.selectors) {
        var options = settings.improved_multi_select;

        for (var key in options.selectors) {
          var selector = options.selectors[key];

          var $target;
          if (!options.isblacklist || 'select[multiple]' === selector) {
            $target = $(selector, context);
          }
          else {
            $target = $('select[multiple]', context).not(selector);
          }

          $target.once('improvedselect', function() {
            var $select = $(this),
              moveButtons = '',
              improvedselect_id = $select.attr('id'),
              $cloned_select = null,
              cloned_select_id = '';
            if (options.orderable) {
              // If the select is orderable then we clone the original select
              // so that we have the original ordering to use later.
              $cloned_select = $select.clone();
              cloned_select_id = $cloned_select.attr('id');
              cloned_select_id += '-cloned';
              $cloned_select.attr('id', cloned_select_id);
              $cloned_select.appendTo($select.parent()).hide();
              // Move button markup to add to the widget.
              moveButtons = '<span class="move_up" sid="' + $select.attr('id') + '">' + Drupal.checkPlain(options.buttontext_moveup) + '</span>' +
                            '<span class="move_down" sid="' + $select.attr('id') + '">' + Drupal.checkPlain(options.buttontext_movedown) + '</span>';
            }
            $select.parent().append(
              '<div class="improvedselect" sid="' + $select.attr('id') + '" id="improvedselect-' + $select.attr('id') + '">' +
                '<div class="improvedselect-text-wrapper">' +
                  '<input type="text" class="improvedselect_filter" sid="' + $select.attr('id') + '" prev="" />' +
                '</div>' +
                '<ul class="improvedselect_sel"></ul>' +
                '<ul class="improvedselect_all"></ul>' +
                '<div class="improvedselect_control">' +
                  '<span class="add" sid="' + $select.attr('id') + '">' + Drupal.checkPlain(options.buttontext_add) + '</span>' +
                  '<span class="del" sid="' + $select.attr('id') + '">' + Drupal.checkPlain(options.buttontext_del) + '</span>' +
                  '<span class="add_all" sid="' + $select.attr('id') + '">' + Drupal.checkPlain(options.buttontext_addall) + '</span>' +
                  '<span class="del_all" sid="' + $select.attr('id') + '">' + Drupal.checkPlain(options.buttontext_delall) + '</span>' +
                  moveButtons +
                '</div>' +
                '<div class="clear"></div>' +
              '</div>');
            if ($select.find('optgroup').has('option').length > 0) {
              $select.parent().find('.improvedselect').addClass('has_group');
              // Build groups.
              $('#improvedselect-' + improvedselect_id + ' .improvedselect-text-wrapper', context)
                .after('<div class="improvedselect_tabs-wrapper" sid="' + $select.attr('id') + '"><ul class="improvedselect_tabs"></ul></div>');
              $select.find('optgroup').has('option').each(function() {
                $('#improvedselect-' + improvedselect_id + ' .improvedselect_tabs', context)
                  .append('<li><a href="">' + $(this).attr('label') + '</a></li>');
              });
              // Show all groups option.
              $('#improvedselect-' + improvedselect_id + ' .improvedselect_tabs', context)
                .prepend('<li class="all"><a href="">' + Drupal.t('All') + '</a></li>');
              // Select group.
              $('#improvedselect-' + improvedselect_id + ' .improvedselect_tabs li a', context).click(function(e) {
                var $group = $(this),
                  sid = $group.parent().parent().parent().attr('sid');
                $('#improvedselect-' + improvedselect_id + ' .improvedselect_tabs li.selected', context).removeClass('selected').find('a').unwrap();
                $group.wrap('<div>').parents('li').first().addClass('selected');

                // Any existing selections in the all list need to be unselected
                // if they aren't part of the newly selected group.
                if (!$group.hasClass('all')) {
                  $('#improvedselect-' + improvedselect_id + ' .improvedselect_all li.selected[group!="' + $group.text() + '"]', context).removeClass('selected');
                }

                // Clear the filter if we have to.
                if (options.groupresetfilter) {
                  // Clear filter box.
                  $('#improvedselect-' + improvedselect_id + ' .improvedselect_filter', context).val('');
                }
                // Force re-filtering.
                $('#improvedselect-' + improvedselect_id + ' .improvedselect_filter', context).attr('prev', '');
                // Re-filtering will handle the rest.
                improvedselectFilter(sid, options, context);
                e.preventDefault();
              });
              // Select all to begin.
              $('#improvedselect-' + improvedselect_id + ' .improvedselect_tabs li.all a', context).click();
            }

            $select.find('option, optgroup').each(function() {
              var $opt = $(this),
                group = '';
              if ($opt[0].tagName == 'OPTGROUP') {
                if ($opt.has('option').length) {
                  $('#improvedselect-'+ improvedselect_id +' .improvedselect_all', context)
                    .append('<li isgroup="isgroup" so="---' + $opt.attr('label') + '---">--- '+ $opt.attr('label') +' ---</li>');
                }
              }
              else {
                group = $opt.parent("optgroup").attr("label");
                if (group) {
                  group = ' group="' + group + '"';
                }
                if ($opt.attr('value') != "_none") {
                  if ($opt.attr('selected')) {
                    $('#improvedselect-' + improvedselect_id + ' .improvedselect_sel', context)
                      .append('<li so="' + $opt.attr('value') + '"' + group + '>' + $opt.html() + '</li>');
                  }
                  else {
                    $('#improvedselect-' + improvedselect_id + ' .improvedselect_all', context)
                      .append('<li so="' + $opt.attr('value') + '"' + group + '>' + $opt.html() + '</li>');
                  }
                }
              }
            });
            $('#improvedselect-'+ improvedselect_id + ' .improvedselect_sel li, #improvedselect-' + improvedselect_id + ' .improvedselect_all li[isgroup!="isgroup"]', context).click(function() {
              $(this).toggleClass('selected');
            });
            $select.hide();
            // Double click feature request.
            $('#improvedselect-'+ improvedselect_id + ' .improvedselect_sel li, #improvedselect-' + improvedselect_id + ' .improvedselect_all li[isgroup!="isgroup"]', context).dblclick(function() {
              // Store selected items.
              var selected = $(this).parent().find('li.selected'),
                current_class = $(this).parent().attr('class');
              // Add item.
              if (current_class == 'improvedselect_all') {
                $(this).parent().find('li.selected').removeClass('selected');
                $(this).addClass('selected');
                $(this).parent().parent().find('.add').click();
              }
              // Remove item.
              else {
                $(this).parent().find('li.selected').removeClass('selected');
                $(this).addClass('selected');
                $(this).parent().parent().find('.del').click();
              }
              // Restore selected items.
              if (selected.length) {
                for (var k = 0; k < selected.length; k++) {
                  if ($(selected[k]).parent().attr('class') == current_class) {
                    $(selected[k]).addClass('selected');
                  }
                }
              }
            });

            // Set the height of the select fields based on the height of the
            // parent, otherwise it can end up with a lot of wasted space.
            $('.improvedselect_sel, .improvedselect_all').each(function() {
              if ($(this).parent().height() > 0 ) {
                $(this).height($(this).parent().height() - 35);
              }
              // @todo: Element is hidden - we can't detect its height.
              else {}
            });
          });
        }

        $('.improvedselect_filter', context).bind('input', function() {
          improvedselectFilter($(this).attr('sid'), options, context);
        });

        // Add selected items.
        $('.improvedselect .add', context).click(function() {
          var sid = $(this).attr('sid');
          $('#improvedselect-' + sid + ' .improvedselect_all .selected', context).each(function() {
            $opt = $(this);
            $opt.removeClass('selected');
            improvedselectUpdateGroupVisibility($opt, 1);
            $('#improvedselect-' + sid + ' .improvedselect_sel', context).append($opt);
          });
          improvedselectUpdate(sid, context);
        });

        // Remove selected items.
        $('.improvedselect .del', context).click(function() {
          var sid = $(this).attr('sid');
          $('#improvedselect-' + sid + ' .improvedselect_sel .selected', context).each(function() {
            $opt = $(this);
            $opt.removeClass('selected');
            $('#improvedselect-' + sid + ' .improvedselect_all', context).append($opt);
            improvedselectUpdateGroupVisibility($opt, 0);
          });
          // Force re-filtering.
          $('#improvedselect-' + sid + ' .improvedselect_filter', context).attr('prev', '');
          // Re-filtering will handle the rest.
          improvedselectFilter(sid, options, context);
          improvedselectUpdate(sid, context);
        });

        // Add all items.
        $('.improvedselect .add_all', context).click(function() {
          var sid = $(this).attr('sid');
          $('#improvedselect-' + sid + ' .improvedselect_all li[isgroup!=isgroup]', context).each(function() {
            $opt = $(this);
            if ($opt.css('display') != 'none') {
              $opt.removeClass('selected');
              improvedselectUpdateGroupVisibility($opt, 1);
              $('#improvedselect-' + sid + ' .improvedselect_sel', context).append($opt);
            }
          });
          improvedselectUpdate(sid, context);
        });

        // Remove all items.
        $('.improvedselect .del_all', context).click(function() {
          var sid = $(this).attr('sid');
          $('#improvedselect-' + sid + ' .improvedselect_sel li', context).each(function() {
            $opt = $(this);
            $opt.removeClass('selected');
            $('#improvedselect-' + sid + ' .improvedselect_all', context).append($opt);
            improvedselectUpdateGroupVisibility($opt, 0);
          });
          // Force re-filtering.
          $('#improvedselect-' + sid + ' .improvedselect_filter', context).attr('prev', '');
          // Re-filtering will handle the rest.
          improvedselectFilter(sid, options, context);
          improvedselectUpdate(sid, context);
        });

        // Move selected items up.
        $('.improvedselect .move_up', context).click(function() {
          var sid = $(this).attr('sid');
          $('#improvedselect-' + sid + ' .improvedselect_sel .selected', context).each(function() {
            var $selected = $(this);
            // Don't move selected items past other selected items or there will
            // be problems when moving multiple items at once.
            $selected.prev(':not(.selected)').before($selected);
          });
          improvedselectUpdate(sid, context);
        });

        // Move selected items down.
        $('.improvedselect .move_down', context).click(function() {
          var sid = $(this).attr('sid');
          // Run through the selections in reverse, otherwise problems occur
          // when moving multiple items at once.
          $($('#improvedselect-' + sid + ' .improvedselect_sel .selected', context).get().reverse()).each(function() {
            var $selected = $(this);
            // Don't move selected items past other selected items or there will
            // be problems when moving multiple items at once.
            $selected.next(':not(.selected)').after($selected);
          });
          improvedselectUpdate(sid, context);
        });
        // Let other scripts know improvedSelect was initialized
        $.event.trigger('improvedMultiSelectInitialized', [$(this)]);
      }
      // Let other scripts know improvedSelect has been attached
      $.event.trigger('improvedMultiSelectAttached');
    }
  };

  /**
   * Filter the all options list.
   */
  function improvedselectFilter(sid, options, context) {
    $filter = $('#improvedselect-' + sid + ' .improvedselect_filter', context);
    // Get current selected group.
    var $selectedGroup = $('#improvedselect-' + sid + ' .improvedselect_tabs li.selected:not(.all) a', context),
      text = $filter.val(),
      pattern,
      regex,
      words;

    if (text.length && text != $filter.attr('prev')) {
      $filter.attr('prev', text);
      switch (options.filtertype) {
        case 'partial':
        default:
          pattern = text;
          break;
        case 'exact':
          pattern = '^' + text + '$';
          break;
        case 'anywords':
          words = text.split(' ');
          pattern = '';
          for (var i = 0; i < words.length; i++) {
            if (words[i]) {
              pattern += (pattern) ? '|\\b' + words[i] + '\\b' : '\\b' + words[i] + '\\b';
            }
          }
          break;
        case 'anywords_partial':
          words = text.split(' ');
          pattern = '';
          for (var i = 0; i < words.length; i++) {
            if (words[i]) {
              pattern += (pattern) ? '|' + words[i] + '' : words[i];
            }
          }
          break;
        case 'allwords':
          words = text.split(' ');
          pattern = '^';
          // Add a lookahead for each individual word.
          // Lookahead is used because the words can match in any order
          // so this makes it simpler and faster.
          for (var i = 0; i < words.length; i++) {
            if (words[i]) {
              pattern += '(?=.*?\\b' + words[i] + '\\b)';
            }
          }
          break;
        case 'allwords_partial':
          words = text.split(' ');
          pattern = '^';
          // Add a lookahead for each individual word.
          // Lookahead is used because the words can match in any order
          // so this makes it simpler and faster.
          for (var i = 0; i < words.length; i++) {
            if (words[i]) {
              pattern += '(?=.*?' + words[i] + ')';
            }
          }
          break;
      }

      regex = new RegExp(pattern,'i');
      $('#improvedselect-' + sid + ' .improvedselect_all li', context).each(function() {
        $opt = $(this);
        if ($opt.attr('isgroup') != 'isgroup') {
          var str = $opt.text();
          if (str.match(regex) && (!$selectedGroup.length || $selectedGroup.text() == $opt.attr('group'))) {
            $opt.show();
            if ($opt.attr('group')) {
              // If a group is selected we don't need to show groups.
              if (!$selectedGroup.length) {
                $opt.siblings('li[isgroup="isgroup"][so="---' + $opt.attr('group') + '---"]').show();
              }
              else {
                $opt.siblings('li[isgroup="isgroup"][so="---' + $opt.attr('group') + '---"]').hide();
              }
            }
          }
          else {
            $opt.hide();
            if ($opt.attr('group')) {
              if ($opt.siblings('li[isgroup!="isgroup"][group="' + $opt.attr('group') + '"]:visible').length == 0) {
                $opt.siblings('li[isgroup="isgroup"][so="---' + $opt.attr('group') + '---"]').hide();
              }
            }
          }
        }
      });
    }
    else {
      if (!text.length) {
        $filter.attr('prev', '');
      }
      $('#improvedselect-' + sid + ' .improvedselect_all li', context).each(function() {
        var $opt = $(this);
        if ($opt.attr('isgroup') != 'isgroup') {
          if (!$selectedGroup.length || $selectedGroup.text() == $opt.attr('group')) {
            $opt.show();
          }
          else {
            $opt.hide();
          }
          improvedselectUpdateGroupVisibility($opt, 0);
        }
      });
    }
  }

  /**
   * Update the visibility of an option's group.
   *
   * @param $opt
   *   A jQuery object of a select option.
   * @param numItems
   *   How many items should be considered an empty group. Generally zero or one
   *   depending on if an item has been or is going to be removed or added.
   */
  function improvedselectUpdateGroupVisibility($opt, numItems) {
    var $selectedGroup = $opt.parents('.improvedselect').first().find('.improvedselect_tabs li.selected:not(.all) a');

    // Don't show groups if a group is selected.
    if ($opt.parent().children('li[isgroup!="isgroup"][group="' + $opt.attr('group') + '"]:visible').length <= numItems || $selectedGroup.length) {
      $opt.siblings('li[isgroup="isgroup"][so="---' + $opt.attr('group') + '---"]').hide();
    }
    else {
      $opt.siblings('li[isgroup="isgroup"][so="---' + $opt.attr('group') + '---"]').show();
    }
  }

  function improvedselectUpdate(sid, context) {
    // If we have sorting enabled, make sure we have the results sorted.
    var $select = $('#' + sid),
      $cloned_select = $('#' + sid + '-cloned');

    if ($cloned_select.length) {
      $select.find('option, optgroup').remove();
      $('#improvedselect-' + sid + ' .improvedselect_sel li', context).each(function() {
        var $li = $(this);
        $select.append($('<option></option>').attr('value', $li.attr('so')).prop('selected', true).text($li.text()));
      });
      // Now that the select has the options in the correct order, use the
      // cloned select for resetting the ul values.
      $select = $cloned_select;
    }
    else {
      $select.find('option:selected').prop('selected', false);
      $('#improvedselect-' + sid + ' .improvedselect_sel li', context).each(function() {
        $('#' + sid + ' [value="' + $(this).attr('so') + '"]', context).prop('selected', true);
      });
    }

    $select.find('option, optgroup').each(function() {
      $opt = $(this);
      if ($opt[0].tagName == 'OPTGROUP') {
        if ($opt.has('option').length) {
          $('#improvedselect-' + sid + ' .improvedselect_all', context).append($('#improvedselect-' + sid + ' .improvedselect_all [so="---' + $opt.attr('label') + '---"]', context));
        }
      }
      else {
        // When using reordering, the options will be from the cloned select,
        // meaning that there will be none selected, which means that items
        // in the selected list will not be reordered, which is what we want.
        if ($opt.attr("selected")) {
          $('#improvedselect-' + sid + ' .improvedselect_sel', context).append($('#improvedselect-' + sid + ' .improvedselect_sel [so="' + $opt.attr('value') + '"]', context));
        }
        else {
          $('#improvedselect-' + sid + ' .improvedselect_all', context).append($('#improvedselect-' + sid + ' .improvedselect_all [so="' + $opt.attr('value') + '"]', context));
        }
      }
    });
    // Don't use the $select variable here as it might be the clone.
    // Tell the ajax system the select has changed.
    $('#' + sid, context).trigger('change');
  }

})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
/*!
Waypoints - 3.1.1
Copyright © 2011-2015 Caleb Troughton
Licensed under the MIT license.
https://github.com/imakewebthings/waypoints/blog/master/licenses.txt
*/
!function(){"use strict";function t(o){if(!o)throw new Error("No options passed to Waypoint constructor");if(!o.element)throw new Error("No element option passed to Waypoint constructor");if(!o.handler)throw new Error("No handler option passed to Waypoint constructor");this.key="waypoint-"+e,this.options=t.Adapter.extend({},t.defaults,o),this.element=this.options.element,this.adapter=new t.Adapter(this.element),this.callback=o.handler,this.axis=this.options.horizontal?"horizontal":"vertical",this.enabled=this.options.enabled,this.triggerPoint=null,this.group=t.Group.findOrCreate({name:this.options.group,axis:this.axis}),this.context=t.Context.findOrCreateByElement(this.options.context),t.offsetAliases[this.options.offset]&&(this.options.offset=t.offsetAliases[this.options.offset]),this.group.add(this),this.context.add(this),i[this.key]=this,e+=1}var e=0,i={};t.prototype.queueTrigger=function(t){this.group.queueTrigger(this,t)},t.prototype.trigger=function(t){this.enabled&&this.callback&&this.callback.apply(this,t)},t.prototype.destroy=function(){this.context.remove(this),this.group.remove(this),delete i[this.key]},t.prototype.disable=function(){return this.enabled=!1,this},t.prototype.enable=function(){return this.context.refresh(),this.enabled=!0,this},t.prototype.next=function(){return this.group.next(this)},t.prototype.previous=function(){return this.group.previous(this)},t.invokeAll=function(t){var e=[];for(var o in i)e.push(i[o]);for(var n=0,r=e.length;r>n;n++)e[n][t]()},t.destroyAll=function(){t.invokeAll("destroy")},t.disableAll=function(){t.invokeAll("disable")},t.enableAll=function(){t.invokeAll("enable")},t.refreshAll=function(){t.Context.refreshAll()},t.viewportHeight=function(){return window.innerHeight||document.documentElement.clientHeight},t.viewportWidth=function(){return document.documentElement.clientWidth},t.adapters=[],t.defaults={context:window,continuous:!0,enabled:!0,group:"default",horizontal:!1,offset:0},t.offsetAliases={"bottom-in-view":function(){return this.context.innerHeight()-this.adapter.outerHeight()},"right-in-view":function(){return this.context.innerWidth()-this.adapter.outerWidth()}},window.Waypoint=t}(),function(){"use strict";function t(t){window.setTimeout(t,1e3/60)}function e(t){this.element=t,this.Adapter=n.Adapter,this.adapter=new this.Adapter(t),this.key="waypoint-context-"+i,this.didScroll=!1,this.didResize=!1,this.oldScroll={x:this.adapter.scrollLeft(),y:this.adapter.scrollTop()},this.waypoints={vertical:{},horizontal:{}},t.waypointContextKey=this.key,o[t.waypointContextKey]=this,i+=1,this.createThrottledScrollHandler(),this.createThrottledResizeHandler()}var i=0,o={},n=window.Waypoint,r=window.onload;e.prototype.add=function(t){var e=t.options.horizontal?"horizontal":"vertical";this.waypoints[e][t.key]=t,this.refresh()},e.prototype.checkEmpty=function(){var t=this.Adapter.isEmptyObject(this.waypoints.horizontal),e=this.Adapter.isEmptyObject(this.waypoints.vertical);t&&e&&(this.adapter.off(".waypoints"),delete o[this.key])},e.prototype.createThrottledResizeHandler=function(){function t(){e.handleResize(),e.didResize=!1}var e=this;this.adapter.on("resize.waypoints",function(){e.didResize||(e.didResize=!0,n.requestAnimationFrame(t))})},e.prototype.createThrottledScrollHandler=function(){function t(){e.handleScroll(),e.didScroll=!1}var e=this;this.adapter.on("scroll.waypoints",function(){(!e.didScroll||n.isTouch)&&(e.didScroll=!0,n.requestAnimationFrame(t))})},e.prototype.handleResize=function(){n.Context.refreshAll()},e.prototype.handleScroll=function(){var t={},e={horizontal:{newScroll:this.adapter.scrollLeft(),oldScroll:this.oldScroll.x,forward:"right",backward:"left"},vertical:{newScroll:this.adapter.scrollTop(),oldScroll:this.oldScroll.y,forward:"down",backward:"up"}};for(var i in e){var o=e[i],n=o.newScroll>o.oldScroll,r=n?o.forward:o.backward;for(var s in this.waypoints[i]){var a=this.waypoints[i][s],l=o.oldScroll<a.triggerPoint,h=o.newScroll>=a.triggerPoint,p=l&&h,u=!l&&!h;(p||u)&&(a.queueTrigger(r),t[a.group.id]=a.group)}}for(var c in t)t[c].flushTriggers();this.oldScroll={x:e.horizontal.newScroll,y:e.vertical.newScroll}},e.prototype.innerHeight=function(){return this.element==this.element.window?n.viewportHeight():this.adapter.innerHeight()},e.prototype.remove=function(t){delete this.waypoints[t.axis][t.key],this.checkEmpty()},e.prototype.innerWidth=function(){return this.element==this.element.window?n.viewportWidth():this.adapter.innerWidth()},e.prototype.destroy=function(){var t=[];for(var e in this.waypoints)for(var i in this.waypoints[e])t.push(this.waypoints[e][i]);for(var o=0,n=t.length;n>o;o++)t[o].destroy()},e.prototype.refresh=function(){var t,e=this.element==this.element.window,i=this.adapter.offset(),o={};this.handleScroll(),t={horizontal:{contextOffset:e?0:i.left,contextScroll:e?0:this.oldScroll.x,contextDimension:this.innerWidth(),oldScroll:this.oldScroll.x,forward:"right",backward:"left",offsetProp:"left"},vertical:{contextOffset:e?0:i.top,contextScroll:e?0:this.oldScroll.y,contextDimension:this.innerHeight(),oldScroll:this.oldScroll.y,forward:"down",backward:"up",offsetProp:"top"}};for(var n in t){var r=t[n];for(var s in this.waypoints[n]){var a,l,h,p,u,c=this.waypoints[n][s],d=c.options.offset,f=c.triggerPoint,w=0,y=null==f;c.element!==c.element.window&&(w=c.adapter.offset()[r.offsetProp]),"function"==typeof d?d=d.apply(c):"string"==typeof d&&(d=parseFloat(d),c.options.offset.indexOf("%")>-1&&(d=Math.ceil(r.contextDimension*d/100))),a=r.contextScroll-r.contextOffset,c.triggerPoint=w+a-d,l=f<r.oldScroll,h=c.triggerPoint>=r.oldScroll,p=l&&h,u=!l&&!h,!y&&p?(c.queueTrigger(r.backward),o[c.group.id]=c.group):!y&&u?(c.queueTrigger(r.forward),o[c.group.id]=c.group):y&&r.oldScroll>=c.triggerPoint&&(c.queueTrigger(r.forward),o[c.group.id]=c.group)}}for(var g in o)o[g].flushTriggers();return this},e.findOrCreateByElement=function(t){return e.findByElement(t)||new e(t)},e.refreshAll=function(){for(var t in o)o[t].refresh()},e.findByElement=function(t){return o[t.waypointContextKey]},window.onload=function(){r&&r(),e.refreshAll()},n.requestAnimationFrame=function(e){var i=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||t;i.call(window,e)},n.Context=e}(),function(){"use strict";function t(t,e){return t.triggerPoint-e.triggerPoint}function e(t,e){return e.triggerPoint-t.triggerPoint}function i(t){this.name=t.name,this.axis=t.axis,this.id=this.name+"-"+this.axis,this.waypoints=[],this.clearTriggerQueues(),o[this.axis][this.name]=this}var o={vertical:{},horizontal:{}},n=window.Waypoint;i.prototype.add=function(t){this.waypoints.push(t)},i.prototype.clearTriggerQueues=function(){this.triggerQueues={up:[],down:[],left:[],right:[]}},i.prototype.flushTriggers=function(){for(var i in this.triggerQueues){var o=this.triggerQueues[i],n="up"===i||"left"===i;o.sort(n?e:t);for(var r=0,s=o.length;s>r;r+=1){var a=o[r];(a.options.continuous||r===o.length-1)&&a.trigger([i])}}this.clearTriggerQueues()},i.prototype.next=function(e){this.waypoints.sort(t);var i=n.Adapter.inArray(e,this.waypoints),o=i===this.waypoints.length-1;return o?null:this.waypoints[i+1]},i.prototype.previous=function(e){this.waypoints.sort(t);var i=n.Adapter.inArray(e,this.waypoints);return i?this.waypoints[i-1]:null},i.prototype.queueTrigger=function(t,e){this.triggerQueues[e].push(t)},i.prototype.remove=function(t){var e=n.Adapter.inArray(t,this.waypoints);e>-1&&this.waypoints.splice(e,1)},i.prototype.first=function(){return this.waypoints[0]},i.prototype.last=function(){return this.waypoints[this.waypoints.length-1]},i.findOrCreate=function(t){return o[t.axis][t.name]||new i(t)},n.Group=i}(),function(){"use strict";function t(t){this.$element=e(t)}var e=window.jQuery,i=window.Waypoint;e.each(["innerHeight","innerWidth","off","offset","on","outerHeight","outerWidth","scrollLeft","scrollTop"],function(e,i){t.prototype[i]=function(){var t=Array.prototype.slice.call(arguments);return this.$element[i].apply(this.$element,t)}}),e.each(["extend","inArray","isEmptyObject"],function(i,o){t[o]=e[o]}),i.adapters.push({name:"jquery",Adapter:t}),i.Adapter=t}(),function(){"use strict";function t(t){return function(){var i=[],o=arguments[0];return t.isFunction(arguments[0])&&(o=t.extend({},arguments[1]),o.handler=arguments[0]),this.each(function(){var n=t.extend({},o,{element:this});"string"==typeof n.context&&(n.context=t(this).closest(n.context)[0]),i.push(new e(n))}),i}}var e=window.Waypoint;window.jQuery&&(window.jQuery.fn.waypoint=t(window.jQuery)),window.Zepto&&(window.Zepto.fn.waypoint=t(window.Zepto))}();
;/*})'"*/;/*})'"*/
/**
 * @file
 *
 * Implement a modal form.
 *
 * @see modal.inc for documentation.
 *
 * This javascript relies on the CTools ajax responder.
 */

(function ($) {
  // Make sure our objects are defined.
  Drupal.CTools = Drupal.CTools || {};
  Drupal.CTools.Modal = Drupal.CTools.Modal || {};

  /**
   * Display the modal
   *
   * @todo -- document the settings.
   */
  Drupal.CTools.Modal.show = function(choice) {
    var opts = {};

    if (choice && typeof choice == 'string' && Drupal.settings[choice]) {
      // This notation guarantees we are actually copying it.
      $.extend(true, opts, Drupal.settings[choice]);
    }
    else if (choice) {
      $.extend(true, opts, choice);
    }

    var defaults = {
      modalTheme: 'CToolsModalDialog',
      throbberTheme: 'CToolsModalThrobber',
      animation: 'show',
      animationSpeed: 'fast',
      modalSize: {
        type: 'scale',
        width: .8,
        height: .8,
        addWidth: 0,
        addHeight: 0,
        // How much to remove from the inner content to make space for the
        // theming.
        contentRight: 25,
        contentBottom: 45
      },
      modalOptions: {
        opacity: .55,
        background: '#fff'
      },
      modalClass: 'default'
    };

    var settings = {};
    $.extend(true, settings, defaults, Drupal.settings.CToolsModal, opts);

    if (Drupal.CTools.Modal.currentSettings && Drupal.CTools.Modal.currentSettings != settings) {
      Drupal.CTools.Modal.modal.remove();
      Drupal.CTools.Modal.modal = null;
    }

    Drupal.CTools.Modal.currentSettings = settings;

    var resize = function(e) {
      // When creating the modal, it actually exists only in a theoretical
      // place that is not in the DOM. But once the modal exists, it is in the
      // DOM so the context must be set appropriately.
      var context = e ? document : Drupal.CTools.Modal.modal;

      if (Drupal.CTools.Modal.currentSettings.modalSize.type == 'scale') {
        var width = $(window).width() * Drupal.CTools.Modal.currentSettings.modalSize.width;
        var height = $(window).height() * Drupal.CTools.Modal.currentSettings.modalSize.height;
      }
      else {
        var width = Drupal.CTools.Modal.currentSettings.modalSize.width;
        var height = Drupal.CTools.Modal.currentSettings.modalSize.height;
      }

      // Use the additionol pixels for creating the width and height.
      $('div.ctools-modal-content', context).css({
        'width': width + Drupal.CTools.Modal.currentSettings.modalSize.addWidth + 'px',
        'height': height + Drupal.CTools.Modal.currentSettings.modalSize.addHeight + 'px'
      });
      $('div.ctools-modal-content .modal-content', context).css({
        'width': (width - Drupal.CTools.Modal.currentSettings.modalSize.contentRight) + 'px',
        'height': (height - Drupal.CTools.Modal.currentSettings.modalSize.contentBottom) + 'px'
      });
    };

    if (!Drupal.CTools.Modal.modal) {
      Drupal.CTools.Modal.modal = $(Drupal.theme(settings.modalTheme));
      if (settings.modalSize.type == 'scale') {
        $(window).bind('resize', resize);
      }
    }

    resize();

    $('span.modal-title', Drupal.CTools.Modal.modal).html(Drupal.CTools.Modal.currentSettings.loadingText);
    Drupal.CTools.Modal.modalContent(Drupal.CTools.Modal.modal, settings.modalOptions, settings.animation, settings.animationSpeed, settings.modalClass);
    $('#modalContent .modal-content').html(Drupal.theme(settings.throbberTheme)).addClass('ctools-modal-loading');

    // Position autocomplete results based on the scroll position of the modal.
    $('#modalContent .modal-content').delegate('input.form-autocomplete', 'keyup', function() {
      $('#autocomplete').css('top', $(this).position().top + $(this).outerHeight() + $(this).offsetParent().filter('#modal-content').scrollTop());
    });
  };

  /**
   * Hide the modal
   */
  Drupal.CTools.Modal.dismiss = function() {
    if (Drupal.CTools.Modal.modal) {
      Drupal.CTools.Modal.unmodalContent(Drupal.CTools.Modal.modal);
    }
  };

  /**
   * Provide the HTML to create the modal dialog.
   */
  Drupal.theme.prototype.CToolsModalDialog = function () {
    var html = '';
    html += '<div id="ctools-modal">';
    html += '  <div class="ctools-modal-content">'; // panels-modal-content
    html += '    <div class="modal-header">';
    html += '      <a class="close" href="#">';
    html +=          Drupal.CTools.Modal.currentSettings.closeText + Drupal.CTools.Modal.currentSettings.closeImage;
    html += '      </a>';
    html += '      <span id="modal-title" class="modal-title">&nbsp;</span>';
    html += '    </div>';
    html += '    <div id="modal-content" class="modal-content">';
    html += '    </div>';
    html += '  </div>';
    html += '</div>';

    return html;
  };

  /**
   * Provide the HTML to create the throbber.
   */
  Drupal.theme.prototype.CToolsModalThrobber = function () {
    var html = '';
    html += '<div id="modal-throbber">';
    html += '  <div class="modal-throbber-wrapper">';
    html +=      Drupal.CTools.Modal.currentSettings.throbber;
    html += '  </div>';
    html += '</div>';

    return html;
  };

  /**
   * Figure out what settings string to use to display a modal.
   */
  Drupal.CTools.Modal.getSettings = function (object) {
    var match = $(object).attr('class').match(/ctools-modal-(\S+)/);
    if (match) {
      return match[1];
    }
  };

  /**
   * Click function for modals that can be cached.
   */
  Drupal.CTools.Modal.clickAjaxCacheLink = function () {
    Drupal.CTools.Modal.show(Drupal.CTools.Modal.getSettings(this));
    return Drupal.CTools.AJAX.clickAJAXCacheLink.apply(this);
  };

  /**
   * Handler to prepare the modal for the response
   */
  Drupal.CTools.Modal.clickAjaxLink = function () {
    Drupal.CTools.Modal.show(Drupal.CTools.Modal.getSettings(this));
    return false;
  };

  /**
   * Submit responder to do an AJAX submit on all modal forms.
   */
  Drupal.CTools.Modal.submitAjaxForm = function(e) {
    var $form = $(this);
    var url = $form.attr('action');

    setTimeout(function() { Drupal.CTools.AJAX.ajaxSubmit($form, url); }, 1);
    return false;
  };

  /**
   * Bind links that will open modals to the appropriate function.
   */
  Drupal.behaviors.ZZCToolsModal = {
    attach: function(context) {
      // Bind links
      // Note that doing so in this order means that the two classes can be
      // used together safely.
      /*
       * @todo remimplement the warm caching feature
       $('a.ctools-use-modal-cache', context).once('ctools-use-modal', function() {
         $(this).click(Drupal.CTools.Modal.clickAjaxCacheLink);
         Drupal.CTools.AJAX.warmCache.apply(this);
       });
        */

      $('area.ctools-use-modal, a.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);
        // Create a drupal ajax object
        var element_settings = {};
        if ($this.attr('href')) {
          element_settings.url = $this.attr('href');
          element_settings.event = 'click';
          element_settings.progress = { type: 'throbber' };
        }
        var base = $this.attr('href');
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
      });

      // Bind buttons
      $('input.ctools-use-modal, button.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);
        var button = this;
        var element_settings = {};

        // AJAX submits specified in this manner automatically submit to the
        // normal form action.
        element_settings.url = Drupal.CTools.Modal.findURL(this);
        if (element_settings.url == '') {
          element_settings.url = $(this).closest('form').attr('action');
        }
        element_settings.event = 'click';
        element_settings.setClick = true;

        var base = $this.attr('id');
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);

        // Make sure changes to settings are reflected in the URL.
        $('.' + $(button).attr('id') + '-url').change(function() {
          Drupal.ajax[base].options.url = Drupal.CTools.Modal.findURL(button);
        });
      });

      // Bind our custom event to the form submit
      $('#modal-content form', context).once('ctools-use-modal', function() {
        var $this = $(this);
        var element_settings = {};

        element_settings.url = $this.attr('action');
        element_settings.event = 'submit';
        element_settings.progress = { 'type': 'throbber' };
        var base = $this.attr('id');

        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
        Drupal.ajax[base].form = $this;

        $('input[type=submit], button', this).click(function(event) {
          Drupal.ajax[base].element = this;
          this.form.clk = this;
          // Stop autocomplete from submitting.
          if (Drupal.autocompleteSubmit && !Drupal.autocompleteSubmit()) {
            return false;
          }
          // An empty event means we were triggered via .click() and
          // in jquery 1.4 this won't trigger a submit.
          // We also have to check jQuery version to prevent
          // IE8 + jQuery 1.4.4 to break on other events
          // bound to the submit button.
          if (jQuery.fn.jquery.substr(0, 3) === '1.4' && typeof event.bubbles === "undefined") {
            $(this.form).trigger('submit');
            return false;
          }
        });
      });

      // Bind a click handler to allow elements with the 'ctools-close-modal'
      // class to close the modal.
      $('.ctools-close-modal', context).once('ctools-close-modal')
        .click(function() {
          Drupal.CTools.Modal.dismiss();
          return false;
        });
    }
  };

  // The following are implementations of AJAX responder commands.

  /**
   * AJAX responder command to place HTML within the modal.
   */
  Drupal.CTools.Modal.modal_display = function(ajax, response, status) {
    var settings = response.settings || ajax.settings || Drupal.settings;
    // If the modal does not exist yet, create it.
    if ($('#modalContent').length == 0) {
      Drupal.CTools.Modal.show(Drupal.CTools.Modal.getSettings(ajax.element));
    }
    // If the modal exists run detachBehaviors before removing existing content.
    else {
      Drupal.detachBehaviors($('#modalContent'), settings, 'unload');
    }
    $('#modal-title').html(response.title);
    // Simulate an actual page load by scrolling to the top after adding the
    // content. This is helpful for allowing users to see error messages at the
    // top of a form, etc.
    $('#modal-content').html(response.output).scrollTop(0);
    $(document).trigger('CToolsAttachBehaviors', $('#modalContent'));

    // Attach behaviors within a modal dialog.
    Drupal.attachBehaviors($('#modalContent'), settings);

    if ($('#modal-content').hasClass('ctools-modal-loading')) {
      $('#modal-content').removeClass('ctools-modal-loading');
    }
    else {
      // If the modal was already shown, and we are simply replacing its
      // content, then focus on the first focusable element in the modal.
      // (When first showing the modal, focus will be placed on the close
      // button by the show() function called above.)
      $('#modal-content :focusable:first').focus();
    }
  };

  /**
   * AJAX responder command to dismiss the modal.
   */
  Drupal.CTools.Modal.modal_dismiss = function(command) {
    Drupal.CTools.Modal.dismiss();
    $('link.ctools-temporary-css').remove();
  };

  /**
   * Display loading
   */
  //Drupal.CTools.AJAX.commands.modal_loading = function(command) {
  Drupal.CTools.Modal.modal_loading = function(command) {
    Drupal.CTools.Modal.modal_display({
      output: Drupal.theme(Drupal.CTools.Modal.currentSettings.throbberTheme),
      title: Drupal.CTools.Modal.currentSettings.loadingText
    });
  };

  /**
   * Find a URL for an AJAX button.
   *
   * The URL for this gadget will be composed of the values of items by
   * taking the ID of this item and adding -url and looking for that
   * class. They need to be in the form in order since we will
   * concat them all together using '/'.
   */
  Drupal.CTools.Modal.findURL = function(item) {
    var url = '';
    var url_class = '.' + $(item).attr('id') + '-url';
    $(url_class).each(
      function() {
        var $this = $(this);
        if (url && $this.val()) {
          url += '/';
        }
        url += $this.val();
      });
    return url;
  };


  /**
   * modalContent
   * @param content string to display in the content box
   * @param css obj of css attributes
   * @param animation (fadeIn, slideDown, show)
   * @param speed (valid animation speeds slow, medium, fast or # in ms)
   * @param modalClass class added to div#modalContent
   */
  Drupal.CTools.Modal.modalContent = function(content, css, animation, speed, modalClass) {
    // If our animation isn't set, make it just show/pop
    if (!animation) {
      animation = 'show';
    }
    else {
      // If our animation isn't "fadeIn" or "slideDown" then it always is show
      if (animation != 'fadeIn' && animation != 'slideDown') {
        animation = 'show';
      }
    }

    if (!speed && 0 !== speed) {
      speed = 'fast';
    }

    // Build our base attributes and allow them to be overriden
    css = jQuery.extend({
      position: 'absolute',
      left: '0px',
      margin: '0px',
      background: '#000',
      opacity: '.55'
    }, css);

    // Add opacity handling for IE.
    css.filter = 'alpha(opacity=' + (100 * css.opacity) + ')';
    content.hide();

    // If we already have modalContent, remove it.
    if ($('#modalBackdrop').length) $('#modalBackdrop').remove();
    if ($('#modalContent').length) $('#modalContent').remove();

    // position code lifted from http://www.quirksmode.org/viewport/compatibility.html
    if (self.pageYOffset) { // all except Explorer
    var wt = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
      var wt = document.documentElement.scrollTop;
    } else if (document.body) { // all other Explorers
      var wt = document.body.scrollTop;
    }

    // Get our dimensions

    // Get the docHeight and (ugly hack) add 50 pixels to make sure we dont have a *visible* border below our div
    var docHeight = $(document).height() + 50;
    var docWidth = $(document).width();
    var winHeight = $(window).height();
    var winWidth = $(window).width();
    if( docHeight < winHeight ) docHeight = winHeight;

    // Create our divs
    $('body').append('<div id="modalBackdrop" class="backdrop-' + modalClass + '" style="z-index: 1000; display: none;"></div><div id="modalContent" class="modal-' + modalClass + '" style="z-index: 1001; position: absolute;">' + $(content).html() + '</div>');

    // Get a list of the tabbable elements in the modal content.
    var getTabbableElements = function () {
      var tabbableElements = $('#modalContent :tabbable'),
          radioButtons = tabbableElements.filter('input[type="radio"]');

      // The list of tabbable elements from jQuery is *almost* right. The
      // exception is with groups of radio buttons. The list from jQuery will
      // include all radio buttons, when in fact, only the selected radio button
      // is tabbable, and if no radio buttons in a group are selected, then only
      // the first is tabbable.
      if (radioButtons.length > 0) {
        // First, build up an index of which groups have an item selected or not.
        var anySelected = {};
        radioButtons.each(function () {
          var name = this.name;

          if (typeof anySelected[name] === 'undefined') {
            anySelected[name] = radioButtons.filter('input[name="' + name + '"]:checked').length !== 0;
          }
        });

        // Next filter out the radio buttons that aren't really tabbable.
        var found = {};
        tabbableElements = tabbableElements.filter(function () {
          var keep = true;

          if (this.type == 'radio') {
            if (anySelected[this.name]) {
              // Only keep the selected one.
              keep = this.checked;
            }
            else {
              // Only keep the first one.
              if (found[this.name]) {
                keep = false;
              }
              found[this.name] = true;
            }
          }

          return keep;
        });
      }

      return tabbableElements.get();
    };

    // Keyboard and focus event handler ensures only modal elements gain focus.
    modalEventHandler = function( event ) {
      target = null;
      if ( event ) { //Mozilla
        target = event.target;
      } else { //IE
        event = window.event;
        target = event.srcElement;
      }

      var parents = $(target).parents().get();
      for (var i = 0; i < parents.length; ++i) {
        var position = $(parents[i]).css('position');
        if (position == 'absolute' || position == 'fixed') {
          return true;
        }
      }

      if ($(target).is('#modalContent, body') || $(target).filter('*:visible').parents('#modalContent').length) {
        // Allow the event only if target is a visible child node
        // of #modalContent.
        return true;
      }
      else {
        getTabbableElements()[0].focus();
      }

      event.preventDefault();
    };
    $('body').bind( 'focus', modalEventHandler );
    $('body').bind( 'keypress', modalEventHandler );

    // Keypress handler Ensures you can only TAB to elements within the modal.
    // Based on the psuedo-code from WAI-ARIA 1.0 Authoring Practices section
    // 3.3.1 "Trapping Focus".
    modalTabTrapHandler = function (evt) {
      // We only care about the TAB key.
      if (evt.which != 9) {
        return true;
      }

      var tabbableElements = getTabbableElements(),
          firstTabbableElement = tabbableElements[0],
          lastTabbableElement = tabbableElements[tabbableElements.length - 1],
          singleTabbableElement = firstTabbableElement == lastTabbableElement,
          node = evt.target;

      // If this is the first element and the user wants to go backwards, then
      // jump to the last element.
      if (node == firstTabbableElement && evt.shiftKey) {
        if (!singleTabbableElement) {
          lastTabbableElement.focus();
        }
        return false;
      }
      // If this is the last element and the user wants to go forwards, then
      // jump to the first element.
      else if (node == lastTabbableElement && !evt.shiftKey) {
        if (!singleTabbableElement) {
          firstTabbableElement.focus();
        }
        return false;
      }
      // If this element isn't in the dialog at all, then jump to the first
      // or last element to get the user into the game.
      else if ($.inArray(node, tabbableElements) == -1) {
        // Make sure the node isn't in another modal (ie. WYSIWYG modal).
        var parents = $(node).parents().get();
        for (var i = 0; i < parents.length; ++i) {
          var position = $(parents[i]).css('position');
          if (position == 'absolute' || position == 'fixed') {
            return true;
          }
        }

        if (evt.shiftKey) {
          lastTabbableElement.focus();
        }
        else {
          firstTabbableElement.focus();
        }
      }
    };
    $('body').bind('keydown', modalTabTrapHandler);

    // Create our content div, get the dimensions, and hide it
    var modalContent = $('#modalContent').css('top','-1000px');
    var $modalHeader = modalContent.find('.modal-header');
    var mdcTop = wt + Math.max((winHeight / 2) - (modalContent.outerHeight() / 2), 0);
    var mdcLeft = ( winWidth / 2 ) - ( modalContent.outerWidth() / 2);
    $('#modalBackdrop').css(css).css('top', 0).css('height', docHeight + 'px').css('width', docWidth + 'px').show();
    modalContent.css({top: mdcTop + 'px', left: mdcLeft + 'px'}).hide()[animation](speed);

    // Bind a click for closing the modalContent
    modalContentClose = function(){close(); return false;};
    $('.close', $modalHeader).bind('click', modalContentClose);

    // Bind a keypress on escape for closing the modalContent
    modalEventEscapeCloseHandler = function(event) {
      if (event.keyCode == 27) {
        close();
        return false;
      }
    };

    $(document).bind('keydown', modalEventEscapeCloseHandler);

    // Per WAI-ARIA 1.0 Authoring Practices, initial focus should be on the
    // close button, but we should save the original focus to restore it after
    // the dialog is closed.
    var oldFocus = document.activeElement;
    $('.close', $modalHeader).focus();

    // Close the open modal content and backdrop
    function close() {
      // Unbind the events
      $(window).unbind('resize',  modalContentResize);
      $('body').unbind( 'focus', modalEventHandler);
      $('body').unbind( 'keypress', modalEventHandler );
      $('body').unbind( 'keydown', modalTabTrapHandler );
      $('.close', $modalHeader).unbind('click', modalContentClose);
      $(document).unbind('keydown', modalEventEscapeCloseHandler);
      $(document).trigger('CToolsCloseModalBehaviors', $('#modalContent'));
      $(document).trigger('CToolsDetachBehaviors', $('#modalContent'));

      // Closing animation.
      switch (animation) {
        case 'fadeIn':
          modalContent.fadeOut(speed, modalContentRemove);
          break;

        case 'slideDown':
          modalContent.slideUp(speed, modalContentRemove);
          break;

        case 'show':
          modalContent.hide(speed, modalContentRemove);
          break;
      }
    }

    // Remove the content.
    modalContentRemove = function () {
      $('#modalContent').remove();
      $('#modalBackdrop').remove();

      // Restore focus to where it was before opening the dialog.
      $(oldFocus).focus();
    };

    // Move and resize the modalBackdrop and modalContent on window resize.
    modalContentResize = function () {
      // Reset the backdrop height/width to get accurate document size.
      $('#modalBackdrop').css('height', '').css('width', '');

      // Position code lifted from:
      // http://www.quirksmode.org/viewport/compatibility.html
      if (self.pageYOffset) { // all except Explorer
        var wt = self.pageYOffset;
      } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
        var wt = document.documentElement.scrollTop;
      } else if (document.body) { // all other Explorers
        var wt = document.body.scrollTop;
      }

      // Get our heights
      var docHeight = $(document).height();
      var docWidth = $(document).width();
      var winHeight = $(window).height();
      var winWidth = $(window).width();
      if( docHeight < winHeight ) docHeight = winHeight;

      // Get where we should move content to
      var modalContent = $('#modalContent');
      var mdcTop = wt + Math.max((winHeight / 2) - (modalContent.outerHeight() / 2), 0);
      var mdcLeft = ( winWidth / 2 ) - ( modalContent.outerWidth() / 2);

      // Apply the changes
      $('#modalBackdrop').css('height', docHeight + 'px').css('width', docWidth + 'px').show();
      modalContent.css('top', mdcTop + 'px').css('left', mdcLeft + 'px').show();
    };
    $(window).bind('resize', modalContentResize);
  };

  /**
   * unmodalContent
   * @param content (The jQuery object to remove)
   * @param animation (fadeOut, slideUp, show)
   * @param speed (valid animation speeds slow, medium, fast or # in ms)
   */
  Drupal.CTools.Modal.unmodalContent = function(content, animation, speed)
  {
    // If our animation isn't set, make it just show/pop
    if (!animation) { var animation = 'show'; } else {
      // If our animation isn't "fade" then it always is show
      if (( animation != 'fadeOut' ) && ( animation != 'slideUp')) animation = 'show';
    }
    // Set a speed if we dont have one
    if ( !speed ) var speed = 'fast';

    // Unbind the events we bound
    $(window).unbind('resize', modalContentResize);
    $('body').unbind('focus', modalEventHandler);
    $('body').unbind('keypress', modalEventHandler);
    $('body').unbind( 'keydown', modalTabTrapHandler );
    var $modalContent = $('#modalContent');
    var $modalHeader = $modalContent.find('.modal-header');
    $('.close', $modalHeader).unbind('click', modalContentClose);
    $(document).unbind('keydown', modalEventEscapeCloseHandler);
    $(document).trigger('CToolsDetachBehaviors', $modalContent);

    // jQuery magic loop through the instances and run the animations or removal.
    content.each(function(){
      if ( animation == 'fade' ) {
        $('#modalContent').fadeOut(speed, function() {
          $('#modalBackdrop').fadeOut(speed, function() {
            $(this).remove();
          });
          $(this).remove();
        });
      } else {
        if ( animation == 'slide' ) {
          $('#modalContent').slideUp(speed,function() {
            $('#modalBackdrop').slideUp(speed, function() {
              $(this).remove();
            });
            $(this).remove();
          });
        } else {
          $('#modalContent').remove();
          $('#modalBackdrop').remove();
        }
      }
    });
  };

$(function() {
  Drupal.ajax.prototype.commands.modal_display = Drupal.CTools.Modal.modal_display;
  Drupal.ajax.prototype.commands.modal_dismiss = Drupal.CTools.Modal.modal_dismiss;
});

})(jQuery);
;/*})'"*/;/*})'"*/
/* @preserve
 * The MIT License (MIT)
 * 
 * Copyright (c) 2013-2017 Petka Antonov
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 */
/**
 * bluebird build version 3.5.0
 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
*/
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(s,a){if(!e[s]){if(!t[s]){var c="function"==typeof _dereq_&&_dereq_;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s<n.length;s++)i(n[s]);return i}({1:[function(t,e,n){"use strict";e.exports=function(t){function e(t){var e=new n(t),r=e.promise();return e.setHowMany(1),e.setUnwrap(),e.init(),r}var n=t._SomePromiseArray;t.any=function(t){return e(t)},t.prototype.any=function(){return e(this)}}},{}],2:[function(t,e,n){"use strict";function r(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new u(16),this._normalQueue=new u(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=l}function i(t,e,n){this._lateQueue.push(t,e,n),this._queueTick()}function o(t,e,n){this._normalQueue.push(t,e,n),this._queueTick()}function s(t){this._normalQueue._pushOne(t),this._queueTick()}var a;try{throw new Error}catch(c){a=c}var l=t("./schedule"),u=t("./queue"),p=t("./util");r.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},r.prototype.hasCustomScheduler=function(){return this._customScheduler},r.prototype.enableTrampoline=function(){this._trampolineEnabled=!0},r.prototype.disableTrampolineIfNecessary=function(){p.hasDevTools&&(this._trampolineEnabled=!1)},r.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},r.prototype.fatalError=function(t,e){e?(process.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),process.exit(2)):this.throwLater(t)},r.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(n){throw new Error("No async scheduler available\n\n    See http://goo.gl/MqrFmX\n")}},p.hasDevTools?(r.prototype.invokeLater=function(t,e,n){this._trampolineEnabled?i.call(this,t,e,n):this._schedule(function(){setTimeout(function(){t.call(e,n)},100)})},r.prototype.invoke=function(t,e,n){this._trampolineEnabled?o.call(this,t,e,n):this._schedule(function(){t.call(e,n)})},r.prototype.settlePromises=function(t){this._trampolineEnabled?s.call(this,t):this._schedule(function(){t._settlePromises()})}):(r.prototype.invokeLater=i,r.prototype.invoke=o,r.prototype.settlePromises=s),r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=a},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,s,void 0,u,h),l._then(a,c,void 0,u,h),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":22}],5:[function(t,e,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}var s,a=t("./util"),c=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(c){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n<t.length;++n)this._doInvokeOnCancel(t[n],e);else if(void 0!==t)if("function"==typeof t){if(!e){var r=s(t).call(this._boundValue());r===a&&(this._attachExtraTrace(r.e),c.throwLater(r.e))}}else t._resultCancelled(this)},e.prototype._invokeOnCancel=function(){var t=this._onCancel();this._unsetOnCancel(),c.invoke(this._doInvokeOnCancel,this,t)},e.prototype._invokeInternalOnCancel=function(){this._isCancellable()&&(this._doInvokeOnCancel(this._onCancel(),!0),this._unsetOnCancel())},e.prototype._resultCancelled=function(){this.cancel()}}},{"./util":36}],7:[function(t,e,n){"use strict";e.exports=function(e){function n(t,n,a){return function(c){var l=a._boundValue();t:for(var u=0;u<t.length;++u){var p=t[u];if(p===Error||null!=p&&p.prototype instanceof Error){if(c instanceof p)return o(n).call(l,c)}else if("function"==typeof p){var h=o(p).call(l,c);if(h===s)return h;if(h)return o(n).call(l,c)}else if(r.isObject(c)){for(var f=i(p),_=0;_<f.length;++_){var d=f[_];if(p[d]!=c[d])continue t}return o(n).call(l,c)}}return e}}var r=t("./util"),i=t("./es5").keys,o=r.tryCatch,s=r.errorObj;return n}},{"./es5":13,"./util":36}],8:[function(t,e,n){"use strict";e.exports=function(t){function e(){this._trace=new e.CapturedTrace(r())}function n(){return i?new e:void 0}function r(){var t=o.length-1;return t>=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],9:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function s(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function a(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new S(this._peekContext())}function _(t,e){if(N(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=j(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&W){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),c=w(a),l=c.length-1;l>=0;--l){var u=c[l];if(!U.test(u)){var p=u.match(M);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var h=c[0],l=0;l<a.length;++l)if(a[l]===h){l>0&&(s="\n"+a[l-1]);break}}var f="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;r._warn(f,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new L(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=j(o);o.stack=s.message+"\n"+s.stack.join("\n")}tt("warning",o)||E(o,"",!0)}}function m(t,e){for(var n=0;n<e.length-1;++n)e[n].push("From previous event:"),e[n]=e[n].join("\n");return n<e.length&&(e[n]=e[n].join("\n")),t+"\n"+e.join("\n")}function g(t){for(var e=0;e<t.length;++e)(0===t[e].length||e+1<t.length&&t[e][0]===t[e+1][0])&&(t.splice(e,1),e--)}function b(t){for(var e=t[0],n=1;n<t.length;++n){for(var r=t[n],i=e.length-1,o=e[i],s=-1,a=r.length-1;a>=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var c=r[a];if(e[i]!==c)break;e.pop(),i--}e=r}}function w(t){for(var e=[],n=0;n<t.length;++n){var r=t[n],i="    (No stack trace)"===r||q.test(r),o=i&&nt(r);i&&!o&&($&&" "!==r.charAt(0)&&(r="    "+r),e.push(r))}return e}function C(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),n=0;n<e.length;++n){var r=e[n];if("    (No stack trace)"===r||q.test(r))break}return n>0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function j(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?C(t):["    (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:w(e)}}function E(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+Q(i,t)}else r=e+String(t);"function"==typeof D?D(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function k(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){I.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||E(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.length<e?t:t.substr(0,e-3)+"..."}function T(){return"function"==typeof it}function P(t){var e=t.match(rt);return e?{fileName:e[1],line:parseInt(e[2],10)}:void 0}function R(t,e){if(T()){for(var n,r,i=t.stack.split("\n"),o=e.stack.split("\n"),s=-1,a=-1,c=0;c<i.length;++c){var l=P(i[c]);if(l){n=l.fileName,s=l.line;break}}for(var c=0;c<o.length;++c){var l=P(o[c]);if(l){r=l.fileName,a=l.line;break}}0>s||0>a||!n||!r||n!==r||s>=a||(nt=function(t){if(B.test(t))return!0;var e=P(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function S(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,S),e>32&&this.uncycle()}var O,A,D,V=e._getDomain,I=e._async,L=t("./errors").Warning,H=t("./util"),N=H.canAttachTrace,B=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,U=/\((?:timers\.js):\d+:\d+\)/,M=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,Q=null,$=!1,G=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),z=!(0==H.env("BLUEBIRD_WARNINGS")||!G&&!H.env("BLUEBIRD_WARNINGS")),X=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!G&&!H.env("BLUEBIRD_LONG_STACK_TRACES")),W=0!=H.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(z||!!H.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),I.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){k("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),k("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=V();A="function"==typeof t?null===e?t:H.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=V();O="function"==typeof t?null===e?t:H.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n    See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&T()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n    See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),I.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=f,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),I.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&T()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!H.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!H.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),H.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!H.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return H.isNode?function(){return process.emit.apply(process,arguments)}:H.global?function(t){var e="on"+t.toLowerCase(),n=H.global[e];return n?(n.apply(H.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){I.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[t].apply(null,arguments))}catch(n){I.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,W=ot.warnings,H.isObject(n)&&"wForgottenReturn"in n&&(W=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(I.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=a,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=s,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(S,Error),n.CapturedTrace=S,S.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>a?(c._parent=e[a+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},S.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=j(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(w(i.stack.split("\n"))),i=i._parent;b(r),g(r),H.notEnumerableProp(t,"stack",m(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,Q=e;var n=Error.captureStackTrace;return nt=function(t){return B.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return q=/@/,Q=e,$=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(Q=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,Q=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(D=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?D=function(t,e){var n=e?"[33m":"[31m";console.warn(n+t+"[0m\n")}:H.isNode||"string"!=typeof(new Error).stack||(D=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:z,longStackTraces:!1,cancellation:!1,monitoring:!1};return X&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return h},checkForgottenReturns:d,setBounds:R,warn:y,deprecated:v,CapturedTrace:S,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":12,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return i(this,t,e,0)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,r){return i(t,r,e,0)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5"),c=a.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,h=r("Warning","warning"),f=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(v){o=r("TypeError","type error"),s=r("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),m=0;m<y.length;++m)"function"==typeof Array.prototype[y[m]]&&(d.prototype[y[m]]=Array.prototype[y[m]]);a.defineProperty(d.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),d.prototype.isOperational=!0;var g=0;d.prototype.toString=function(){var t=Array(4*g+1).join(" "),e="\n"+t+"AggregateError of:\n";g++,t=Array(4*g+1).join(" ");for(var n=0;n<this.length;++n){for(var r=this[n]===this?"[Circular AggregateError]":this[n]+"",i=r.split("\n"),o=0;o<i.length;++o)i[o]=t+i[o];r=i.join("\n"),e+=r+"\n"}return g--,e},u(i,Error);var b=Error.__BluebirdErrorTypes__;b||(b=c({CancellationError:f,TimeoutError:_,OperationalError:i,RejectionError:i,AggregateError:d}),a.defineProperty(Error,"__BluebirdErrorTypes__",{value:b,writable:!1,enumerable:!1,configurable:!1})),e.exports={Error:Error,TypeError:o,RangeError:s,CancellationError:b.CancellationError,OperationalError:b.OperationalError,TimeoutError:b.TimeoutError,AggregateError:b.AggregateError,Warning:h}},{"./es5":13,"./util":36}],13:[function(t,e,n){var r=function(){"use strict";return void 0===this}();if(r)e.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:r,propertyIsWritable:function(t,e){var n=Object.getOwnPropertyDescriptor(t,e);return!(n&&!n.writable&&!n.set)}};else{var i={}.hasOwnProperty,o={}.toString,s={}.constructor.prototype,a=function(t){var e=[];for(var n in t)i.call(t,n)&&e.push(n);return e},c=function(t,e){return{value:t[e]}},l=function(t,e,n){return t[e]=n.value,t},u=function(t){return t},p=function(t){try{return Object(t).constructor.prototype}catch(e){return s}},h=function(t){try{return"[object Array]"===o.call(t)}catch(e){return!1}};e.exports={isArray:h,keys:a,names:a,defineProperty:l,getDescriptor:c,freeze:u,getPrototypeOf:p,isES5:r,propertyIsWritable:function(){return!0}}}},{}],14:[function(t,e,n){"use strict";e.exports=function(t,e){var n=t.map;t.prototype.filter=function(t,r){return n(this,t,r,e)},t.filter=function(t,r,i){return n(t,r,i,e)}}},{}],15:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t,e,n){this.promise=t,this.type=e,this.handler=n,this.called=!1,this.cancelPromise=null}function o(t){this.finallyHandler=t}function s(t,e){return null!=t.cancelPromise?(arguments.length>1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function a(){return l.call(this,this.promise._target()._settledValue())}function c(t){return s(this,t)?void 0:(h.e=t,h)}function l(t){var i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var f=n(u,i);if(f instanceof e){if(null!=this.cancelPromise){if(f._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),h.e=_,h}f.isPending()&&f._attachCancellationCallback(new o(this))}return f._then(a,c,void 0,this,void 0)}}}return i.isRejected()?(s(this),h.e=t,h):(s(this),t)}var u=t("./util"),p=e.CancellationError,h=u.errorObj,f=t("./catch_filter")(r);return i.prototype.isFinallyHandler=function(){return 0===this.type},o.prototype._resultCancelled=function(){s(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,new i(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,l,l)},e.prototype.tap=function(t){return this._passThrough(t,1,l)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,l);var r,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var s=arguments[r];if(!u.isObject(s))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(s)));i[o++]=s}i.length=o;var a=arguments[r];return this._passThrough(f(i,a,this),1,void 0,l)},i}},{"./catch_filter":7,"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o<n.length;++o){r._pushContext();var s=f(n[o])(t);if(r._popContext(),s===h){r._pushContext();var a=e.reject(h.e);return r._popContext(),a}var c=i(s,r);if(c instanceof e)return c}return null}function c(t,n,i,o){if(s.cancellation()){var a=new e(r),c=this._finallyPromise=new e(r);this._promise=a.lastly(function(){return c}),a._captureStackTrace(),a._setOnCancel(this)}else{var l=this._promise=new e(r);l._captureStackTrace()}this._stack=o,this._generatorFunction=t,this._receiver=n,this._generator=void 0,this._yieldHandlers="function"==typeof i?[i].concat(_):_,this._yieldedPromise=null,this._cancellationPhase=!1}var l=t("./errors"),u=l.TypeError,p=t("./util"),h=p.errorObj,f=p.tryCatch,_=[];p.inherits(c,o),c.prototype._isResolved=function(){return null===this._promise},c.prototype._cleanup=function(){this._promise=this._generator=null,s.cancellation()&&null!==this._finallyPromise&&(this._finallyPromise._fulfill(),this._finallyPromise=null)},c.prototype._promiseCancelled=function(){if(!this._isResolved()){var t,n="undefined"!=typeof this._generator["return"];if(n)this._promise._pushContext(),t=f(this._generator["return"]).call(this._generator,void 0),this._promise._popContext();else{var r=new e.CancellationError("generator .return() sentinel");e.coroutine.returnSentinel=r,this._promise._attachExtraTrace(r),this._promise._pushContext(),t=f(this._generator["throw"]).call(this._generator,r),this._promise._popContext()}this._cancellationPhase=!0,this._yieldedPromise=null,this._continue(t)}},c.prototype._promiseFulfilled=function(t){this._yieldedPromise=null,this._promise._pushContext();var e=f(this._generator.next).call(this._generator,t);this._promise._popContext(),this._continue(e)},c.prototype._promiseRejected=function(t){this._yieldedPromise=null,this._promise._attachExtraTrace(t),this._promise._pushContext();var e=f(this._generator["throw"]).call(this._generator,t);this._promise._popContext(),this._continue(e)},c.prototype._resultCancelled=function(){if(this._yieldedPromise instanceof e){var t=this._yieldedPromise;this._yieldedPromise=null,t.cancel()}},c.prototype.promise=function(){return this._promise},c.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver),this._receiver=this._generatorFunction=void 0,this._promiseFulfilled(void 0)},c.prototype._continue=function(t){var n=this._promise;if(t===h)return this._cleanup(),this._cancellationPhase?n.cancel():n._rejectCallback(t.e,!1);var r=t.value;if(t.done===!0)return this._cleanup(),this._cancellationPhase?n.cancel():n._resolveCallback(r);var o=i(r,this._promise);if(!(o instanceof e)&&(o=a(o,this._yieldHandlers,this._promise),null===o))return void this._promiseRejected(new u("A value %s was yielded that could not be treated as a promise\n\n    See http://goo.gl/MqrFmX\n\n".replace("%s",String(r))+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")));o=o._target();var s=o._bitField;0===(50397184&s)?(this._yieldedPromise=o,o._proxy(this,null)):0!==(33554432&s)?e._async.invoke(this._promiseFulfilled,this,o._value()):0!==(16777216&s)?e._async.invoke(this._promiseRejected,this,o._reason()):this._promiseCancelled();
},e.coroutine=function(t,e){if("function"!=typeof t)throw new u("generatorFunction must be a function\n\n    See http://goo.gl/MqrFmX\n");var n=Object(e).yieldHandler,r=c,i=(new Error).stack;return function(){var e=t.apply(this,arguments),o=new r(void 0,void 0,n,i),s=o.promise();return o._generator=e,o._promiseFulfilled(void 0),s}},e.coroutine.addYieldHandler=function(t){if("function"!=typeof t)throw new u("expecting a function but got "+p.classString(t));_.push(t)},e.spawn=function(t){if(s.deprecated("Promise.spawn()","Promise.coroutine()"),"function"!=typeof t)return n("generatorFunction must be a function\n\n    See http://goo.gl/MqrFmX\n");var r=new c(t,this),i=r.promise();return r._run(e.spawn),i}}},{"./errors":12,"./util":36}],17:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){var a=t("./util");a.canEvaluate,a.tryCatch,a.errorObj;e.join=function(){var t,e=arguments.length-1;if(e>0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=l();this._callback=null===i?e:u.domainBind(i,e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],f.invoke(this._asyncInit,this,void 0)}function c(t,n,i,o){if("function"!=typeof n)return r("expecting a function but got "+u.classString(n));var s=0;if(void 0!==i){if("object"!=typeof i||null===i)return e.reject(new TypeError("options argument must be an object but it is "+u.classString(i)));if("number"!=typeof i.concurrency)return e.reject(new TypeError("'concurrency' must be a number but it is "+u.classString(i.concurrency)));s=i.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new a(t,n,s,o).promise()}var l=e._getDomain,u=t("./util"),p=u.tryCatch,h=u.errorObj,f=e._async;u.inherits(a,n),a.prototype._asyncInit=function(){this._init$(void 0,-2)},a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){var r=this._values,o=this.length(),a=this._preservedValues,c=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,c>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(c>=1&&this._inFlight>=c)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var l=this._promise,u=this._callback,f=l._boundValue();l._pushContext();var _=p(u).call(f,t,n,o),d=l._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",l),_===h)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return c>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var m=++this._totalResolved;return m>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlight<e;){if(this._isResolved())return;var r=t.pop();this._promiseFulfilled(n[r],r)}},a.prototype._filter=function(t,e){for(var n=e.length,r=new Array(n),i=0,o=0;n>o;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return c(this,t,e,null)},e.map=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments),s=r._popContext();return o.checkForgottenReturns(i,s,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=s.isArray(l)?a(t).apply(u,l):a(t).call(u,l)}else c=a(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=u.keys(t),i=0;i<n.length;++i){var o=n[i];p.test(o)||(e[o]=t[o])}return e}return s.markAsOriginatingFromRejection(t),t}function o(t,e){return function(n,r){if(null!==t){if(n){var o=i(a(n));t._attachExtraTrace(o),t._reject(o)}else if(e){var s=[].slice.call(arguments,1);t._fulfill(s)}else t._fulfill(r);t=null}}}var s=t("./util"),a=s.maybeWrapAsError,c=t("./errors"),l=c.OperationalError,u=t("./es5"),p=/^(?:name|message|stack|cause)$/;e.exports=o},{"./errors":12,"./es5":13,"./util":36}],21:[function(t,e,n){"use strict";e.exports=function(e){function n(t,e){var n=this;if(!o.isArray(t))return r.call(n,t,e);var i=a(e).apply(n._boundValue(),[null].concat(t));i===c&&s.throwLater(i.e)}function r(t,e){var n=this,r=n._boundValue(),i=void 0===t?a(e).call(r,null):a(e).call(r,null,t);i===c&&s.throwLater(i.e)}function i(t,e){var n=this;if(!t){var r=new Error(t+"");r.cause=t,t=r}var i=a(e).call(n._boundValue(),t);i===c&&s.throwLater(i.e)}var o=t("./util"),s=e._async,a=o.tryCatch,c=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=r;void 0!==e&&Object(e).spread&&(o=n),this._then(o,i,void 0,this,t)}return this}}},{"./util":36}],22:[function(t,e,n){"use strict";e.exports=function(){function n(){}function r(t,e){if(null==t||t.constructor!==i)throw new m("the promise constructor cannot be invoked directly\n\n    See http://goo.gl/MqrFmX\n");if("function"!=typeof e)throw new m("expecting a function but got "+f.classString(e))}function i(t){t!==b&&r(this,t),this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._resolveFromExecutor(t),this._promiseCreated(),this._fireEvent("promiseCreated",this)}function o(t){this.promise._resolveCallback(t)}function s(t){this.promise._rejectCallback(t,!1)}function a(t){var e=new i(b);e._fulfillmentHandler0=t,e._rejectionHandler0=t,e._promise0=t,e._receiver0=t}var c,l=function(){return new m("circular promise resolution chain\n\n    See http://goo.gl/MqrFmX\n")},u=function(){return new i.PromiseInspection(this._target())},p=function(t){return i.reject(new m(t))},h={},f=t("./util");c=f.isNode?function(){var t=process.domain;return void 0===t&&(t=null),t}:function(){return null},f.notEnumerableProp(i,"_getDomain",c);var _=t("./es5"),d=t("./async"),v=new d;_.defineProperty(i,"_async",{value:v});var y=t("./errors"),m=i.TypeError=y.TypeError;i.RangeError=y.RangeError;var g=i.CancellationError=y.CancellationError;i.TimeoutError=y.TimeoutError,i.OperationalError=y.OperationalError,i.RejectionError=y.OperationalError,i.AggregateError=y.AggregateError;var b=function(){},w={},C={},j=t("./thenables")(i,b),E=t("./promise_array")(i,b,j,p,n),k=t("./context")(i),F=k.create,x=t("./debuggability")(i,k),T=(x.CapturedTrace,t("./finally")(i,j,C)),P=t("./catch_filter")(C),R=t("./nodeback"),S=f.errorObj,O=f.tryCatch;return i.prototype.toString=function(){return"[object Promise]"},i.prototype.caught=i.prototype["catch"]=function(t){var e=arguments.length;if(e>1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!f.isObject(o))return p("Catch statement predicate: expecting an object but got "+f.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(u,u,void 0,this,void 0)},i.prototype.then=function(t,e){if(x.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+f.classString(t);arguments.length>1&&(n+=", "+f.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?p("expecting a function but got "+f.classString(t)):this.all()._then(t,void 0,void 0,w,void 0)},i.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new E(this).promise()},i.prototype.error=function(t){return this.caught(f.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=O(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new E(t).promise()},i.cast=function(t){var e=j(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var s=void 0!==o,a=s?o:new i(b),l=this._target(),u=l._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var p=c();if(0!==(50397184&u)){var h,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,h=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,h=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new g("late cancellation observer"),l._attachExtraTrace(_),h=e),v.invoke(d,l,{handler:null===p?h:"function"==typeof h&&f.domainBind(p,h),promise:a,receiver:r,value:_})}else l._addCallbacks(t,e,a,r,p);return a},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},i.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},i.prototype._setAsyncGuaranteed=function(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===h?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=h),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=h),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:f.domainBind(i,e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this[s+1]=null===i?e:f.domainBind(i,e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(l(),!1);var n=j(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(l());var o=r._bitField;if(0===(50397184&o)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;s>a;++a)r._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new g("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=f.ensureErrorObject(t),i=r===t;if(!i&&!n&&x.warnings()){var o="a promise was rejected with a non-error: "+f.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==b){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)}},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===w?n&&"number"==typeof n.length?o=O(t).apply(this._boundValue(),n):(o=S,o.e=new m("cannot .spread() a non-array: "+f.classString(n))):o=O(t).call(e,n);var s=r._popContext();i=r._bitField,0===(65536&i)&&(o===C?r._reject(n):o===S?r._rejectCallback(o.e,!1):(x.checkForgottenReturns(o,s,"",r,this),r._resolveCallback(o)))}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var s=t instanceof i,a=this._bitField,c=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),r instanceof T&&r.isFinallyHandler()?(r.cancelPromise=t,O(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):s||t instanceof E?t._cancel():r.cancel()):"function"==typeof e?s?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&a)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):s&&(c&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,f.isNode):void((65535&e)>0?v.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){x.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:s}},f.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,j,p,x),t("./bind")(i,b,j,x),t("./cancel")(i,E,p,x),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,E,j,b,v,c),i.Promise=i,i.version="3.5.0",t("./map.js")(i,E,p,j,b,x),t("./call_get.js")(i),t("./using.js")(i,p,j,F,b,x),t("./timers.js")(i,b,x),t("./generators.js")(i,p,b,j,n,x),t("./nodeify.js")(i),t("./promisify.js")(i,b),t("./props.js")(i,E,j,p),t("./race.js")(i,b,j,p),t("./reduce.js")(i,E,p,j,b,x),t("./settle.js")(i,E,x),t("./some.js")(i,E,p),t("./filter.js")(i,b),t("./each.js")(i,b),t("./any.js")(i),f.toFastProperties(i),f.toFastProperties(i.prototype),a({a:1}),a({b:2}),a({c:3}),a(1),a(function(){}),a(void 0),a(!1),a(new i(b)),x.setBounds(d.firstLineError,f.lastLineError),i}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}function a(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var a=o._bitField;if(this._values=o,0===(50397184&a))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&a))return 0!==(16777216&a)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(s(n))):void this._iterate(o)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var c=r(t[a],i);c instanceof e?(c=c._target(),s=c._bitField):s=null,o?null!==s&&c.suppressUnhandledRejections():null!==s?0===(50397184&s)?(c._proxy(this,a),this._values[a]=c):o=0!==(33554432&s)?this._promiseFulfilled(c._value(),a):0!==(16777216&s)?this._promiseRejected(c._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(c,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;n<t.length;++n)t[n]instanceof e&&t[n].cancel()}},a.prototype.shouldCopyValues=function(){return!0},a.prototype.getActualLength=function(t){return t},a}},{"./util":36}],24:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t){return!C.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,n){var r=f.getDataPropertyOrDefault(t,e+n,b);return r?i(r):!1}function s(t,e,n){for(var r=0;r<t.length;r+=2){var i=t[r];if(n.test(i))for(var o=i.replace(n,""),s=0;s<t.length;s+=2)if(t[s]===o)throw new m("Cannot promisify an API that has normal methods with '%s'-suffix\n\n    See http://goo.gl/MqrFmX\n".replace("%s",e))}}function a(t,e,n,r){for(var a=f.inheritedDataKeys(t),c=[],l=0;l<a.length;++l){var u=a[l],p=t[u],h=r===j?!0:j(u,p,t);"function"!=typeof p||i(p)||o(t,u,e)||!r(u,p,t,h)||c.push(u,p)}return s(c,e,n),c}function c(t,r,i,o,s,a){function c(){var i=r;r===h&&(i=this);var o=new e(n);o._captureStackTrace();var s="string"==typeof u&&this!==l?this[u]:t,c=_(o,a);try{s.apply(i,d(arguments,c))}catch(p){o._rejectCallback(v(p),!0,!0)}return o._isFateSealed()||o._setAsyncGuaranteed(),o}var l=function(){return this}(),u=t;return"string"==typeof u&&(t=o),f.notEnumerableProp(c,"__isPromisified__",!0),c}function l(t,e,n,r,i){for(var o=new RegExp(E(e)+"$"),s=a(t,e,o,n),c=0,l=s.length;l>c;c+=2){var u=s[c],p=s[c+1],_=u+e;if(r===k)t[_]=k(u,h,u,p,e,i);else{var d=r(p,function(){return k(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return k(t,e,void 0,t,null,n)}var p,h={},f=t("./util"),_=t("./nodeback"),d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,m=t("./errors").TypeError,g="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},E=function(t){return t.replace(/([$])/,"\\$")},k=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?h:e.context,o=!!e.multiArgs,s=u(t,n,o);return f.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new m("the target of promisifyAll must be an object or a function\n\n    See http://goo.gl/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=g);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=k),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n    See http://goo.gl/MqrFmX\n");for(var s=f.inheritedDataKeys(t),a=0;a<s.length;++a){var c=t[s[a]];"constructor"!==s[a]&&f.isClass(c)&&(l(c.prototype,r,i,o,n),l(c,r,i,o,n))}return l(t,r,i,o,n)}}},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){function o(t){var e,n=!1;if(void 0!==a&&t instanceof a)e=p(t),n=!0;else{var r=u.keys(t),i=r.length;e=new Array(2*i);for(var o=0;i>o;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,n?-6:-3)}function s(t){var n,s=r(t);return l(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n    See http://goo.gl/MqrFmX\n")}var a,c=t("./util"),l=c.isObject,u=t("./es5");"function"==typeof Map&&(a=Map);var p=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),h=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};c.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=h(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacity<t},i.prototype._pushOne=function(t){var e=this.length();this._checkCapacity(e+1);var n=this._front+e&this._capacity-1;this[n]=t,this._length=e+1},i.prototype.push=function(t,e,n){var r=this.length()+3;if(this._willBeOverCapacity(r))return this._pushOne(t),this._pushOne(e),void this._pushOne(n);var i=this._front+r-3;this._checkCapacity(r);var o=this._capacity-1;this[i+0&o]=t,this[i+1&o]=e,this[i+2&o]=n,this._length=r},i.prototype.shift=function(){var t=this._front,e=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length--,e},i.prototype.length=function(){return this._length},i.prototype._checkCapacity=function(t){this._capacity<t&&this._resizeTo(this._capacity<<1)},i.prototype._resizeTo=function(t){var e=this._capacity;this._capacity=t;var n=this._front,i=this._length,o=n+i&e-1;r(this,0,this,e,o)},e.exports=i},{}],27:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){function o(t,o){var c=r(t);if(c instanceof e)return a(c);if(t=s.asArray(t),null===t)return i("expecting an array or an iterable object but got "+s.classString(t));var l=new e(n);void 0!==o&&l._propagateFrom(o,3);for(var u=l._fulfill,p=l._reject,h=0,f=t.length;f>h;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,p,void 0,l,null)}return l}var s=t("./util"),a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=h();this._fn=null===s?n:f.domainBind(s,n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,i===o?this._eachValues=Array(this._length):0===i?this._eachValues=null:this._eachValues=void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function l(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+f.classString(e));var o=new a(t,e,n,i);return o.promise()}function u(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(p,void 0,void 0,this,void 0)):p.call(this,n)}function p(t){var n=this.array,r=n._promise,i=_(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var h=e._getDomain,f=t("./util"),_=f.tryCatch;f.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&null!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return null!==this._eachValues&&this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(u,void 0,void 0,o,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(c,c,void 0,n,this)},e.prototype.reduce=function(t,e){return l(this,t,e,null)},e.reduce=function(t,e,n,r){return l(t,e,n,r)}}},{"./util":36}],29:[function(t,e,n){"use strict";var r,i=t("./util"),o=function(){throw new Error("No async scheduler available\n\n    See http://goo.gl/MqrFmX\n")},s=i.getNativePromise();if(i.isNode&&"undefined"==typeof MutationObserver){var a=global.setImmediate,c=process.nextTick;r=i.isRecentNode?function(t){a.call(global,t)}:function(t){c.call(process,t)}}else if("function"==typeof s&&"function"==typeof s.resolve){var l=s.resolve();r=function(t){l.then(t)}}else r="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o:function(){var t=document.createElement("div"),e={attributes:!0},n=!1,r=document.createElement("div"),i=new MutationObserver(function(){t.classList.toggle("foo"),n=!1});i.observe(r,e);var o=function(){n||(n=!0,r.classList.toggle("foo"))};return function(n){var r=new MutationObserver(function(){r.disconnect(),n()});r.observe(t,e),o()}}();e.exports=r},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t),
this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return r("expecting a positive integer\n\n    See http://goo.gl/MqrFmX\n");var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,c=t("./errors").AggregateError,l=s.isArray,u={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=l(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()?(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new c,e=this.length();e<this._values.length;++e)this._values[e]!==u&&t.push(this._values[e]);return t.length>0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n    See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n    See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},t.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){r&&r._pushContext();var c=e.reject(i.e);return r&&r._popContext(),c}if("function"==typeof i){if(s(t)){var c=new e(n);return t._then(c._fulfill,c._reject,void 0,c,null),c}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(e){return l.e=e,l}}function s(t){try{return p.call(t,"_promise0")}catch(e){return!1}}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,p,!0),a=null)}var a=new e(n),u=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,h=c.tryCatch(r).call(t,o,s);return p=!1,a&&h===l&&(a._rejectCallback(h.e,!0,!0),a=null),u}var c=t("./util"),l=c.errorObj,u=c.isObject,p={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.handle=t}function o(t){return clearTimeout(this.handle),t}function s(t){throw clearTimeout(this.handle),t}var a=t("./util"),c=e.TimeoutError;i.prototype._resultCancelled=function(){clearTimeout(this.handle)};var l=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var s,a;return void 0!==o?(s=e.resolve(o)._then(l,null,null,t,void 0),r.cancellation()&&o instanceof e&&s._setOnCancel(o)):(s=new e(n),a=setTimeout(function(){s._fulfill()},+t),r.cancellation()&&s._setOnCancel(new i(a)),s._captureStackTrace()),s._setAsyncGuaranteed(),s};e.prototype.delay=function(t){return u(t,this)};var p=function(t,e,n){var r;r="string"!=typeof e?e instanceof Error?e:new c("operation timed out"):new c(e),a.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._reject(r),null!=n&&n.cancel()};e.prototype.timeout=function(t,e){t=+t;var n,a,c=new i(setTimeout(function(){n.isPending()&&p(n,e,a)},t));return r.cancellation()?(a=this.then(),n=a._then(o,s,void 0,c,void 0),n._setOnCancel(c)):n=this._then(o,s,void 0,c,void 0),n}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function c(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function l(t,n){function i(){if(s>=l)return u._fulfill();var o=c(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(p){return a(p)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,l=t.length,u=new e(o);return i(),u}function u(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function h(t){return u.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function f(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,m=_.tryCatch,g={};u.prototype.data=function(){return this._data},u.prototype.promise=function(){return this._promise},u.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():g},u.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=e!==g?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},u.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,u),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},f.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var c=new f(t),p=0;t>p;++p){var d=o[p];if(u.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var g=r(d);g instanceof e&&(d=g._then(h,null,null,{resources:c,index:p},void 0))}c[p]=d}for(var b=new Array(c.length),p=0;p<b.length;++p)b[p]=e.resolve(c[p]).reflect();var w=e.all(b).then(function(t){for(var e=0;e<t.length;++e){var n=t[e];if(n.isRejected())return y.e=n.error(),y;if(!n.isFulfilled())return void w.cancel();t[e]=n.value()}C._pushContext(),i=m(i);var r=a?i.apply(void 0,t):i(t),o=C._popContext();return s.checkForgottenReturns(r,o,"Promise.using",C),r}),C=w.lastly(function(){var t=new e.PromiseInspection(w);return l(c,t)});return c.promise=C,C._setOnCancel(c),C},e.prototype._setDisposable=function(t){this._bitField=131072|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(131072&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(t,e,n){"use strict";function r(){try{var t=P;return P=null,t.apply(this,arguments)}catch(e){return T.e=e,T}}function i(t){return P=t,r}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return"function"==typeof t||"object"==typeof t&&null!==t}function a(t){return o(t)?new Error(v(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function p(t){throw t}function h(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=A.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function f(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return D.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function m(t){try{u(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&F.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function C(t,e,n){for(var r=F.names(t),i=0;i<r.length;++i){var o=r[i];if(n(o))try{F.defineProperty(e,o,F.getDescriptor(t,o))}catch(s){}}}function j(t){return N?process.env[t]:void 0}function E(){if("function"==typeof Promise)try{var t=new Promise(function(){});if("[object Promise]"==={}.toString.call(t))return Promise}catch(e){}}function k(t,e){return t.bind(e)}var F=t("./es5"),x="undefined"==typeof navigator,T={e:{}},P,R="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0!==this?this:null,S=function(t,e){function n(){this.constructor=t,this.constructor$=e;for(var n in e.prototype)r.call(e.prototype,n)&&"$"!==n.charAt(n.length-1)&&(this[n+"$"]=e.prototype[n])}var r={}.hasOwnProperty;return n.prototype=e.prototype,t.prototype=new n,t.prototype},O=function(){var t=[Array.prototype,Object.prototype,Function.prototype],e=function(e){for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1};if(F.isES5){var n=Object.getOwnPropertyNames;return function(t){for(var r=[],i=Object.create(null);null!=t&&!e(t);){var o;try{o=n(t)}catch(s){return r}for(var a=0;a<o.length;++a){var c=o[a];if(!i[c]){i[c]=!0;var l=Object.getOwnPropertyDescriptor(t,c);null!=l&&null==l.get&&null==l.set&&r.push(c)}}t=F.getPrototypeOf(t)}return r}}var r={}.hasOwnProperty;return function(n){if(e(n))return[];var i=[];t:for(var o in n)if(r.call(n,o))i.push(o);else{for(var s=0;s<t.length;++s)if(r.call(t[s],o))continue t;i.push(o)}return i}}(),A=/this\s*\.\s*\S+\s*=/,D=/^[a-z$_][a-z$_0-9]*$/i,V=function(){return"stack"in new Error?function(t){return b(t)?t:new Error(v(t))}:function(t){if(b(t))return t;try{throw new Error(v(t))}catch(e){return e}}}(),I=function(t){return F.isArray(t)?t:null};if("undefined"!=typeof Symbol&&Symbol.iterator){var L="function"==typeof Array.from?function(t){return Array.from(t)}:function(t){for(var e,n=[],r=t[Symbol.iterator]();!(e=r.next()).done;)n.push(e.value);return n};I=function(t){return F.isArray(t)?t:null!=t&&"function"==typeof t[Symbol.iterator]?L(t):null}}var H="undefined"!=typeof process&&"[object process]"===w(process).toLowerCase(),N="undefined"!=typeof process&&"undefined"!=typeof process.env,B={isClass:h,isIdentifier:_,inheritedDataKeys:O,getDataPropertyOrDefault:l,thrower:p,isArray:F.isArray,asArray:I,notEnumerableProp:u,isPrimitive:o,isObject:s,isError:y,canEvaluate:x,errorObj:T,tryCatch:i,inherits:S,withAppended:c,maybeWrapAsError:a,toFastProperties:f,filledRange:d,toString:v,canAttachTrace:b,ensureErrorObject:V,originatesFromRejection:g,markAsOriginatingFromRejection:m,classString:w,copyDescriptors:C,hasDevTools:"undefined"!=typeof chrome&&chrome&&"function"==typeof chrome.loadTimes,isNode:H,hasEnvVariables:N,env:j,global:R,getNativePromise:E,domainBind:k};B.isRecentNode=B.isNode&&function(){var t=process.versions.node.split(".").map(Number);return 0===t[0]&&t[1]>10||t[0]>0}(),B.isNode&&B.toFastProperties(process);try{throw new Error}catch(U){B.lastLineError=U}e.exports=B},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise);
;/*})'"*/;/*})'"*/
/* perfect-scrollbar v0.6.2 */
!function t(e,n,r){function o(l,s){if(!n[l]){if(!e[l]){var a="function"==typeof require&&require;if(!s&&a)return a(l,!0);if(i)return i(l,!0);var c=new Error("Cannot find module '"+l+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[l]={exports:{}};e[l][0].call(u.exports,function(t){var n=e[l][1][t];return o(n?n:t)},u,u.exports,t,e,n,r)}return n[l].exports}for(var i="function"==typeof require&&require,l=0;l<r.length;l++)o(r[l]);return o}({1:[function(t,e){"use strict";function n(t){t.fn.perfectScrollbar=function(e){return this.each(function(){if("object"==typeof e||"undefined"==typeof e){var n=e;o.get(this)||r.initialize(this,n)}else{var i=e;"update"===i?r.update(this):"destroy"===i&&r.destroy(this)}return t(this)})}}var r=t("../main"),o=t("../plugin/instances");if("function"==typeof define&&define.amd)define(["jquery"],n);else{var i=window.jQuery?window.jQuery:window.$;"undefined"!=typeof i&&n(i)}e.exports=n},{"../main":7,"../plugin/instances":18}],2:[function(t,e,n){"use strict";function r(t,e){var n=t.className.split(" ");n.indexOf(e)<0&&n.push(e),t.className=n.join(" ")}function o(t,e){var n=t.className.split(" "),r=n.indexOf(e);r>=0&&n.splice(r,1),t.className=n.join(" ")}n.add=function(t,e){t.classList?t.classList.add(e):r(t,e)},n.remove=function(t,e){t.classList?t.classList.remove(e):o(t,e)},n.list=function(t){return t.classList?t.classList:t.className.split(" ")}},{}],3:[function(t,e,n){"use strict";function r(t,e){return window.getComputedStyle(t)[e]}function o(t,e,n){return"number"==typeof n&&(n=n.toString()+"px"),t.style[e]=n,t}function i(t,e){for(var n in e){var r=e[n];"number"==typeof r&&(r=r.toString()+"px"),t.style[n]=r}return t}n.e=function(t,e){var n=document.createElement(t);return n.className=e,n},n.appendTo=function(t,e){return e.appendChild(t),t},n.css=function(t,e,n){return"object"==typeof e?i(t,e):"undefined"==typeof n?r(t,e):o(t,e,n)},n.matches=function(t,e){return"undefined"!=typeof t.matches?t.matches(e):"undefined"!=typeof t.matchesSelector?t.matchesSelector(e):"undefined"!=typeof t.webkitMatchesSelector?t.webkitMatchesSelector(e):"undefined"!=typeof t.mozMatchesSelector?t.mozMatchesSelector(e):"undefined"!=typeof t.msMatchesSelector?t.msMatchesSelector(e):void 0},n.remove=function(t){"undefined"!=typeof t.remove?t.remove():t.parentNode&&t.parentNode.removeChild(t)}},{}],4:[function(t,e){"use strict";var n=function(t){this.element=t,this.events={}};n.prototype.bind=function(t,e){"undefined"==typeof this.events[t]&&(this.events[t]=[]),this.events[t].push(e),this.element.addEventListener(t,e,!1)},n.prototype.unbind=function(t,e){var n="undefined"!=typeof e;this.events[t]=this.events[t].filter(function(r){return n&&r!==e?!0:(this.element.removeEventListener(t,r,!1),!1)},this)},n.prototype.unbindAll=function(){for(var t in this.events)this.unbind(t)};var r=function(){this.eventElements=[]};r.prototype.eventElement=function(t){var e=this.eventElements.filter(function(e){return e.element===t})[0];return"undefined"==typeof e&&(e=new n(t),this.eventElements.push(e)),e},r.prototype.bind=function(t,e,n){this.eventElement(t).bind(e,n)},r.prototype.unbind=function(t,e,n){this.eventElement(t).unbind(e,n)},r.prototype.unbindAll=function(){for(var t=0;t<this.eventElements.length;t++)this.eventElements[t].unbindAll()},r.prototype.once=function(t,e,n){var r=this.eventElement(t),o=function(t){r.unbind(e,o),n(t)};r.bind(e,o)},e.exports=r},{}],5:[function(t,e){"use strict";e.exports=function(){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return function(){return t()+t()+"-"+t()+"-"+t()+"-"+t()+"-"+t()+t()+t()}}()},{}],6:[function(t,e,n){"use strict";var r=t("./class"),o=t("./dom");n.toInt=function(t){return"string"==typeof t?parseInt(t,10):~~t},n.clone=function(t){if(null===t)return null;if("object"==typeof t){var e={};for(var n in t)e[n]=this.clone(t[n]);return e}return t},n.extend=function(t,e){var n=this.clone(t);for(var r in e)n[r]=this.clone(e[r]);return n},n.isEditable=function(t){return o.matches(t,"input,[contenteditable]")||o.matches(t,"select,[contenteditable]")||o.matches(t,"textarea,[contenteditable]")||o.matches(t,"button,[contenteditable]")},n.removePsClasses=function(t){for(var e=r.list(t),n=0;n<e.length;n++){var o=e[n];0===o.indexOf("ps-")&&r.remove(t,o)}},n.outerWidth=function(t){return this.toInt(o.css(t,"width"))+this.toInt(o.css(t,"paddingLeft"))+this.toInt(o.css(t,"paddingRight"))+this.toInt(o.css(t,"borderLeftWidth"))+this.toInt(o.css(t,"borderRightWidth"))},n.startScrolling=function(t,e){r.add(t,"ps-in-scrolling"),"undefined"!=typeof e?r.add(t,"ps-"+e):(r.add(t,"ps-x"),r.add(t,"ps-y"))},n.stopScrolling=function(t,e){r.remove(t,"ps-in-scrolling"),"undefined"!=typeof e?r.remove(t,"ps-"+e):(r.remove(t,"ps-x"),r.remove(t,"ps-y"))},n.env={isWebKit:"WebkitAppearance"in document.documentElement.style,supportsTouch:"ontouchstart"in window||window.DocumentTouch&&document instanceof window.DocumentTouch,supportsIePointer:null!==window.navigator.msMaxTouchPoints}},{"./class":2,"./dom":3}],7:[function(t,e){"use strict";var n=t("./plugin/destroy"),r=t("./plugin/initialize"),o=t("./plugin/update");e.exports={initialize:r,update:o,destroy:n}},{"./plugin/destroy":9,"./plugin/initialize":17,"./plugin/update":20}],8:[function(t,e){"use strict";e.exports={wheelSpeed:1,wheelPropagation:!1,swipePropagation:!0,minScrollbarLength:null,maxScrollbarLength:null,useBothWheelAxes:!1,useKeyboard:!0,suppressScrollX:!1,suppressScrollY:!1,scrollXMarginOffset:0,scrollYMarginOffset:0}},{}],9:[function(t,e){"use strict";var n=t("../lib/dom"),r=t("../lib/helper"),o=t("./instances");e.exports=function(t){var e=o.get(t);e.event.unbindAll(),n.remove(e.scrollbarX),n.remove(e.scrollbarY),n.remove(e.scrollbarXRail),n.remove(e.scrollbarYRail),r.removePsClasses(t),o.remove(t)}},{"../lib/dom":3,"../lib/helper":6,"./instances":18}],10:[function(t,e){"use strict";function n(t,e){function n(t){return t.getBoundingClientRect()}var o=window.Event.prototype.stopPropagation.bind;e.event.bind(e.scrollbarY,"click",o),e.event.bind(e.scrollbarYRail,"click",function(o){var l=r.toInt(e.scrollbarYHeight/2),s=o.pageY-n(e.scrollbarYRail).top-l,a=e.containerHeight-e.scrollbarYHeight,c=s/a;0>c?c=0:c>1&&(c=1),t.scrollTop=(e.contentHeight-e.containerHeight)*c,i(t)}),e.event.bind(e.scrollbarX,"click",o),e.event.bind(e.scrollbarXRail,"click",function(o){var l=r.toInt(e.scrollbarXWidth/2),s=o.pageX-n(e.scrollbarXRail).left-l;console.log(o.pageX,e.scrollbarXRail.offsetLeft);var a=e.containerWidth-e.scrollbarXWidth,c=s/a;0>c?c=0:c>1&&(c=1),t.scrollLeft=(e.contentWidth-e.containerWidth)*c,i(t)})}var r=t("../../lib/helper"),o=t("../instances"),i=t("../update-geometry");e.exports=function(t){var e=o.get(t);n(t,e)}},{"../../lib/helper":6,"../instances":18,"../update-geometry":19}],11:[function(t,e){"use strict";function n(t,e){function n(n){var o=r+n,l=e.containerWidth-e.scrollbarXWidth;e.scrollbarXLeft=0>o?0:o>l?l:o;var s=i.toInt(e.scrollbarXLeft*(e.contentWidth-e.containerWidth)/(e.containerWidth-e.scrollbarXWidth));t.scrollLeft=s}var r=null,l=null,a=function(e){n(e.pageX-l),s(t),e.stopPropagation(),e.preventDefault()},c=function(){i.stopScrolling(t,"x"),e.event.unbind(e.ownerDocument,"mousemove",a)};e.event.bind(e.scrollbarX,"mousedown",function(n){l=n.pageX,r=i.toInt(o.css(e.scrollbarX,"left")),i.startScrolling(t,"x"),e.event.bind(e.ownerDocument,"mousemove",a),e.event.once(e.ownerDocument,"mouseup",c),n.stopPropagation(),n.preventDefault()})}function r(t,e){function n(n){var o=r+n,l=e.containerHeight-e.scrollbarYHeight;e.scrollbarYTop=0>o?0:o>l?l:o;var s=i.toInt(e.scrollbarYTop*(e.contentHeight-e.containerHeight)/(e.containerHeight-e.scrollbarYHeight));t.scrollTop=s}var r=null,l=null,a=function(e){n(e.pageY-l),s(t),e.stopPropagation(),e.preventDefault()},c=function(){i.stopScrolling(t,"y"),e.event.unbind(e.ownerDocument,"mousemove",a)};e.event.bind(e.scrollbarY,"mousedown",function(n){l=n.pageY,r=i.toInt(o.css(e.scrollbarY,"top")),i.startScrolling(t,"y"),e.event.bind(e.ownerDocument,"mousemove",a),e.event.once(e.ownerDocument,"mouseup",c),n.stopPropagation(),n.preventDefault()})}var o=t("../../lib/dom"),i=t("../../lib/helper"),l=t("../instances"),s=t("../update-geometry");e.exports=function(t){var e=l.get(t);n(t,e),r(t,e)}},{"../../lib/dom":3,"../../lib/helper":6,"../instances":18,"../update-geometry":19}],12:[function(t,e){"use strict";function n(t,e){function n(n,r){var o=t.scrollTop;if(0===n){if(!e.scrollbarYActive)return!1;if(0===o&&r>0||o>=e.contentHeight-e.containerHeight&&0>r)return!e.settings.wheelPropagation}var i=t.scrollLeft;if(0===r){if(!e.scrollbarXActive)return!1;if(0===i&&0>n||i>=e.contentWidth-e.containerWidth&&n>0)return!e.settings.wheelPropagation}return!0}var o=!1;e.event.bind(t,"mouseenter",function(){o=!0}),e.event.bind(t,"mouseleave",function(){o=!1});var l=!1;e.event.bind(e.ownerDocument,"keydown",function(s){if((!s.isDefaultPrevented||!s.isDefaultPrevented())&&o){var a=document.activeElement?document.activeElement:e.ownerDocument.activeElement;if(a){for(;a.shadowRoot;)a=a.shadowRoot.activeElement;if(r.isEditable(a))return}var c=0,u=0;switch(s.which){case 37:c=-30;break;case 38:u=30;break;case 39:c=30;break;case 40:u=-30;break;case 33:u=90;break;case 32:case 34:u=-90;break;case 35:u=s.ctrlKey?-e.contentHeight:-e.containerHeight;break;case 36:u=s.ctrlKey?t.scrollTop:e.containerHeight;break;default:return}t.scrollTop=t.scrollTop-u,t.scrollLeft=t.scrollLeft+c,i(t),l=n(c,u),l&&s.preventDefault()}})}var r=t("../../lib/helper"),o=t("../instances"),i=t("../update-geometry");e.exports=function(t){var e=o.get(t);n(t,e)}},{"../../lib/helper":6,"../instances":18,"../update-geometry":19}],13:[function(t,e){"use strict";function n(t,e){function n(n,r){var o=t.scrollTop;if(0===n){if(!e.scrollbarYActive)return!1;if(0===o&&r>0||o>=e.contentHeight-e.containerHeight&&0>r)return!e.settings.wheelPropagation}var i=t.scrollLeft;if(0===r){if(!e.scrollbarXActive)return!1;if(0===i&&0>n||i>=e.contentWidth-e.containerWidth&&n>0)return!e.settings.wheelPropagation}return!0}function o(t){var e=t.deltaX,n=-1*t.deltaY;return("undefined"==typeof e||"undefined"==typeof n)&&(e=-1*t.wheelDeltaX/6,n=t.wheelDeltaY/6),t.deltaMode&&1===t.deltaMode&&(e*=10,n*=10),e!==e&&n!==n&&(e=0,n=t.wheelDelta),[e,n]}function l(e,n){var r=t.querySelector("textarea:hover");if(r){var o=r.scrollHeight-r.clientHeight;if(o>0&&!(0===r.scrollTop&&n>0||r.scrollTop===o&&0>n))return!0;var i=r.scrollLeft-r.clientWidth;if(i>0&&!(0===r.scrollLeft&&0>e||r.scrollLeft===i&&e>0))return!0}return!1}function s(s){if(r.env.isWebKit||!t.querySelector("select:focus")){var c=o(s),u=c[0],d=c[1];l(u,d)||(a=!1,e.settings.useBothWheelAxes?e.scrollbarYActive&&!e.scrollbarXActive?(t.scrollTop=d?t.scrollTop-d*e.settings.wheelSpeed:t.scrollTop+u*e.settings.wheelSpeed,a=!0):e.scrollbarXActive&&!e.scrollbarYActive&&(t.scrollLeft=u?t.scrollLeft+u*e.settings.wheelSpeed:t.scrollLeft-d*e.settings.wheelSpeed,a=!0):(t.scrollTop=t.scrollTop-d*e.settings.wheelSpeed,t.scrollLeft=t.scrollLeft+u*e.settings.wheelSpeed),i(t),a=a||n(u,d),a&&(s.stopPropagation(),s.preventDefault()))}}var a=!1;"undefined"!=typeof window.onwheel?e.event.bind(t,"wheel",s):"undefined"!=typeof window.onmousewheel&&e.event.bind(t,"mousewheel",s)}var r=t("../../lib/helper"),o=t("../instances"),i=t("../update-geometry");e.exports=function(t){var e=o.get(t);n(t,e)}},{"../../lib/helper":6,"../instances":18,"../update-geometry":19}],14:[function(t,e){"use strict";function n(t,e){e.event.bind(t,"scroll",function(){o(t)})}var r=t("../instances"),o=t("../update-geometry");e.exports=function(t){var e=r.get(t);n(t,e)}},{"../instances":18,"../update-geometry":19}],15:[function(t,e){"use strict";function n(t,e){function n(){var t=window.getSelection?window.getSelection():document.getSelection?document.getSelection():"";return 0===t.toString().length?null:t.getRangeAt(0).commonAncestorContainer}function l(){a||(a=setInterval(function(){return o.get(t)?(t.scrollTop=t.scrollTop+c.top,t.scrollLeft=t.scrollLeft+c.left,void i(t)):void clearInterval(a)},50))}function s(){a&&(clearInterval(a),a=null),r.stopScrolling(t)}var a=null,c={top:0,left:0},u=!1;e.event.bind(e.ownerDocument,"selectionchange",function(){t.contains(n())?u=!0:(u=!1,s())}),e.event.bind(window,"mouseup",function(){u&&(u=!1,s())}),e.event.bind(window,"mousemove",function(e){if(u){var n={x:e.pageX,y:e.pageY},o={left:t.offsetLeft,right:t.offsetLeft+t.offsetWidth,top:t.offsetTop,bottom:t.offsetTop+t.offsetHeight};n.x<o.left+3?(c.left=-5,r.startScrolling(t,"x")):n.x>o.right-3?(c.left=5,r.startScrolling(t,"x")):c.left=0,n.y<o.top+3?(c.top=o.top+3-n.y<5?-5:-20,r.startScrolling(t,"y")):n.y>o.bottom-3?(c.top=n.y-o.bottom+3<5?5:20,r.startScrolling(t,"y")):c.top=0,0===c.top&&0===c.left?s():l()}})}var r=t("../../lib/helper"),o=t("../instances"),i=t("../update-geometry");e.exports=function(t){var e=o.get(t);n(t,e)}},{"../../lib/helper":6,"../instances":18,"../update-geometry":19}],16:[function(t,e){"use strict";function n(t,e,n,i){function l(n,r){var o=t.scrollTop,i=t.scrollLeft,l=Math.abs(n),s=Math.abs(r);if(s>l){if(0>r&&o===e.contentHeight-e.containerHeight||r>0&&0===o)return!e.settings.swipePropagation}else if(l>s&&(0>n&&i===e.contentWidth-e.containerWidth||n>0&&0===i))return!e.settings.swipePropagation;return!0}function s(e,n){t.scrollTop=t.scrollTop-n,t.scrollLeft=t.scrollLeft-e,o(t)}function a(){w=!0}function c(){w=!1}function u(t){return t.targetTouches?t.targetTouches[0]:t}function d(t){return t.targetTouches&&1===t.targetTouches.length?!0:t.pointerType&&"mouse"!==t.pointerType&&t.pointerType!==t.MSPOINTER_TYPE_MOUSE?!0:!1}function p(t){if(d(t)){y=!0;var e=u(t);b.pageX=e.pageX,b.pageY=e.pageY,g=(new Date).getTime(),null!==m&&clearInterval(m),t.stopPropagation()}}function f(t){if(!w&&y&&d(t)){var e=u(t),n={pageX:e.pageX,pageY:e.pageY},r=n.pageX-b.pageX,o=n.pageY-b.pageY;s(r,o),b=n;var i=(new Date).getTime(),a=i-g;a>0&&(v.x=r/a,v.y=o/a,g=i),l(r,o)&&(t.stopPropagation(),t.preventDefault())}}function h(){!w&&y&&(y=!1,clearInterval(m),m=setInterval(function(){return r.get(t)?Math.abs(v.x)<.01&&Math.abs(v.y)<.01?void clearInterval(m):(s(30*v.x,30*v.y),v.x*=.8,void(v.y*=.8)):void clearInterval(m)},10))}var b={},g=0,v={},m=null,w=!1,y=!1;n&&(e.event.bind(window,"touchstart",a),e.event.bind(window,"touchend",c),e.event.bind(t,"touchstart",p),e.event.bind(t,"touchmove",f),e.event.bind(t,"touchend",h)),i&&(window.PointerEvent?(e.event.bind(window,"pointerdown",a),e.event.bind(window,"pointerup",c),e.event.bind(t,"pointerdown",p),e.event.bind(t,"pointermove",f),e.event.bind(t,"pointerup",h)):window.MSPointerEvent&&(e.event.bind(window,"MSPointerDown",a),e.event.bind(window,"MSPointerUp",c),e.event.bind(t,"MSPointerDown",p),e.event.bind(t,"MSPointerMove",f),e.event.bind(t,"MSPointerUp",h)))}var r=t("../instances"),o=t("../update-geometry");e.exports=function(t,e,o){var i=r.get(t);n(t,i,e,o)}},{"../instances":18,"../update-geometry":19}],17:[function(t,e){"use strict";var n=t("../lib/class"),r=t("../lib/helper"),o=t("./instances"),i=t("./update-geometry"),l=t("./handler/click-rail"),s=t("./handler/drag-scrollbar"),a=t("./handler/keyboard"),c=t("./handler/mouse-wheel"),u=t("./handler/native-scroll"),d=t("./handler/selection"),p=t("./handler/touch");e.exports=function(t,e){e="object"==typeof e?e:{},n.add(t,"ps-container");var f=o.add(t);f.settings=r.extend(f.settings,e),l(t),s(t),c(t),u(t),d(t),(r.env.supportsTouch||r.env.supportsIePointer)&&p(t,r.env.supportsTouch,r.env.supportsIePointer),f.settings.useKeyboard&&a(t),i(t)}},{"../lib/class":2,"../lib/helper":6,"./handler/click-rail":10,"./handler/drag-scrollbar":11,"./handler/keyboard":12,"./handler/mouse-wheel":13,"./handler/native-scroll":14,"./handler/selection":15,"./handler/touch":16,"./instances":18,"./update-geometry":19}],18:[function(t,e,n){"use strict";function r(t){var e=this;e.settings=d.clone(a),e.containerWidth=null,e.containerHeight=null,e.contentWidth=null,e.contentHeight=null,e.isRtl="rtl"===s.css(t,"direction"),e.event=new c,e.ownerDocument=t.ownerDocument||document,e.scrollbarXRail=s.appendTo(s.e("div","ps-scrollbar-x-rail"),t),e.scrollbarX=s.appendTo(s.e("div","ps-scrollbar-x"),e.scrollbarXRail),e.scrollbarXActive=null,e.scrollbarXWidth=null,e.scrollbarXLeft=null,e.scrollbarXBottom=d.toInt(s.css(e.scrollbarXRail,"bottom")),e.isScrollbarXUsingBottom=e.scrollbarXBottom===e.scrollbarXBottom,e.scrollbarXTop=e.isScrollbarXUsingBottom?null:d.toInt(s.css(e.scrollbarXRail,"top")),e.railBorderXWidth=d.toInt(s.css(e.scrollbarXRail,"borderLeftWidth"))+d.toInt(s.css(e.scrollbarXRail,"borderRightWidth")),e.railXMarginWidth=d.toInt(s.css(e.scrollbarXRail,"marginLeft"))+d.toInt(s.css(e.scrollbarXRail,"marginRight")),e.railXWidth=null,e.scrollbarYRail=s.appendTo(s.e("div","ps-scrollbar-y-rail"),t),e.scrollbarY=s.appendTo(s.e("div","ps-scrollbar-y"),e.scrollbarYRail),e.scrollbarYActive=null,e.scrollbarYHeight=null,e.scrollbarYTop=null,e.scrollbarYRight=d.toInt(s.css(e.scrollbarYRail,"right")),e.isScrollbarYUsingRight=e.scrollbarYRight===e.scrollbarYRight,e.scrollbarYLeft=e.isScrollbarYUsingRight?null:d.toInt(s.css(e.scrollbarYRail,"left")),e.scrollbarYOuterWidth=e.isRtl?d.outerWidth(e.scrollbarY):null,e.railBorderYWidth=d.toInt(s.css(e.scrollbarYRail,"borderTopWidth"))+d.toInt(s.css(e.scrollbarYRail,"borderBottomWidth")),e.railYMarginHeight=d.toInt(s.css(e.scrollbarYRail,"marginTop"))+d.toInt(s.css(e.scrollbarYRail,"marginBottom")),e.railYHeight=null}function o(t){return"undefined"==typeof t.dataset?t.getAttribute("data-ps-id"):t.dataset.psId}function i(t,e){"undefined"==typeof t.dataset?t.setAttribute("data-ps-id",e):t.dataset.psId=e}function l(t){"undefined"==typeof t.dataset?t.removeAttribute("data-ps-id"):delete t.dataset.psId}var s=t("../lib/dom"),a=t("./default-setting"),c=t("../lib/event-manager"),u=t("../lib/guid"),d=t("../lib/helper"),p={};n.add=function(t){var e=u();return i(t,e),p[e]=new r(t),p[e]},n.remove=function(t){delete p[o(t)],l(t)},n.get=function(t){return p[o(t)]}},{"../lib/dom":3,"../lib/event-manager":4,"../lib/guid":5,"../lib/helper":6,"./default-setting":8}],19:[function(t,e){"use strict";function n(t,e){return t.settings.minScrollbarLength&&(e=Math.max(e,t.settings.minScrollbarLength)),t.settings.maxScrollbarLength&&(e=Math.min(e,t.settings.maxScrollbarLength)),e}function r(t,e){var n={width:e.railXWidth};n.left=e.isRtl?t.scrollLeft+e.containerWidth-e.contentWidth:t.scrollLeft,e.isScrollbarXUsingBottom?n.bottom=e.scrollbarXBottom-t.scrollTop:n.top=e.scrollbarXTop+t.scrollTop,i.css(e.scrollbarXRail,n);var r={top:t.scrollTop,height:e.railYHeight};e.isScrollbarYUsingRight?r.right=e.isRtl?e.contentWidth-t.scrollLeft-e.scrollbarYRight-e.scrollbarYOuterWidth:e.scrollbarYRight-t.scrollLeft:r.left=e.isRtl?t.scrollLeft+2*e.containerWidth-e.contentWidth-e.scrollbarYLeft-e.scrollbarYOuterWidth:e.scrollbarYLeft+t.scrollLeft,i.css(e.scrollbarYRail,r),i.css(e.scrollbarX,{left:e.scrollbarXLeft,width:e.scrollbarXWidth-e.railBorderXWidth}),i.css(e.scrollbarY,{top:e.scrollbarYTop,height:e.scrollbarYHeight-e.railBorderYWidth})}var o=t("../lib/class"),i=t("../lib/dom"),l=t("../lib/helper"),s=t("./instances");e.exports=function(t){var e=s.get(t);e.containerWidth=t.clientWidth,e.containerHeight=t.clientHeight,e.contentWidth=t.scrollWidth,e.contentHeight=t.scrollHeight,t.contains(e.scrollbarXRail)||i.appendTo(e.scrollbarXRail,t),t.contains(e.scrollbarYRail)||i.appendTo(e.scrollbarYRail,t),!e.settings.suppressScrollX&&e.containerWidth+e.settings.scrollXMarginOffset<e.contentWidth?(e.scrollbarXActive=!0,e.railXWidth=e.containerWidth-e.railXMarginWidth,e.scrollbarXWidth=n(e,l.toInt(e.railXWidth*e.containerWidth/e.contentWidth)),e.scrollbarXLeft=l.toInt(t.scrollLeft*(e.railXWidth-e.scrollbarXWidth)/(e.contentWidth-e.containerWidth))):(e.scrollbarXActive=!1,e.scrollbarXWidth=0,e.scrollbarXLeft=0,t.scrollLeft=0),!e.settings.suppressScrollY&&e.containerHeight+e.settings.scrollYMarginOffset<e.contentHeight?(e.scrollbarYActive=!0,e.railYHeight=e.containerHeight-e.railYMarginHeight,e.scrollbarYHeight=n(e,l.toInt(e.railYHeight*e.containerHeight/e.contentHeight)),e.scrollbarYTop=l.toInt(t.scrollTop*(e.railYHeight-e.scrollbarYHeight)/(e.contentHeight-e.containerHeight))):(e.scrollbarYActive=!1,e.scrollbarYHeight=0,e.scrollbarYTop=0,t.scrollTop=0),e.scrollbarXLeft>=e.railXWidth-e.scrollbarXWidth&&(e.scrollbarXLeft=e.railXWidth-e.scrollbarXWidth),e.scrollbarYTop>=e.railYHeight-e.scrollbarYHeight&&(e.scrollbarYTop=e.railYHeight-e.scrollbarYHeight),r(t,e),o[e.scrollbarXActive?"add":"remove"](t,"ps-active-x"),o[e.scrollbarYActive?"add":"remove"](t,"ps-active-y")}},{"../lib/class":2,"../lib/dom":3,"../lib/helper":6,"./instances":18}],20:[function(t,e){"use strict";var n=t("../lib/dom"),r=t("./instances"),o=t("./update-geometry");e.exports=function(t){var e=r.get(t);n.css(e.scrollbarXRail,"display","none"),n.css(e.scrollbarYRail,"display","none"),o(t),n.css(e.scrollbarXRail,"display","block"),n.css(e.scrollbarYRail,"display","block")}},{"../lib/dom":3,"./instances":18,"./update-geometry":19}]},{},[1]);
;/*})'"*/;/*})'"*/
(function($, Drupal) {
  Drupal.behaviors.RelaYoutubeEmbed = {
    attach: function(context, settings) {

      $('body', context).once('youtube-embed', function() {
        function hideControl() {
          $('.video-sound-toggle').fadeOut();
        }
        if (typeof settings.relaVideo !== 'undefined') {
          if (settings.relaVideo.videoSource == 'youtube') {

            if (settings.relaVideo.sound == 'muted') {
              $('.video-sound-toggle').hide();
            }
            var videoID = settings.relaVideo.videoID;
            var tag = document.createElement('script');
            tag.src = 'https://www.youtube.com/player_api';
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            var tv,
              playerDefaults = {
                autoplay: 0,
                autohide: 1,
                modestbranding: 0,
                rel: 0,
                showinfo: 0,
                controls: 0,
                disablekb: 1,
                enablejsapi: 1,
                iv_load_policy: 3,
                vq: 'hd1080'

              };

            var startTime = 0.5;
            if (videoID == 'ohhUuVPFFUY') {
              startTime = 0.5
            }
            var vid = [{
              'videoId': videoID,
              'startSeconds': startTime
            }];

            window.onYouTubePlayerAPIReady = function() {
              tv = new YT.Player('tv', {
                events: {
                  'onReady': onPlayerReady,
                  'onStateChange': onPlayerStateChange
                },
                playerVars: playerDefaults
              });

              vidRescale();

            }

            function onPlayerReady() {
              tv.loadVideoById(vid[0]);

              if (settings.relaVideo.sound == 'muted') {
                tv.mute();
                $('.video-sound-toggle').hide();
                return;
              }
              $('.overlay-trigger', context).click(function() {
                tv.mute();
              });

              // // var promise = document.querySelector('#verifyAudio').play();
              // if (promise !== undefined) {
              //   promise.then(_ => {
              //     // Autoplay started!
              //   }).catch(error => {
              //     // Autoplay was prevented.
              //     // Show a "Play" button so that user can start playback.
              //     tv.mute();
              //     $('.video-sound-toggle').removeClass('hidden').addClass('animated');

              //     setTimeout(hideControl, 8000);
              //   });

              Promise.resolve(document.querySelector('#verifyAudio').play()).then(function() {
                //Returning a thenable from a handler is automatically
                //cast to a trusted Promise as per Promises/A+ specification
                $('.video-sound-toggle').hide();

              }).then(function() {

              }).catch(function(e) {
                tv.mute();
                $('.video-sound-toggle').removeClass('hidden').addClass('animated');
                setTimeout(hideControl, 8000);
                console.log(e);
              });



            }

            function onPlayerStateChange(e) {

              if (e.data === 1) {
                $('#tv').addClass('active');
              } else if (e.data === 0) {
                tv.seekTo(vid[0].startSeconds)
              }
            }

            function vidRescale() {

              var w = $('.tv .screen').parent().width(),
                h = $('.tv .screen').parent().height() + 150;

              if (w / h > 16 / 9) {
                tv.setSize(w, w / 16 * 9);
                $('.tv .screen').css({
                  'left': '0px'
                });
              } else {
                tv.setSize(h / 9 * 16, h);
                $('.tv .screen').css({
                  'left': -($('.tv .screen').outerWidth() - w) / 2
                });
              }
            }

            $(window).on('resize', function() {
              if (tv) {
                vidRescale();
              }
            });

            $('.hi span').on('click', function() {
              $('#tv').toggleClass('mute');
              if ($('#tv').hasClass('mute')) {
                tv.mute();
              } else {
                tv.unMute();
              }
            });

            $('.video-sound-toggle').click(function() {
              if ($(this).hasClass('muted')) {
                tv.unMute();
                setTimeout(hideControl, 1000);
              } else {
                tv.mute();
              }

              $(this).toggleClass('muted');
            });

          } // end VideoID definition check.
        } // Youtube check
        if (typeof settings.relaVideo !== 'undefined') {
          if (settings.relaVideo.videoSource == 'vimeo') {
            $('.screen').addClass('active');

            var playerID = '#vimeo-fullscreen';
            var playerIframe = $(playerID)[0];
            var player = new Vimeo.Player(playerIframe);
            if (settings.relaVideo.sound == 'muted') {
              player.setVolume(0);
              $('.video-sound-toggle').hide();
            }
            vimeoRescale();
            player.play().then(function() {
              // the video was played
              $('.vimeo-play-btn .video-status-icon').removeClass('fa-play').addClass('fa-pause');
              $('.vimeo-play-btn .btn-text').text('Pause');
              $('.vimeo-play-btn').attr('data-status', 'playing');

            }).catch(function(error) {
              switch (error.name) {
                case 'PasswordError':
                  // the video is password-protected and the viewer needs to enter the
                  // password first
                  console.log('Pass error');
                  break;

                case 'PrivacyError':
                  console.log('Vimeo Video is private. Cannot play');
                  break;

                default:
                  console.log(error.name);
                  break;
              }
            });

            $('.vimeo-play-btn').click(function(){
              var status = $(this).attr('data-status');
              if (status == 'playing') {
                player.pause();
                $('.vimeo-play-btn .video-status-icon').removeClass('fa-pause').addClass('fa-play');
                $('.vimeo-play-btn .btn-text').text('Play');
                $('.vimeo-play-btn').attr('data-status', 'paused');
              }
              if (status == 'paused') {
                player.play();
                $('.vimeo-play-btn .video-status-icon').removeClass('fa-play').addClass('fa-pause');
                $('.vimeo-play-btn .btn-text').text('Pause');
                $('.vimeo-play-btn').attr('data-status', 'playing');
              }

            });

            // var promise = document.querySelector('#verifyAudio').play();
            // if (promise !== undefined) {
            //   promise.then(_ => {
            //     // Autoplay started! But because of a vimeo bug, we need to
            //     // always show the button and mute it.
            //     player.setVolume(0);
            //     $('.video-sound-toggle').removeClass('hidden').addClass('animated');
            //     setTimeout(hideControl, 10000);
            //   }).catch(error => {
            //     // Autoplay was prevented.
            //     // Show a "Play" button so that user can start playback.
            //     player.setVolume(0);
            //     $('.video-sound-toggle').removeClass('hidden').addClass('animated');
            //     setTimeout(hideControl, 8000);
            //   });
            // }


            // Need this here cuz ie 11. Useing bluebird promise library.
            Promise.resolve(document.querySelector('#verifyAudio').play()).then(function() {
              // Autoplay started! But because of a vimeo bug, we need to
              // always show the button and mute it.
              player.setVolume(0);
              $('.video-sound-toggle').removeClass('hidden').addClass('animated');
              setTimeout(hideControl, 10000);

            }).then(function() {

            }).catch(function(e) {
              // Autoplay was prevented.
              // Show a "Play" button so that user can start playback.
              player.setVolume(0);
              $('.video-sound-toggle').removeClass('hidden').addClass('animated');
              setTimeout(hideControl, 8000);
            });

            $('.video-sound-toggle').click(function() {
              if ($(this).hasClass('muted')) {
                player.setMuted(false);
                player.setVolume(1);
                setTimeout(hideControl, 1000);
              } else {
                player.setVolume(0);
              }

              $(this).toggleClass('muted');
            });

            function vimeoRescale() {
              var w = $('.tv .screen').parent().width(),
                h = $('.tv .screen').parent().height() + 200;

              if (w / h > 16 / 9) {
                $(playerID).width(w).height(w / 16 * 9);
                $(playerID).css({
                  'left': '0px'
                });
              } else {
                $(playerID).width(h / 9 * 16).height(h);
                $(playerID).css({
                  'left': -($(playerID).outerWidth() - w) / 2
                });
              }
            } // End viemo rescale
            $(window).on('resize', function() {
              vimeoRescale();
            });
          } // End settings check.
        } // Emd Vimeo
      }); // end body

    } //end attach
  }
})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
(function($, Drupal, undefined) {

  Drupal.behaviors.LenisSmoothScroll = {
    attach: function(context, settings) {
      if (Drupal.settings.propertySmoothScroll !== undefined) {
        if (Drupal.settings.propertySmoothScroll == true) {
          //https://github.com/studio-freight/lenis
          // Anything that is fixed full screen like overlays and shit
          // need to be in this list.
          var preventLenisSelectors = [
            '#overlay-content-extra',
            '#overlay-description',
            '#right-edit-overlay',
            '#ajax-content-overlay',
            '#side-menu',
            '.lenis-prevent'

          ]
          $.each(preventLenisSelectors, function(index, selector) {
            var $elements = $(selector);
            if ($elements.length) {
              $elements.attr('data-lenis-prevent', '');
            }
          });

          const lenis = new Lenis()

          function raf(time) {
            lenis.raf(time)
            requestAnimationFrame(raf)
          }

          requestAnimationFrame(raf);

        }
      }
    }
  }

 Drupal.behaviors.mobileDetect = {
    attach: function(context, settings) {

      if (Drupal.relaGlobalFunctions.isMobile()) {
        $('.full-bg').css('background-attachment', 'scroll');
      }
      else {
        //We can only init  skrollr on desktop cuz it locks the body on mobile
        if (typeof skrollr != 'undefined') {
          skrollr.init({
            forceHeight: false
          });
        }
      }
    }
  }

  Drupal.behaviors.propertySetButtonTextColor =  {
    attach: function(context, settings) {
      if (Drupal.settings.propertyTemplateSettings !== undefined) {
        $('body', context).on('contact-form-loaded', function() {
          setTimeout(function() {
            var submitBGColor = $('button[name="op"]').css("background-color");
            var textColor = getTextColor(submitBGColor);
            $('.form-submit').css("color", textColor);
          }, 100);
        });

        function getTextColor(rgba){
          rgba = rgba.match(/\d+/g);
          if((rgba[0]*0.299)+(rgba[1]*0.587)+(rgba[2]*0.114)>186) {
            return 'black';
          }
          else {
            return 'white';
          }
        }
      }
    }
  }

  Drupal.behaviors.floorplanZoom = {
    attach: function(context, settings) {
      $('.easyzoom--overlay').once().click(function(){
        $('.hotspot-viewer').removeClass('zoom-active');
      });

      $('.hotspot-container.zoomable-1 .field-name-field-doc-file').once().click(function() {
        $wrapper = $(this).parent().parent().parent();//('.hotspot-container');
        $isActive = $wrapper.hasClass('zoom-active');

        if (!$isActive) {
          $wrapper.addClass('zoom-active');
        }
        else {
          $wrapper.removeClass('zoom-active');

        }
      });
    }
  }


  Drupal.behaviors.propertyVtourGallery = {
    attach: function(context, settings) {
      $('.vtab', context).click(function() {


        var tourURL = $(this).data('tour-url');
        $('.vtab-active').removeClass('vtab-active');
        $(this).addClass('vtab-active');

        $('.vtour-frame').attr('src', tourURL);
        return false;
      });
    }
  }

  var getaudio = $('#property-audio')[0];

  function playAudio() {
    $('#property-audio').addClass('on');
    $('#bars').addClass('playing');
    $('#bars').removeClass('paused');

    getaudio.play();
  }

  function pauseAudio() {
    $('#property-audio').removeClass('on');
    $('#bars').removeClass('playing');
    $('#bars').addClass('paused');

    getaudio.pause();
  }

  $(document).ready(function() {

    // Check for Audio.

    if ($('#property-audio').length) {
      getaudio = $('#property-audio')[0];

      // var promise = document.querySelector('audio').play();
      // if (promise !== undefined) {
      //   promise.catch(error => {
      //     // Auto-play was prevented
      //     // Show a UI element to let the user manually start playback
      //     pauseAudio();

      //     var prompt = '<div class="audio-prompt bounceInLeft">Click for the full experience</div>';
      //     $('#bars').after(prompt);
      //     $('.audio-prompt').addClass('animated');
      //     setTimeout(function() {
      //       $('.audio-prompt').removeClass('bounceInLeft').addClass('bounceOutLeft');
      //     }, 4000);

      //   }).then(() => {
      //     // Auto-play started
      //   });
      // }

      Promise.resolve(document.querySelector('audio').play()).then(function() {
        //Returning a thenable from a handler is automatically
        //cast to a trusted Promise as per Promises/A+ specification

      }).then(function() {

      }).catch(function(e) {
        pauseAudio();

        var prompt = '<div class="audio-prompt bounceInLeft text-black">Click for the full audio experience</div>';
        $('#bars').after(prompt);
        $('.audio-prompt').addClass('animated');
        setTimeout(function() {
          $('.audio-prompt').removeClass('bounceInLeft').addClass('bounceOutLeft');
        }, 4000);
        console.log(e);
      });
    }

  });


  Drupal.behaviors.propertyGalleryPID = {
    attach: function(context, settings) {
      $('.view-id-property_gallery', context).each(function() {
        $view = $(this);
        $images = $view.find('.views-row');
        var count = $images.length;
        var i;
        for (i = 0; i < count; i++) {
          $images.eq(i).find('[data-pid]').attr('data-pid', i);
        }
      });

      // Loop through custom preview images and match up the position of
      // the image in the gallery array so it opens to that image.
      if (typeof settings.RelaProperty.imageListPS !== 'undefined') {
        var psImages = Drupal.settings.RelaProperty.imageListPS;
        var propertyNid = Drupal.settings.RelaProperty.nid;
        var imageCount = psImages[propertyNid].length;
        $('[data-ps-url]', context).each(function(){
          for (i = 0; i < imageCount; i++) {
            if ($(this).attr('data-ps-url') == psImages[propertyNid][i]['url']) {
              $(this).attr('data-pid', i);
            }
          }
        })
      }

      // Loop through custom preview images and match up the position of
      // the image in the gallery array so it opens to that image.
      if (
        typeof settings.RelaPropertyFloorplan !== 'undefined' &&
        typeof settings.RelaPropertyFloorplan.floorplanListPS !== 'undefined'
        ) {
        var fpImages = Drupal.settings.RelaPropertyFloorplan.floorplanListPS;
        var imageCount = fpImages.length;
        $('[data-ps-fp-url]', context).each(function(){
          for (i = 0; i < imageCount; i++) {
            if ($(this).attr('data-ps-fp-url') == fpImages[i]['url']) {
              $(this).attr('data-pid', i);
            }
          }
        })
      }
    }
  }


  Drupal.behaviors.propertyAudio = {
    attach: function(context, settings) {

      $('body', context).on('click', '.audio-prompt', function() {
        $('#bars').click();
      });
      $('#bars', context).click(function() {
        if ($('#property-audio').hasClass('on')) {
          pauseAudio();
        } else {
          playAudio();
        }
      });

      $('.overlay-trigger', context).click(function() {
        if ($('#property-audio').length) {
          if ($('#property-audio').hasClass('on')) {
            pauseAudio();
            $('#property-audio').addClass('overlay-pause');
          }
        }

        if (typeof settings.relaVideo !== 'undefined') {
          if (settings.relaVideo.videoSource == 'vimeo') {
            var playerID = '#vimeo-fullscreen';
            var playerIframe = $(playerID)[0];
            var player = new Vimeo.Player(playerIframe);
            player.setVolume(0)
          }
        }

      });

      $('.overlay-close', context).click(function() {
        if ($('.overlay-pause', context).length) {
          $('.overlay-pause').removeClass('overlay-pause');
          playAudio();
        }
      });

      // Social links JS.
      $('.field-type-social-links-field .field-label', context).click(function() {
        $(this).parent().find('.social-links').toggleClass('active');
      });

    }
  }



  // Drupal.behaviors.exitIntent = {
  //   attach: function(context, settings) {

  //     var pid = Drupal.settings.exitIntent.pid || 0;

  //     if (pid > 0) {
  //       // $('.lead-pop-exit', context).each(function(){
  //       //   $(function() {
  //       //     ddexitpop.init({
  //       //       contentsource: ['id', 'ph'],
  //       //       fxclass: 'random',
  //       //       displayfreq: 'always',
  //       //       onddexitpop: function($popup) {
  //       //         $('.lead-pop-exit').click();
  //       //       }
  //       //     })
  //       //   });
  //       // })

  //     }
  //   }
  // }

  Drupal.behaviors.vTourActivate = {
    attach: function(context, settings) {

      $('.vtour-tabs .tour-cover-image').unbind('click');
      $('.vtour-tabs .tour-cover-image').click(function() {
        $this = $(this);
        $vtour = $this.hide().prev();
        var src = $vtour.attr('src');
        if (~src.indexOf('matterport.com')) {
          $vtour.attr('src', src + '&play=1');
        }
      });
    }
  }

  Drupal.behaviors.sbowcaseTabs = {
    attach: function(context, settings) {
      if (('#showcase').length > 0) {

        // setup for intial load
        $('.showcase-tabs-wrapper', context).find('.showcase-tab:first').once('showCaseTabInit').addClass('active');
        $('#showcase', context).find('.showcase-content:first').once('showCaseTabInit').addClass('active');
        var sectionHeight = $('.showcase-content.active').find('.showcase-section').height() + 100;

        //$('.showcase-content.active').parent().css('height', sectionHeight + 'px');

        $('.showcase-tab', context).on('click', function() {
          var $tab = $(this);
          $('#showcase .active').each(function() {
            $(this).removeClass('active');
          });
          var tabID = "#" + $(this).attr('tab-data');
          //sectionHeight = $(tabID).find('.showcase-section').height() + 100;

          $(this).addClass('active');

          $(tabID).addClass('active');
          //$('.showcase-contents-wrapper').css('height', sectionHeight + 'px');
          if ($tab.hasClass('resize-content')) {

            window.dispatchEvent(new Event('resize'));
          }
          return false;
        });
      }

    }
  }


  Drupal.behaviors.vTourLazy = {
    attach: function(context, settings) {
      $('#frame-vtour').load(function(e) {
        if (!$(this).hasClass('vtour-loaded-processed')) {
          $(this).addClass('vtour-loaded-processed');
          setTimeout(function() {
            window.scrollTo(0, 0);
          }, 1);
        }
      });
    }

  }
  // Drupal.behaviors.owlVideoGallery = {
  //   attach: function(context, settings) {
  //      if (Drupal.settings.owlVideo) {
  //        var setNav = false;
  //        var navItems = []
  //        if (Drupal.settings.owlVideo.count > 1) {
  //          setNav = true;
  //          navItems = ['<span class="icon icon-arrow-left valign-sub"></span> ', '<span class="icon icon-arrow-right valign-sub"></span>'];
  //        }
  //        var owlVideo = $(".owl-gallery-ryne-videos .view-content", context).owlCarousel({
  //          loop: false,
  //          items: 1,
  //          pagination: false,
  //          nav: setNav,
  //          navText: navItems,

  //        });

  //        $('.owl-vid-wrapper .play-button').on('click', function() {
  //          var videoURL = $(this).attr('data-video-url');
  //          console.log(videoURL);
  //          embedIframe = '<iframe width="100%" height="100%" src="' + videoURL + '" frameborder="0" allowfullscreen></iframe>';
  //          $(this).parent().html(embedIframe);
  //        });
  //      }
  //    }
  //  }
  //

  Drupal.behaviors.quickfit = {
    attach: function(context, settings) {
      $('.quickfit:visible').each(function() {
        $this = $(this);
        $span = $this.find('span');
        var divWidth = $this.width(),
          spanWidth = $span.width(),
          padding = parseInt($this.attr('data-padding')) || 20,
          curFontSize = parseInt($this.css('font-size')) || 16,
          maxFontSize = parseInt($this.attr('data-max-font'));
        if (spanWidth + (padding * 2) > divWidth) {
          while (spanWidth + (padding * 2) > divWidth) {
            curFontSize -= 3;
            $this.css('font-size', curFontSize + 'px');
            spanWidth = $span.width();

            if (curFontSize < 1) {
              return;
            }
          }
          curFontSize += 3;
          $this.css('font-size', curFontSize + 'px');
        } else if (spanWidth + (padding * 2) < divWidth) {
          while (spanWidth + (padding * 2) < divWidth) {
            console.log('sljda');
            curFontSize += 3;
            $this.css('font-size', curFontSize + 'px');
            spanWidth = $span.width();

            if (maxFontSize != 0 && curFontSize > maxFontSize) {
              return;
            }
          }
          while (spanWidth + (padding * 2) > divWidth) {
            curFontSize -= 3;
            $this.css('font-size', curFontSize + 'px');
            spanWidth = $span.width();
            if (curFontSize < 1) {
              return;
            }
          }
          curFontSize -= 3;
          $this.css('font-size', curFontSize + 'px');
        }
      });
    }
  }


  Drupal.behaviors.propertyPass = {
    attach: function(context, settings) {

      // check for cookie.
      // Need to do something if user changes passwords, so cookie
      // needs to be some type of hashed value that checks against live
      // pass value.

      $("#prop-pass-check", context).click(function() {


        if (settings.relaPPSSHash !== undefined) {
          if ($.cookie('rela_ppss') === null) {
            showPassPop();
          } else {
            var cooky = $.cookie('rela_ppss');
            if (cooky !== settings.relaPPSSHash) {
              showPassPop();
            }
          }
        }
      });

      function showPassPop() {
        $('body').addClass('ppss-required');
        $('#ajax-content-overlay').show();
        $('.overlay-header').hide();

        var $show = $('#prop-pass-show');

        $('#overlay-content-static').show();
        $('body').addClass('overlay-open');

        if ($show.attr('data-static-content')) {
          var target = $show.attr('data-static-content');
          $('#' + target).show().detach().appendTo('#overlay-content-static');
        }
        setTimeout(function() {
          $('#prop-pass-show').click();
        }, 200)


      }


      $('#prop-pass-show', context).click(function() {


      });
    }
  }

  Drupal.behaviors.multiGallery = {
    attach: function(context, settings) {
      var icon = '';

      if (typeof settings.multiGallerylazyloader !== 'undefined') {
        icon = Drupal.settings.multiGallerylazyloader.icon;
      }

      if ($('.multi-gallery-overlay').length) {

        $('.property-overlay-link-photos a').removeAttr('data').addClass('multi-gallery-open');
        $('.sticky-link-photos a').removeAttr('data').addClass('multi-gallery-open');



        $(".multi-gallery-image .inner", context).each(function(i) {
          $(this).parent().attr("data-pid", ++i - 1);

        });
      }

      $('.multi-gallery-open', context).click(function() {
        $('body').css('overflow', 'hidden').addClass('multi-is-gallery-open');
        $('.outside-menu-toggle.open').click();
        $('.multi-gallery-overlay').fadeIn();
        $(".multi-gallery-image .inner", context).each(function(i) {
          if (!$(this).hasClass('img-processed')) {
            var target = $(this);
            $('<img/>').attr('src', $(this).data('src')).on('load', function() {
              $(this).remove(); // prevent memory leaks as @benweet suggested
              target.css('background-image', "url(" + target.data('src') + ")").addClass('img-processed');
            });

          }
        });

        var nidTarget = $(this).attr('data-nid');
        var target = $('#gallery-' + nidTarget);
        $('.multi-gallery-overlay').scrollTop(0);
        if(target.length > 0) {
          $('.multi-gallery-overlay').animate({
            scrollTop: $(target).offset().top - $('.multi-gallery-overlay').offset().top,
          }, 1000);
        }
        return false;
      });

      $('.multi-gallery-close', context).click(function() {
        $('.multi-gallery-overlay').fadeOut();
        $('body').css('overflow', '').removeClass('multi-is-gallery-open');;
      });

      $('.multi-gallery-image', context).click(function() {
        $('.multi-gallery-overlay').fadeOut();
        $('body').css('overflow', '').removeClass('multi-is-gallery-open');;
      });

      $('.multi-gallery-overlay .gallery-item-preview', context).click(function() {
        var nidTarget = $(this).data('nid');

        var target = $('#gallery-' + nidTarget);

        $('.multi-gallery-overlay').animate({
          scrollTop: $(target).position().top,
        }, 1000);
      });
    }
  }
})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
/*!
 * Packery PACKAGED v2.1.1
 * 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(t, e) {
  "use strict";
  "function" == typeof define && define.amd ? define("jquery-bridget/jquery-bridget", ["jquery"], function(i) {
    e(t, i)
  }) : "object" == typeof module && module.exports ? module.exports = e(t, require("jquery")) : t.jQueryBridget = e(t, t.jQuery)
}(window, function(t, e) {
  "use strict";

  function i(i, s, a) {
    function h(t, e, n) {
      var o, s = "$()." + i + '("' + e + '")';
      return t.each(function(t, h) {
        var u = a.data(h, i);
        if (!u) return void r(i + " not initialized. Cannot call methods, i.e. " + s);
        var c = u[e];
        if (!c || "_" == e.charAt(0)) return void r(s + " is not a valid method");
        var d = c.apply(u, n);
        o = void 0 === o ? d : o
      }), void 0 !== o ? o : t
    }

    function u(t, e) {
      t.each(function(t, n) {
        var o = a.data(n, i);
        o ? (o.option(e), o._init()) : (o = new s(n, e), a.data(n, i, o))
      })
    }
    a = a || e || t.jQuery, a && (s.prototype.option || (s.prototype.option = function(t) {
      a.isPlainObject(t) && (this.options = a.extend(!0, this.options, t))
    }), a.fn[i] = function(t) {
      if ("string" == typeof t) {
        var e = o.call(arguments, 1);
        return h(this, t, e)
      }
      return u(this, t), this
    }, n(a))
  }

  function n(t) {
    !t || t && t.bridget || (t.bridget = i)
  }
  var o = Array.prototype.slice,
    s = t.console,
    r = "undefined" == typeof s ? function() {} : function(t) {
      s.error(t)
    };
  return n(e || t.jQuery), i
}),
function(t, e) {
  "use strict";
  "function" == typeof define && define.amd ? define("get-size/get-size", [], function() {
    return e()
  }) : "object" == typeof module && module.exports ? module.exports = e() : t.getSize = e()
}(window, function() {
  "use strict";

  function t(t) {
    var e = parseFloat(t),
      i = -1 == t.indexOf("%") && !isNaN(e);
    return i && e
  }

  function e() {}

  function i() {
    for (var t = {
        width: 0,
        height: 0,
        innerWidth: 0,
        innerHeight: 0,
        outerWidth: 0,
        outerHeight: 0
      }, e = 0; u > e; e++) {
      var i = h[e];
      t[i] = 0
    }
    return t
  }

  function n(t) {
    var e = getComputedStyle(t);
    return e || a("Style returned " + e + ". Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1"), e
  }

  function o() {
    if (!c) {
      c = !0;
      var e = document.createElement("div");
      e.style.width = "200px", e.style.padding = "1px 2px 3px 4px", e.style.borderStyle = "solid", e.style.borderWidth = "1px 2px 3px 4px", e.style.boxSizing = "border-box";
      var i = document.body || document.documentElement;
      i.appendChild(e);
      var o = n(e);
      s.isBoxSizeOuter = r = 200 == t(o.width), i.removeChild(e)
    }
  }

  function s(e) {
    if (o(), "string" == typeof e && (e = document.querySelector(e)), e && "object" == typeof e && e.nodeType) {
      var s = n(e);
      if ("none" == s.display) return i();
      var a = {};
      a.width = e.offsetWidth, a.height = e.offsetHeight;
      for (var c = a.isBorderBox = "border-box" == s.boxSizing, d = 0; u > d; d++) {
        var f = h[d],
          l = s[f],
          p = parseFloat(l);
        a[f] = isNaN(p) ? 0 : p
      }
      var g = a.paddingLeft + a.paddingRight,
        m = a.paddingTop + a.paddingBottom,
        y = a.marginLeft + a.marginRight,
        v = a.marginTop + a.marginBottom,
        _ = a.borderLeftWidth + a.borderRightWidth,
        x = a.borderTopWidth + a.borderBottomWidth,
        b = c && r,
        E = t(s.width);
      E !== !1 && (a.width = E + (b ? 0 : g + _));
      var T = t(s.height);
      return T !== !1 && (a.height = T + (b ? 0 : m + x)), a.innerWidth = a.width - (g + _), a.innerHeight = a.height - (m + x), a.outerWidth = a.width + y, a.outerHeight = a.height + v, a
    }
  }
  var r, a = "undefined" == typeof console ? e : function(t) {
      console.error(t)
    },
    h = ["paddingLeft", "paddingRight", "paddingTop", "paddingBottom", "marginLeft", "marginRight", "marginTop", "marginBottom", "borderLeftWidth", "borderRightWidth", "borderTopWidth", "borderBottomWidth"],
    u = h.length,
    c = !1;
  return s
}),
function(t, e) {
  "function" == typeof define && define.amd ? define("ev-emitter/ev-emitter", e) : "object" == typeof module && module.exports ? module.exports = e() : t.EvEmitter = e()
}(this, function() {
  function t() {}
  var e = t.prototype;
  return e.on = function(t, e) {
    if (t && e) {
      var i = this._events = this._events || {},
        n = i[t] = i[t] || [];
      return -1 == n.indexOf(e) && n.push(e), this
    }
  }, e.once = function(t, e) {
    if (t && e) {
      this.on(t, e);
      var i = this._onceEvents = this._onceEvents || {},
        n = i[t] = i[t] || {};
      return n[e] = !0, this
    }
  }, e.off = function(t, e) {
    var i = this._events && this._events[t];
    if (i && i.length) {
      var n = i.indexOf(e);
      return -1 != n && i.splice(n, 1), this
    }
  }, e.emitEvent = function(t, e) {
    var i = this._events && this._events[t];
    if (i && i.length) {
      var n = 0,
        o = i[n];
      e = e || [];
      for (var s = this._onceEvents && this._onceEvents[t]; o;) {
        var r = s && s[o];
        r && (this.off(t, o), delete s[o]), o.apply(this, e), n += r ? 0 : 1, o = i[n]
      }
      return this
    }
  }, t
}),
function(t, e) {
  "use strict";
  "function" == typeof define && define.amd ? define("desandro-matches-selector/matches-selector", e) : "object" == typeof module && module.exports ? module.exports = e() : t.matchesSelector = e()
}(window, function() {
  "use strict";
  var t = function() {
    var t = Element.prototype;
    if (t.matches) return "matches";
    if (t.matchesSelector) return "matchesSelector";
    for (var e = ["webkit", "moz", "ms", "o"], i = 0; i < e.length; i++) {
      var n = e[i],
        o = n + "MatchesSelector";
      if (t[o]) return o
    }
  }();
  return function(e, i) {
    return e[t](i)
  }
}),
function(t, e) {
  "function" == typeof define && define.amd ? define("fizzy-ui-utils/utils", ["desandro-matches-selector/matches-selector"], function(i) {
    return e(t, i)
  }) : "object" == typeof module && module.exports ? module.exports = e(t, require("desandro-matches-selector")) : t.fizzyUIUtils = e(t, t.matchesSelector)
}(window, function(t, e) {
  var i = {};
  i.extend = function(t, e) {
    for (var i in e) t[i] = e[i];
    return t
  }, i.modulo = function(t, e) {
    return (t % e + e) % e
  }, i.makeArray = function(t) {
    var e = [];
    if (Array.isArray(t)) e = t;
    else if (t && "number" == typeof t.length)
      for (var i = 0; i < t.length; i++) e.push(t[i]);
    else e.push(t);
    return e
  }, i.removeFrom = function(t, e) {
    var i = t.indexOf(e); - 1 != i && t.splice(i, 1)
  }, i.getParent = function(t, i) {
    for (; t != document.body;)
      if (t = t.parentNode, e(t, i)) return t
  }, i.getQueryElement = function(t) {
    return "string" == typeof t ? document.querySelector(t) : t
  }, i.handleEvent = function(t) {
    var e = "on" + t.type;
    this[e] && this[e](t)
  }, i.filterFindElements = function(t, n) {
    t = i.makeArray(t);
    var o = [];
    return t.forEach(function(t) {
      if (t instanceof HTMLElement) {
        if (!n) return void o.push(t);
        e(t, n) && o.push(t);
        for (var i = t.querySelectorAll(n), s = 0; s < i.length; s++) o.push(i[s])
      }
    }), o
  }, i.debounceMethod = function(t, e, i) {
    var n = t.prototype[e],
      o = e + "Timeout";
    t.prototype[e] = function() {
      var t = this[o];
      t && clearTimeout(t);
      var e = arguments,
        s = this;
      this[o] = setTimeout(function() {
        n.apply(s, e), delete s[o]
      }, i || 100)
    }
  }, i.docReady = function(t) {
    "complete" == document.readyState ? t() : document.addEventListener("DOMContentLoaded", t)
  }, i.toDashed = function(t) {
    return t.replace(/(.)([A-Z])/g, function(t, e, i) {
      return e + "-" + i
    }).toLowerCase()
  };
  var n = t.console;
  return i.htmlInit = function(e, o) {
    i.docReady(function() {
      var s = i.toDashed(o),
        r = "data-" + s,
        a = document.querySelectorAll("[" + r + "]"),
        h = document.querySelectorAll(".js-" + s),
        u = i.makeArray(a).concat(i.makeArray(h)),
        c = r + "-options",
        d = t.jQuery;
      u.forEach(function(t) {
        var i, s = t.getAttribute(r) || t.getAttribute(c);
        try {
          i = s && JSON.parse(s)
        } catch (a) {
          return void(n && n.error("Error parsing " + r + " on " + t.className + ": " + a))
        }
        var h = new e(t, i);
        d && d.data(t, o, h)
      })
    })
  }, i
}),
function(t, e) {
  "function" == typeof define && define.amd ? define("outlayer/item", ["ev-emitter/ev-emitter", "get-size/get-size"], e) : "object" == typeof module && module.exports ? module.exports = e(require("ev-emitter"), require("get-size")) : (t.Outlayer = {}, t.Outlayer.Item = e(t.EvEmitter, t.getSize))
}(window, function(t, e) {
  "use strict";

  function i(t) {
    for (var e in t) return !1;
    return e = null, !0
  }

  function n(t, e) {
    t && (this.element = t, this.layout = e, this.position = {
      x: 0,
      y: 0
    }, this._create())
  }

  function o(t) {
    return t.replace(/([A-Z])/g, function(t) {
      return "-" + t.toLowerCase()
    })
  }
  var s = document.documentElement.style,
    r = "string" == typeof s.transition ? "transition" : "WebkitTransition",
    a = "string" == typeof s.transform ? "transform" : "WebkitTransform",
    h = {
      WebkitTransition: "webkitTransitionEnd",
      transition: "transitionend"
    }[r],
    u = {
      transform: a,
      transition: r,
      transitionDuration: r + "Duration",
      transitionProperty: r + "Property",
      transitionDelay: r + "Delay"
    },
    c = n.prototype = Object.create(t.prototype);
  c.constructor = n, c._create = function() {
    this._transn = {
      ingProperties: {},
      clean: {},
      onEnd: {}
    }, this.css({
      position: "absolute"
    })
  }, c.handleEvent = function(t) {
    var e = "on" + t.type;
    this[e] && this[e](t)
  }, c.getSize = function() {
    this.size = e(this.element)
  }, c.css = function(t) {
    var e = this.element.style;
    for (var i in t) {
      var n = u[i] || i;
      e[n] = t[i]
    }
  }, c.getPosition = function() {
    var t = getComputedStyle(this.element),
      e = this.layout._getOption("originLeft"),
      i = this.layout._getOption("originTop"),
      n = t[e ? "left" : "right"],
      o = t[i ? "top" : "bottom"],
      s = this.layout.size,
      r = -1 != n.indexOf("%") ? parseFloat(n) / 100 * s.width : parseInt(n, 10),
      a = -1 != o.indexOf("%") ? parseFloat(o) / 100 * s.height : parseInt(o, 10);
    r = isNaN(r) ? 0 : r, a = isNaN(a) ? 0 : a, r -= e ? s.paddingLeft : s.paddingRight, a -= i ? s.paddingTop : s.paddingBottom, this.position.x = r, this.position.y = a
  }, c.layoutPosition = function() {
    var t = this.layout.size,
      e = {},
      i = this.layout._getOption("originLeft"),
      n = this.layout._getOption("originTop"),
      o = i ? "paddingLeft" : "paddingRight",
      s = i ? "left" : "right",
      r = i ? "right" : "left",
      a = this.position.x + t[o];
    e[s] = this.getXValue(a), e[r] = "";
    var h = n ? "paddingTop" : "paddingBottom",
      u = n ? "top" : "bottom",
      c = n ? "bottom" : "top",
      d = this.position.y + t[h];
    e[u] = this.getYValue(d), e[c] = "", this.css(e), this.emitEvent("layout", [this])
  }, c.getXValue = function(t) {
    var e = this.layout._getOption("horizontal");
    return this.layout.options.percentPosition && !e ? t / this.layout.size.width * 100 + "%" : t + "px"
  }, c.getYValue = function(t) {
    var e = this.layout._getOption("horizontal");
    return this.layout.options.percentPosition && e ? t / this.layout.size.height * 100 + "%" : t + "px"
  }, c._transitionTo = function(t, e) {
    this.getPosition();
    var i = this.position.x,
      n = this.position.y,
      o = parseInt(t, 10),
      s = parseInt(e, 10),
      r = o === this.position.x && s === this.position.y;
    if (this.setPosition(t, e), r && !this.isTransitioning) return void this.layoutPosition();
    var a = t - i,
      h = e - n,
      u = {};
    u.transform = this.getTranslate(a, h), this.transition({
      to: u,
      onTransitionEnd: {
        transform: this.layoutPosition
      },
      isCleaning: !0
    })
  }, c.getTranslate = function(t, e) {
    var i = this.layout._getOption("originLeft"),
      n = this.layout._getOption("originTop");
    return t = i ? t : -t, e = n ? e : -e, "translate3d(" + t + "px, " + e + "px, 0)"
  }, c.goTo = function(t, e) {
    this.setPosition(t, e), this.layoutPosition()
  }, c.moveTo = c._transitionTo, c.setPosition = function(t, e) {
    this.position.x = parseInt(t, 10), this.position.y = parseInt(e, 10)
  }, c._nonTransition = function(t) {
    this.css(t.to), t.isCleaning && this._removeStyles(t.to);
    for (var e in t.onTransitionEnd) t.onTransitionEnd[e].call(this)
  }, c.transition = function(t) {
    if (!parseFloat(this.layout.options.transitionDuration)) return void this._nonTransition(t);
    var e = this._transn;
    for (var i in t.onTransitionEnd) e.onEnd[i] = t.onTransitionEnd[i];
    for (i in t.to) e.ingProperties[i] = !0, t.isCleaning && (e.clean[i] = !0);
    if (t.from) {
      this.css(t.from);
      var n = this.element.offsetHeight;
      n = null
    }
    this.enableTransition(t.to), this.css(t.to), this.isTransitioning = !0
  };
  var d = "opacity," + o(a);
  c.enableTransition = function() {
    if (!this.isTransitioning) {
      var t = this.layout.options.transitionDuration;
      t = "number" == typeof t ? t + "ms" : t, this.css({
        transitionProperty: d,
        transitionDuration: t,
        transitionDelay: this.staggerDelay || 0
      }), this.element.addEventListener(h, this, !1)
    }
  }, c.onwebkitTransitionEnd = function(t) {
    this.ontransitionend(t)
  }, c.onotransitionend = function(t) {
    this.ontransitionend(t)
  };
  var f = {
    "-webkit-transform": "transform"
  };
  c.ontransitionend = function(t) {
    if (t.target === this.element) {
      var e = this._transn,
        n = f[t.propertyName] || t.propertyName;
      if (delete e.ingProperties[n], i(e.ingProperties) && this.disableTransition(), n in e.clean && (this.element.style[t.propertyName] = "", delete e.clean[n]), n in e.onEnd) {
        var o = e.onEnd[n];
        o.call(this), delete e.onEnd[n]
      }
      this.emitEvent("transitionEnd", [this])
    }
  }, c.disableTransition = function() {
    this.removeTransitionStyles(), this.element.removeEventListener(h, this, !1), this.isTransitioning = !1
  }, c._removeStyles = function(t) {
    var e = {};
    for (var i in t) e[i] = "";
    this.css(e)
  };
  var l = {
    transitionProperty: "",
    transitionDuration: "",
    transitionDelay: ""
  };
  return c.removeTransitionStyles = function() {
    this.css(l)
  }, c.stagger = function(t) {
    t = isNaN(t) ? 0 : t, this.staggerDelay = t + "ms"
  }, c.removeElem = function() {
    this.element.parentNode.removeChild(this.element), this.css({
      display: ""
    }), this.emitEvent("remove", [this])
  }, c.remove = function() {
    return r && parseFloat(this.layout.options.transitionDuration) ? (this.once("transitionEnd", function() {
      this.removeElem()
    }), void this.hide()) : void this.removeElem()
  }, c.reveal = function() {
    delete this.isHidden, this.css({
      display: ""
    });
    var t = this.layout.options,
      e = {},
      i = this.getHideRevealTransitionEndProperty("visibleStyle");
    e[i] = this.onRevealTransitionEnd, this.transition({
      from: t.hiddenStyle,
      to: t.visibleStyle,
      isCleaning: !0,
      onTransitionEnd: e
    })
  }, c.onRevealTransitionEnd = function() {
    this.isHidden || this.emitEvent("reveal")
  }, c.getHideRevealTransitionEndProperty = function(t) {
    var e = this.layout.options[t];
    if (e.opacity) return "opacity";
    for (var i in e) return i
  }, c.hide = function() {
    this.isHidden = !0, this.css({
      display: ""
    });
    var t = this.layout.options,
      e = {},
      i = this.getHideRevealTransitionEndProperty("hiddenStyle");
    e[i] = this.onHideTransitionEnd, this.transition({
      from: t.visibleStyle,
      to: t.hiddenStyle,
      isCleaning: !0,
      onTransitionEnd: e
    })
  }, c.onHideTransitionEnd = function() {
    this.isHidden && (this.css({
      display: "none"
    }), this.emitEvent("hide"))
  }, c.destroy = function() {
    this.css({
      position: "",
      left: "",
      right: "",
      top: "",
      bottom: "",
      transition: "",
      transform: ""
    })
  }, n
}),
function(t, e) {
  "use strict";
  "function" == typeof define && define.amd ? define("outlayer/outlayer", ["ev-emitter/ev-emitter", "get-size/get-size", "fizzy-ui-utils/utils", "./item"], function(i, n, o, s) {
    return e(t, i, n, o, s)
  }) : "object" == typeof module && module.exports ? module.exports = e(t, require("ev-emitter"), require("get-size"), require("fizzy-ui-utils"), require("./item")) : t.Outlayer = e(t, t.EvEmitter, t.getSize, t.fizzyUIUtils, t.Outlayer.Item)
}(window, function(t, e, i, n, o) {
  "use strict";

  function s(t, e) {
    var i = n.getQueryElement(t);
    if (!i) return void(h && h.error("Bad element for " + this.constructor.namespace + ": " + (i || t)));
    this.element = i, u && (this.$element = u(this.element)), this.options = n.extend({}, this.constructor.defaults), this.option(e);
    var o = ++d;
    this.element.outlayerGUID = o, f[o] = this, this._create();
    var s = this._getOption("initLayout");
    s && this.layout()
  }

  function r(t) {
    function e() {
      t.apply(this, arguments)
    }
    return e.prototype = Object.create(t.prototype), e.prototype.constructor = e, e
  }

  function a(t) {
    if ("number" == typeof t) return t;
    var e = t.match(/(^\d*\.?\d*)(\w*)/),
      i = e && e[1],
      n = e && e[2];
    if (!i.length) return 0;
    i = parseFloat(i);
    var o = p[n] || 1;
    return i * o
  }
  var h = t.console,
    u = t.jQuery,
    c = function() {},
    d = 0,
    f = {};
  s.namespace = "outlayer", s.Item = o, s.defaults = {
    containerStyle: {
      position: "relative"
    },
    initLayout: !0,
    originLeft: !0,
    originTop: !0,
    resize: !0,
    resizeContainer: !0,
    transitionDuration: "0.4s",
    hiddenStyle: {
      opacity: 0,
      transform: "scale(0.001)"
    },
    visibleStyle: {
      opacity: 1,
      transform: "scale(1)"
    }
  };
  var l = s.prototype;
  n.extend(l, e.prototype), l.option = function(t) {
    n.extend(this.options, t)
  }, l._getOption = function(t) {
    var e = this.constructor.compatOptions[t];
    return e && void 0 !== this.options[e] ? this.options[e] : this.options[t]
  }, s.compatOptions = {
    initLayout: "isInitLayout",
    horizontal: "isHorizontal",
    layoutInstant: "isLayoutInstant",
    originLeft: "isOriginLeft",
    originTop: "isOriginTop",
    resize: "isResizeBound",
    resizeContainer: "isResizingContainer"
  }, l._create = function() {
    this.reloadItems(), this.stamps = [], this.stamp(this.options.stamp), n.extend(this.element.style, this.options.containerStyle);
    var t = this._getOption("resize");
    t && this.bindResize()
  }, l.reloadItems = function() {
    this.items = this._itemize(this.element.children)
  }, l._itemize = function(t) {
    for (var e = this._filterFindItemElements(t), i = this.constructor.Item, n = [], o = 0; o < e.length; o++) {
      var s = e[o],
        r = new i(s, this);
      n.push(r)
    }
    return n
  }, l._filterFindItemElements = function(t) {
    return n.filterFindElements(t, this.options.itemSelector)
  }, l.getItemElements = function() {
    return this.items.map(function(t) {
      return t.element
    })
  }, l.layout = function() {
    this._resetLayout(), this._manageStamps();
    var t = this._getOption("layoutInstant"),
      e = void 0 !== t ? t : !this._isLayoutInited;
    this.layoutItems(this.items, e), this._isLayoutInited = !0
  }, l._init = l.layout, l._resetLayout = function() {
    this.getSize()
  }, l.getSize = function() {
    this.size = i(this.element)
  }, l._getMeasurement = function(t, e) {
    var n, o = this.options[t];
    o ? ("string" == typeof o ? n = this.element.querySelector(o) : o instanceof HTMLElement && (n = o), this[t] = n ? i(n)[e] : o) : this[t] = 0
  }, l.layoutItems = function(t, e) {
    t = this._getItemsForLayout(t), this._layoutItems(t, e), this._postLayout()
  }, l._getItemsForLayout = function(t) {
    return t.filter(function(t) {
      return !t.isIgnored
    })
  }, l._layoutItems = function(t, e) {
    if (this._emitCompleteOnItems("layout", t), t && t.length) {
      var i = [];
      t.forEach(function(t) {
        var n = this._getItemLayoutPosition(t);
        n.item = t, n.isInstant = e || t.isLayoutInstant, i.push(n)
      }, this), this._processLayoutQueue(i)
    }
  }, l._getItemLayoutPosition = function() {
    return {
      x: 0,
      y: 0
    }
  }, l._processLayoutQueue = function(t) {
    this.updateStagger(), t.forEach(function(t, e) {
      this._positionItem(t.item, t.x, t.y, t.isInstant, e)
    }, this)
  }, l.updateStagger = function() {
    var t = this.options.stagger;
    return null === t || void 0 === t ? void(this.stagger = 0) : (this.stagger = a(t), this.stagger)
  }, l._positionItem = function(t, e, i, n, o) {
    n ? t.goTo(e, i) : (t.stagger(o * this.stagger), t.moveTo(e, i))
  }, l._postLayout = function() {
    this.resizeContainer()
  }, l.resizeContainer = function() {
    var t = this._getOption("resizeContainer");
    if (t) {
      var e = this._getContainerSize();
      e && (this._setContainerMeasure(e.width, !0), this._setContainerMeasure(e.height, !1))
    }
  }, l._getContainerSize = c, l._setContainerMeasure = function(t, e) {
    if (void 0 !== t) {
      var i = this.size;
      i.isBorderBox && (t += e ? i.paddingLeft + i.paddingRight + i.borderLeftWidth + i.borderRightWidth : i.paddingBottom + i.paddingTop + i.borderTopWidth + i.borderBottomWidth), t = Math.max(t, 0), this.element.style[e ? "width" : "height"] = t + "px"
    }
  }, l._emitCompleteOnItems = function(t, e) {
    function i() {
      o.dispatchEvent(t + "Complete", null, [e])
    }

    function n() {
      r++, r == s && i()
    }
    var o = this,
      s = e.length;
    if (!e || !s) return void i();
    var r = 0;
    e.forEach(function(e) {
      e.once(t, n)
    })
  }, l.dispatchEvent = function(t, e, i) {
    var n = e ? [e].concat(i) : i;
    if (this.emitEvent(t, n), u)
      if (this.$element = this.$element || u(this.element), e) {
        var o = u.Event(e);
        o.type = t, this.$element.trigger(o, i)
      } else this.$element.trigger(t, i)
  }, l.ignore = function(t) {
    var e = this.getItem(t);
    e && (e.isIgnored = !0)
  }, l.unignore = function(t) {
    var e = this.getItem(t);
    e && delete e.isIgnored
  }, l.stamp = function(t) {
    t = this._find(t), t && (this.stamps = this.stamps.concat(t), t.forEach(this.ignore, this))
  }, l.unstamp = function(t) {
    t = this._find(t), t && t.forEach(function(t) {
      n.removeFrom(this.stamps, t), this.unignore(t)
    }, this)
  }, l._find = function(t) {
    return t ? ("string" == typeof t && (t = this.element.querySelectorAll(t)), t = n.makeArray(t)) : void 0
  }, l._manageStamps = function() {
    this.stamps && this.stamps.length && (this._getBoundingRect(), this.stamps.forEach(this._manageStamp, this))
  }, l._getBoundingRect = function() {
    var t = this.element.getBoundingClientRect(),
      e = this.size;
    this._boundingRect = {
      left: t.left + e.paddingLeft + e.borderLeftWidth,
      top: t.top + e.paddingTop + e.borderTopWidth,
      right: t.right - (e.paddingRight + e.borderRightWidth),
      bottom: t.bottom - (e.paddingBottom + e.borderBottomWidth)
    }
  }, l._manageStamp = c, l._getElementOffset = function(t) {
    var e = t.getBoundingClientRect(),
      n = this._boundingRect,
      o = i(t),
      s = {
        left: e.left - n.left - o.marginLeft,
        top: e.top - n.top - o.marginTop,
        right: n.right - e.right - o.marginRight,
        bottom: n.bottom - e.bottom - o.marginBottom
      };
    return s
  }, l.handleEvent = n.handleEvent, l.bindResize = function() {
    t.addEventListener("resize", this), this.isResizeBound = !0
  }, l.unbindResize = function() {
    t.removeEventListener("resize", this), this.isResizeBound = !1
  }, l.onresize = function() {
    this.resize()
  }, n.debounceMethod(s, "onresize", 100), l.resize = function() {
    this.isResizeBound && this.needsResizeLayout() && this.layout()
  }, l.needsResizeLayout = function() {
    var t = i(this.element),
      e = this.size && t;
    return e && t.innerWidth !== this.size.innerWidth
  }, l.addItems = function(t) {
    var e = this._itemize(t);
    return e.length && (this.items = this.items.concat(e)), e
  }, l.appended = function(t) {
    var e = this.addItems(t);
    e.length && (this.layoutItems(e, !0), this.reveal(e))
  }, l.prepended = function(t) {
    var e = this._itemize(t);
    if (e.length) {
      var i = this.items.slice(0);
      this.items = e.concat(i), this._resetLayout(), this._manageStamps(), this.layoutItems(e, !0), this.reveal(e), this.layoutItems(i)
    }
  }, l.reveal = function(t) {
    if (this._emitCompleteOnItems("reveal", t), t && t.length) {
      var e = this.updateStagger();
      t.forEach(function(t, i) {
        t.stagger(i * e), t.reveal()
      })
    }
  }, l.hide = function(t) {
    if (this._emitCompleteOnItems("hide", t), t && t.length) {
      var e = this.updateStagger();
      t.forEach(function(t, i) {
        t.stagger(i * e), t.hide()
      })
    }
  }, l.revealItemElements = function(t) {
    var e = this.getItems(t);
    this.reveal(e)
  }, l.hideItemElements = function(t) {
    var e = this.getItems(t);
    this.hide(e)
  }, l.getItem = function(t) {
    for (var e = 0; e < this.items.length; e++) {
      var i = this.items[e];
      if (i.element == t) return i
    }
  }, l.getItems = function(t) {
    t = n.makeArray(t);
    var e = [];
    return t.forEach(function(t) {
      var i = this.getItem(t);
      i && e.push(i)
    }, this), e
  }, l.remove = function(t) {
    var e = this.getItems(t);
    this._emitCompleteOnItems("remove", e), e && e.length && e.forEach(function(t) {
      t.remove(), n.removeFrom(this.items, t)
    }, this)
  }, l.destroy = function() {
    var t = this.element.style;
    t.height = "", t.position = "", t.width = "", this.items.forEach(function(t) {
      t.destroy()
    }), this.unbindResize();
    var e = this.element.outlayerGUID;
    delete f[e], delete this.element.outlayerGUID, u && u.removeData(this.element, this.constructor.namespace)
  }, s.data = function(t) {
    t = n.getQueryElement(t);
    var e = t && t.outlayerGUID;
    return e && f[e]
  }, s.create = function(t, e) {
    var i = r(s);
    return i.defaults = n.extend({}, s.defaults), n.extend(i.defaults, e), i.compatOptions = n.extend({}, s.compatOptions), i.namespace = t, i.data = s.data, i.Item = r(o), n.htmlInit(i, t), u && u.bridget && u.bridget(t, i), i
  };
  var p = {
    ms: 1,
    s: 1e3
  };
  return s.Item = o, s
}),
function(t, e) {
  "function" == typeof define && define.amd ? define("packery/js/rect", e) : "object" == typeof module && module.exports ? module.exports = e() : (t.Packery = t.Packery || {}, t.Packery.Rect = e())
}(window, function() {
  "use strict";

  function t(e) {
    for (var i in t.defaults) this[i] = t.defaults[i];
    for (i in e) this[i] = e[i]
  }
  t.defaults = {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  };
  var e = t.prototype;
  return e.contains = function(t) {
    var e = t.width || 0,
      i = t.height || 0;
    return this.x <= t.x && this.y <= t.y && this.x + this.width >= t.x + e && this.y + this.height >= t.y + i
  }, e.overlaps = function(t) {
    var e = this.x + this.width,
      i = this.y + this.height,
      n = t.x + t.width,
      o = t.y + t.height;
    return this.x < n && e > t.x && this.y < o && i > t.y
  }, e.getMaximalFreeRects = function(e) {
    if (!this.overlaps(e)) return !1;
    var i, n = [],
      o = this.x + this.width,
      s = this.y + this.height,
      r = e.x + e.width,
      a = e.y + e.height;
    return this.y < e.y && (i = new t({
      x: this.x,
      y: this.y,
      width: this.width,
      height: e.y - this.y
    }), n.push(i)), o > r && (i = new t({
      x: r,
      y: this.y,
      width: o - r,
      height: this.height
    }), n.push(i)), s > a && (i = new t({
      x: this.x,
      y: a,
      width: this.width,
      height: s - a
    }), n.push(i)), this.x < e.x && (i = new t({
      x: this.x,
      y: this.y,
      width: e.x - this.x,
      height: this.height
    }), n.push(i)), n
  }, e.canFit = function(t) {
    return this.width >= t.width && this.height >= t.height
  }, t
}),
function(t, e) {
  if ("function" == typeof define && define.amd) define("packery/js/packer", ["./rect"], e);
  else if ("object" == typeof module && module.exports) module.exports = e(require("./rect"));
  else {
    var i = t.Packery = t.Packery || {};
    i.Packer = e(i.Rect)
  }
}(window, function(t) {
  "use strict";

  function e(t, e, i) {
    this.width = t || 0, this.height = e || 0, this.sortDirection = i || "downwardLeftToRight", this.reset()
  }
  var i = e.prototype;
  i.reset = function() {
    this.spaces = [];
    var e = new t({
      x: 0,
      y: 0,
      width: this.width,
      height: this.height
    });
    this.spaces.push(e), this.sorter = n[this.sortDirection] || n.downwardLeftToRight
  }, i.pack = function(t) {
    for (var e = 0; e < this.spaces.length; e++) {
      var i = this.spaces[e];
      if (i.canFit(t)) {
        this.placeInSpace(t, i);
        break
      }
    }
  }, i.columnPack = function(t) {
    for (var e = 0; e < this.spaces.length; e++) {
      var i = this.spaces[e],
        n = i.x <= t.x && i.x + i.width >= t.x + t.width && i.height >= t.height - .01;
      if (n) {
        t.y = i.y, this.placed(t);
        break
      }
    }
  }, i.rowPack = function(t) {
    for (var e = 0; e < this.spaces.length; e++) {
      var i = this.spaces[e],
        n = i.y <= t.y && i.y + i.height >= t.y + t.height && i.width >= t.width - .01;
      if (n) {
        t.x = i.x, this.placed(t);
        break
      }
    }
  }, i.placeInSpace = function(t, e) {
    t.x = e.x, t.y = e.y, this.placed(t)
  }, i.placed = function(t) {
    for (var e = [], i = 0; i < this.spaces.length; i++) {
      var n = this.spaces[i],
        o = n.getMaximalFreeRects(t);
      o ? e.push.apply(e, o) : e.push(n)
    }
    this.spaces = e, this.mergeSortSpaces()
  }, i.mergeSortSpaces = function() {
    e.mergeRects(this.spaces), this.spaces.sort(this.sorter)
  }, i.addSpace = function(t) {
    this.spaces.push(t), this.mergeSortSpaces()
  }, e.mergeRects = function(t) {
    var e = 0,
      i = t[e];
    t: for (; i;) {
      for (var n = 0, o = t[e + n]; o;) {
        if (o == i) n++;
        else {
          if (o.contains(i)) {
            t.splice(e, 1), i = t[e];
            continue t
          }
          i.contains(o) ? t.splice(e + n, 1) : n++
        }
        o = t[e + n]
      }
      e++, i = t[e]
    }
    return t
  };
  var n = {
    downwardLeftToRight: function(t, e) {
      return t.y - e.y || t.x - e.x
    },
    rightwardTopToBottom: function(t, e) {
      return t.x - e.x || t.y - e.y
    }
  };
  return e
}),
function(t, e) {
  "function" == typeof define && define.amd ? define("packery/js/item", ["outlayer/outlayer", "./rect"], e) : "object" == typeof module && module.exports ? module.exports = e(require("outlayer"), require("./rect")) : t.Packery.Item = e(t.Outlayer, t.Packery.Rect)
}(window, function(t, e) {
  "use strict";
  var i = document.documentElement.style,
    n = "string" == typeof i.transform ? "transform" : "WebkitTransform",
    o = function() {
      t.Item.apply(this, arguments)
    },
    s = o.prototype = Object.create(t.Item.prototype),
    r = s._create;
  s._create = function() {
    r.call(this), this.rect = new e
  };
  var a = s.moveTo;
  return s.moveTo = function(t, e) {
    var i = Math.abs(this.position.x - t),
      n = Math.abs(this.position.y - e),
      o = this.layout.dragItemCount && !this.isPlacing && !this.isTransitioning && 1 > i && 1 > n;
    return o ? void this.goTo(t, e) : void a.apply(this, arguments)
  }, s.enablePlacing = function() {
    this.removeTransitionStyles(), this.isTransitioning && n && (this.element.style[n] = "none"), this.isTransitioning = !1, this.getSize(), this.layout._setRectSize(this.element, this.rect), this.isPlacing = !0
  }, s.disablePlacing = function() {
    this.isPlacing = !1
  }, s.removeElem = function() {
    this.element.parentNode.removeChild(this.element), this.layout.packer.addSpace(this.rect), this.emitEvent("remove", [this])
  }, s.showDropPlaceholder = function() {
    var t = this.dropPlaceholder;
    t || (t = this.dropPlaceholder = document.createElement("div"), t.className = "packery-drop-placeholder", t.style.position = "absolute"), t.style.width = this.size.width + "px", t.style.height = this.size.height + "px", this.positionDropPlaceholder(), this.layout.element.appendChild(t)
  }, s.positionDropPlaceholder = function() {
    this.dropPlaceholder.style[n] = "translate(" + this.rect.x + "px, " + this.rect.y + "px)"
  }, s.hideDropPlaceholder = function() {
    var t = this.dropPlaceholder.parentNode;
    t && t.removeChild(this.dropPlaceholder)
  }, o
}),
function(t, e) {
  "function" == typeof define && define.amd ? define(["get-size/get-size", "outlayer/outlayer", "packery/js/rect", "packery/js/packer", "packery/js/item"], e) : "object" == typeof module && module.exports ? module.exports = e(require("get-size"), require("outlayer"), require("./rect"), require("./packer"), require("./item")) : t.Packery = e(t.getSize, t.Outlayer, t.Packery.Rect, t.Packery.Packer, t.Packery.Item)
}(window, function(t, e, i, n, o) {
  "use strict";

  function s(t, e) {
    return t.position.y - e.position.y || t.position.x - e.position.x
  }

  function r(t, e) {
    return t.position.x - e.position.x || t.position.y - e.position.y
  }

  function a(t, e) {
    var i = e.x - t.x,
      n = e.y - t.y;
    return Math.sqrt(i * i + n * n)
  }
  i.prototype.canFit = function(t) {
    return this.width >= t.width - 1 && this.height >= t.height - 1
  };
  var h = e.create("packery");
  h.Item = o;
  var u = h.prototype;
  u._create = function() {
    e.prototype._create.call(this), this.packer = new n, this.shiftPacker = new n, this.isEnabled = !0, this.dragItemCount = 0;
    var t = this;
    this.handleDraggabilly = {
      dragStart: function() {
        t.itemDragStart(this.element)
      },
      dragMove: function() {
        t.itemDragMove(this.element, this.position.x, this.position.y)
      },
      dragEnd: function() {
        t.itemDragEnd(this.element)
      }
    }, this.handleUIDraggable = {
      start: function(e, i) {
        i && t.itemDragStart(e.currentTarget)
      },
      drag: function(e, i) {
        i && t.itemDragMove(e.currentTarget, i.position.left, i.position.top)
      },
      stop: function(e, i) {
        i && t.itemDragEnd(e.currentTarget)
      }
    }
  }, u._resetLayout = function() {
    this.getSize(), this._getMeasurements();
    var t, e, i;
    this._getOption("horizontal") ? (t = 1 / 0, e = this.size.innerHeight + this.gutter, i = "rightwardTopToBottom") : (t = this.size.innerWidth + this.gutter, e = 1 / 0, i = "downwardLeftToRight"), this.packer.width = this.shiftPacker.width = t, this.packer.height = this.shiftPacker.height = e, this.packer.sortDirection = this.shiftPacker.sortDirection = i, this.packer.reset(), this.maxY = 0, this.maxX = 0
  }, u._getMeasurements = function() {
    this._getMeasurement("columnWidth", "width"), this._getMeasurement("rowHeight", "height"), this._getMeasurement("gutter", "width")
  }, u._getItemLayoutPosition = function(t) {
    if (this._setRectSize(t.element, t.rect), this.isShifting || this.dragItemCount > 0) {
      var e = this._getPackMethod();
      this.packer[e](t.rect)
    } else this.packer.pack(t.rect);
    return this._setMaxXY(t.rect), t.rect
  }, u.shiftLayout = function() {
    this.isShifting = !0, this.layout(), delete this.isShifting
  }, u._getPackMethod = function() {
    return this._getOption("horizontal") ? "rowPack" : "columnPack"
  }, u._setMaxXY = function(t) {
    this.maxX = Math.max(t.x + t.width, this.maxX), this.maxY = Math.max(t.y + t.height, this.maxY)
  }, u._setRectSize = function(e, i) {
    var n = t(e),
      o = n.outerWidth,
      s = n.outerHeight;
    (o || s) && (o = this._applyGridGutter(o, this.columnWidth), s = this._applyGridGutter(s, this.rowHeight)), i.width = Math.min(o, this.packer.width), i.height = Math.min(s, this.packer.height)
  }, u._applyGridGutter = function(t, e) {
    if (!e) return t + this.gutter;
    e += this.gutter;
    var i = t % e,
      n = i && 1 > i ? "round" : "ceil";
    return t = Math[n](t / e) * e
  }, u._getContainerSize = function() {
    return this._getOption("horizontal") ? {
      width: this.maxX - this.gutter
    } : {
      height: this.maxY - this.gutter
    }
  }, u._manageStamp = function(t) {
    var e, n = this.getItem(t);
    if (n && n.isPlacing) e = n.rect;
    else {
      var o = this._getElementOffset(t);
      e = new i({
        x: this._getOption("originLeft") ? o.left : o.right,
        y: this._getOption("originTop") ? o.top : o.bottom
      })
    }
    this._setRectSize(t, e), this.packer.placed(e), this._setMaxXY(e)
  }, u.sortItemsByPosition = function() {
    var t = this._getOption("horizontal") ? r : s;
    this.items.sort(t)
  }, u.fit = function(t, e, i) {
    var n = this.getItem(t);
    n && (this.stamp(n.element), n.enablePlacing(), this.updateShiftTargets(n), e = void 0 === e ? n.rect.x : e, i = void 0 === i ? n.rect.y : i, this.shift(n, e, i), this._bindFitEvents(n), n.moveTo(n.rect.x, n.rect.y), this.shiftLayout(), this.unstamp(n.element), this.sortItemsByPosition(), n.disablePlacing())
  }, u._bindFitEvents = function(t) {
    function e() {
      n++, 2 == n && i.dispatchEvent("fitComplete", null, [t])
    }
    var i = this,
      n = 0;
    t.once("layout", e), this.once("layoutComplete", e)
  }, u.resize = function() {
    this.isResizeBound && this.needsResizeLayout() && (this.options.shiftPercentResize ? this.resizeShiftPercentLayout() : this.layout())
  }, u.needsResizeLayout = function() {
    var e = t(this.element),
      i = this._getOption("horizontal") ? "innerHeight" : "innerWidth";
    return e[i] != this.size[i]
  }, u.resizeShiftPercentLayout = function() {
    var e = this._getItemsForLayout(this.items),
      i = this._getOption("horizontal"),
      n = i ? "y" : "x",
      o = i ? "height" : "width",
      s = i ? "rowHeight" : "columnWidth",
      r = i ? "innerHeight" : "innerWidth",
      a = this[s];
    if (a = a && a + this.gutter) {
      this._getMeasurements();
      var h = this[s] + this.gutter;
      e.forEach(function(t) {
        var e = Math.round(t.rect[n] / a);
        t.rect[n] = e * h
      })
    } else {
      var u = t(this.element)[r] + this.gutter,
        c = this.packer[o];
      e.forEach(function(t) {
        t.rect[n] = t.rect[n] / c * u
      })
    }
    this.shiftLayout()
  }, u.itemDragStart = function(t) {
    if (this.isEnabled) {
      this.stamp(t);
      var e = this.getItem(t);
      e && (e.enablePlacing(), e.showDropPlaceholder(), this.dragItemCount++, this.updateShiftTargets(e))
    }
  }, u.updateShiftTargets = function(t) {
    this.shiftPacker.reset(), this._getBoundingRect();
    var e = this._getOption("originLeft"),
      n = this._getOption("originTop");
    this.stamps.forEach(function(t) {
      var o = this.getItem(t);
      if (!o || !o.isPlacing) {
        var s = this._getElementOffset(t),
          r = new i({
            x: e ? s.left : s.right,
            y: n ? s.top : s.bottom
          });
        this._setRectSize(t, r), this.shiftPacker.placed(r)
      }
    }, this);
    var o = this._getOption("horizontal"),
      s = o ? "rowHeight" : "columnWidth",
      r = o ? "height" : "width";
    this.shiftTargetKeys = [], this.shiftTargets = [];
    var a, h = this[s];
    if (h = h && h + this.gutter) {
      var u = Math.ceil(t.rect[r] / h),
        c = Math.floor((this.shiftPacker[r] + this.gutter) / h);
      a = (c - u) * h;
      for (var d = 0; c > d; d++) {
        var f = o ? 0 : d * h,
          l = o ? d * h : 0;
        this._addShiftTarget(f, l, a)
      }
    } else a = this.shiftPacker[r] + this.gutter - t.rect[r], this._addShiftTarget(0, 0, a);
    var p = this._getItemsForLayout(this.items),
      g = this._getPackMethod();
    p.forEach(function(t) {
      var e = t.rect;
      this._setRectSize(t.element, e), this.shiftPacker[g](e), this._addShiftTarget(e.x, e.y, a);
      var i = o ? e.x + e.width : e.x,
        n = o ? e.y : e.y + e.height;
      if (this._addShiftTarget(i, n, a), h)
        for (var s = Math.round(e[r] / h), u = 1; s > u; u++) {
          var c = o ? i : e.x + h * u,
            d = o ? e.y + h * u : n;
          this._addShiftTarget(c, d, a)
        }
    }, this)
  }, u._addShiftTarget = function(t, e, i) {
    var n = this._getOption("horizontal") ? e : t;
    if (!(0 !== n && n > i)) {
      var o = t + "," + e,
        s = -1 != this.shiftTargetKeys.indexOf(o);
      s || (this.shiftTargetKeys.push(o), this.shiftTargets.push({
        x: t,
        y: e
      }))
    }
  }, u.shift = function(t, e, i) {
    var n, o = 1 / 0,
      s = {
        x: e,
        y: i
      };
    this.shiftTargets.forEach(function(t) {
      var e = a(t, s);
      o > e && (n = t, o = e)
    }), t.rect.x = n.x, t.rect.y = n.y
  };
  var c = 120;
  u.itemDragMove = function(t, e, i) {
    function n() {
      s.shift(o, e, i), o.positionDropPlaceholder(), s.layout()
    }
    var o = this.isEnabled && this.getItem(t);
    if (o) {
      e -= this.size.paddingLeft, i -= this.size.paddingTop;
      var s = this,
        r = new Date;
      this._itemDragTime && r - this._itemDragTime < c ? (clearTimeout(this.dragTimeout), this.dragTimeout = setTimeout(n, c)) : (n(), this._itemDragTime = r)
    }
  }, u.itemDragEnd = function(t) {
    function e() {
      n++, 2 == n && (i.element.classList.remove("is-positioning-post-drag"), i.hideDropPlaceholder(), o.dispatchEvent("dragItemPositioned", null, [i]))
    }
    var i = this.isEnabled && this.getItem(t);
    if (i) {
      clearTimeout(this.dragTimeout), i.element.classList.add("is-positioning-post-drag");
      var n = 0,
        o = this;
      i.once("layout", e), this.once("layoutComplete", e), i.moveTo(i.rect.x, i.rect.y), this.layout(), this.dragItemCount = Math.max(0, this.dragItemCount - 1), this.sortItemsByPosition(), i.disablePlacing(), this.unstamp(i.element)
    }
  }, u.bindDraggabillyEvents = function(t) {
    this._bindDraggabillyEvents(t, "on")
  }, u.unbindDraggabillyEvents = function(t) {
    this._bindDraggabillyEvents(t, "off")
  }, u._bindDraggabillyEvents = function(t, e) {
    var i = this.handleDraggabilly;
    t[e]("dragStart", i.dragStart), t[e]("dragMove", i.dragMove), t[e]("dragEnd", i.dragEnd)
  }, u.bindUIDraggableEvents = function(t) {
    this._bindUIDraggableEvents(t, "on")
  }, u.unbindUIDraggableEvents = function(t) {
    this._bindUIDraggableEvents(t, "off")
  }, u._bindUIDraggableEvents = function(t, e) {
    var i = this.handleUIDraggable;
    t[e]("dragstart", i.start)[e]("drag", i.drag)[e]("dragstop", i.stop)
  };
  var d = u.destroy;
  return u.destroy = function() {
    d.apply(this, arguments), this.isEnabled = !1
  }, h.Rect = i, h.Packer = n, h
});
;/*})'"*/;/*})'"*/
(function($, Drupal, undefined) {

  Drupal.behaviors.Isotopes = {
    attach: function(context, settings) {
      if ($('.packery').length > 0) {
        $('.packery').packery({
          itemSelector: '.grid-item',
          transitionDuration: '0.2s',
        });
      }
      if ($('.packery-gutter').length > 0) {
        $('.packery-gutter').packery({
          itemSelector: '.grid-item',
          transitionDuration: '0.2s',
          gutter: 10
        });
      }

    }
  }








})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
/*
 * FlowType.JS v1.1
 * Copyright 2013-2014, Simple Focus http://simplefocus.com/
 *
 * FlowType.JS by Simple Focus (http://simplefocus.com/)
 * is licensed under the MIT License. Read a copy of the
 * license in the LICENSE.txt file or at
 * http://choosealicense.com/licenses/mit
 *
 * Thanks to Giovanni Difeterici (http://www.gdifeterici.com/)
 */

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

    // Establish default settings/variables
    // ====================================
    var settings = $.extend({
        maximum: 9999,
        minimum: 1,
        maxFont: 9999,
        minFont: 1,
        fontRatio: 35
      }, options),

      // Do the magic math
      // =================
      changes = function(el) {
        var $el = $(el),
          elw = $el.width(),
          width = elw > settings.maximum ? settings.maximum : elw < settings.minimum ? settings.minimum : elw,
          fontBase = width / settings.fontRatio,
          fontSize = fontBase > settings.maxFont ? settings.maxFont : fontBase < settings.minFont ? settings.minFont : fontBase;
        $el.css('font-size', fontSize + 'px');
      };

    // Make the magic visible
    // ======================
    return this.each(function() {
      // Context for resize callback
      var that = this;
      // Make changes upon resize
      $(window).resize(function() {
        changes(that);
      });
      // Set changes on load
      changes(this);
    });
  };
}(jQuery));
;/*})'"*/;/*})'"*/
// DD Exit Intent Pop Up Script
// By Dynamic Drive: http://www.dynamicdrive.com
// Oct 5th 17'- Creation Date

var ddexitpop = (function($) {

  var defaults = {
    delayregister: 0,
    delayshow: 200,
    hideaftershow: true,
    displayfreq: 'always',
    persistcookie: 'ddexitpop_shown',
    fxclass: 'rubberBand',
    mobileshowafter: 3000,
    onddexitpop: function() {}
  }
  var animatedcssclasses = ["bounce", "flash", "pulse", "rubberBand", "shake", "swing", "tada", "wobble", "jello", "bounceIn", "bounceInDown", "bounceInLeft", "bounceInRight", "bounceInUp", "fadeIn", "fadeInDown", "fadeInDownBig", "fadeInLeft", "fadeInLeftBig", "fadeInRight", "fadeInRightBig", "fadeInUp", "fadeInUpBig", "flipInX", "flipInY", "lightSpeedIn", "rotateIn", "rotateInDownLeft", "rotateInDownRight", "rotateInUpLeft", "rotateInUpRight", "slideInUp", "slideInDown", "slideInLeft", "slideInRight", "zoomIn", "zoomInDown", "zoomInLeft", "zoomInRight", "zoomInUp", "rollIn"]

  var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));
  var crossdeviceclickevt = isTouch ? 'touchstart' : 'click'

  function getCookie(Name) {
    var re = new RegExp(Name + "=[^;]+", "i"); //construct RE to search for target name/value pair
    if (document.cookie.match(re)) //if cookie found
      return document.cookie.match(re)[0].split("=")[1] //return its value
    return null
  }

  function setCookie(name, value, duration) {
    var expirestr = '',
      expiredate = new Date()
    if (typeof duration != "undefined") { //if set persistent cookie
      var offsetmin = parseInt(duration) * (/hr/i.test(duration) ? 60 : /day/i.test(duration) ? 60 * 24 : 1)
      expiredate.setMinutes(expiredate.getMinutes() + offsetmin)
      expirestr = "; expires=" + expiredate.toUTCString()
    }
    document.cookie = name + "=" + value + "; path=/" + expirestr
  }

  function makeajaxfriendly(url) { // function to ensure hostname portion of URL 'http://mysite.com/pathtofile' is same origin as current hostname (ie: www.mysite.com)
    if (/^http/i.test(url)) {
      var dummyurl = document.createElement('a')
      dummyurl.href = url
      return dummyurl.href.replace(RegExp(dummyurl.hostname, 'i'), location.hostname)
    } else {
      return url
    }
  }

  var ddexitpop = {

    wrappermarkup: '',
    $wrapperref: null,
    $contentref: null,
    displaypopup: true, // Boolean to ensure popup is only opened once when showpopup() is called
    delayshowtimer: null, // setTimeout reference to delay showing of exit pop after mouse moves outside  browser top edge
    settings: null,

    ajaxrequest: function(filepath) {
      var ajaxfriendlyurl = makeajaxfriendly(filepath)
      $.ajax({
        url: ajaxfriendlyurl,
        dataType: 'html',
        error: function(ajaxrequest) {
          alert('Error fetching content.<br />Server Response: ' + ajaxrequest.responseText)
        },
        success: function(content) {
          ddexitpop.$contentref = $(content).appendTo(document.body)
          ddexitpop.setup(ddexitpop.$contentref)
        }
      })
    },

    detectexit: function(e) {
      if (e.clientY < 60) {
        this.delayshowtimer = setTimeout(function() {
          ddexitpop.showpopup()
          ddexitpop.settings.onddexitpop(ddexitpop.$contentref)
        }, this.settings.delayshow)
      }
    },

    detectenter: function(e) {
      if (e.clientY < 60) {
        clearTimeout(this.delayshowtimer)
      }
    },

    showpopup: function() {
      if (this.$contentref != null && this.displaypopup == true) {
        if (this.settings.randomizefxclass === true) {
          this.settings.fxclass = animatedcssclasses[Math.floor(Math.random() * animatedcssclasses.length)]
        }
        this.$wrapperref.addClass('open')
        this.$contentref.addClass(this.settings.fxclass)
        this.displaypopup = false
        if (this.settings.hideaftershow) {
          $(document).off('mouseleave.registerexit')
        }
      }
    },

    hidepopup: function() {
      this.$wrapperref.removeClass('open')
      this.$contentref.removeClass(this.settings.fxclass)
      this.displaypopup = true
    },

    setup: function($content) {
      this.$contentref.addClass('animated')
      this.$wrapperref = $(this.wrappermarkup).appendTo(document.body)
      this.$wrapperref.append(this.$contentref)
      this.$wrapperref.find('.veil').on(crossdeviceclickevt, function() {
        ddexitpop.hidepopup()
      })
      if (this.settings.displayfreq != 'always') {
        if (this.settings.displayfreq == 'session') {
          setCookie(this.settings.persistcookie, 'yes')
        } else if (/\d+(hr|day)/i.test(this.settings.displayfreq)) {
          setCookie(this.settings.persistcookie, 'yes', this.settings.displayfreq)
          setCookie(this.settings.persistcookie + '_duration', this.settings.displayfreq, this.settings.displayfreq) // remember the duration of persistence
        }
      }
    },

    init: function(options) {

      var s = $.extend({}, defaults, options)

      var persistduration = getCookie(s.persistcookie + '_duration')
      if (persistduration && (s.displayfreq == 'session' || s.displayfreq != persistduration)) {
        setCookie(s.persistcookie, 'yes', -1) // delete persistent cookie (if stored)
        setCookie(s.persistcookie + '_duration', '', -1) // delete persistent cookie duration (if stored)
      }
      if (s.displayfreq != 'always' && getCookie(s.persistcookie)) {
        return
      }

      if (s.fxclass == 'random') {
        s.randomizefxclass = true
      }
      this.settings = s
      if (s.contentsource[0] == 'ajax') {
        this.ajaxrequest(s.contentsource[1])
      } else if (s.contentsource[0] == 'id') {
        this.$contentref = $('#' + s.contentsource[1]).appendTo(document.body)
        this.setup(this.$contentref)
      } else if (s.contentsource[0] == 'inline') {
        this.$contentref = $(s.contentsource[1]).appendTo(document.body)
        this.setup(this.$contentref)
      }
      setTimeout(function() {
        $(document).on('mouseleave.registerexit', function(e) {
          ddexitpop.detectexit(e)
        })
        $(document).on('mouseenter.registerenter', function(e) {
          ddexitpop.detectenter(e)
        })
      }, s.delayregister)

      if (s.mobileshowafter > 0) {
        $(document).one('touchstart', function() {
          setTimeout(function() {
            ddexitpop.showpopup()
          }, s.mobileshowafter)
        })
      }
    }
  }

  return ddexitpop


})(jQuery);
;/*})'"*/;/*})'"*/
/**
 * @file
 * Some basic behaviors and utility functions for Views.
 */
(function ($) {

  Drupal.Views = {};

  /**
   * JQuery UI tabs, Views integration component.
   */
  Drupal.behaviors.viewsTabs = {
    attach: function (context) {
      if ($.viewsUi && $.viewsUi.tabs) {
        $('#views-tabset').once('views-processed').viewsTabs({
          selectedClass: 'active'
        });
      }

      $('a.views-remove-link').once('views-processed').click(function(event) {
        var id = $(this).attr('id').replace('views-remove-link-', '');
        $('#views-row-' + id).hide();
        $('#views-removed-' + id).attr('checked', true);
        event.preventDefault();
      });
      /**
    * Here is to handle display deletion
    * (checking in the hidden checkbox and hiding out the row).
    */
      $('a.display-remove-link')
        .addClass('display-processed')
        .click(function() {
          var id = $(this).attr('id').replace('display-remove-link-', '');
          $('#display-row-' + id).hide();
          $('#display-removed-' + id).attr('checked', true);
          return false;
        });
    }
  };

  /**
 * Helper function to parse a querystring.
 */
  Drupal.Views.parseQueryString = function (query) {
    var args = {};
    var pos = query.indexOf('?');
    if (pos != -1) {
      query = query.substring(pos + 1);
    }
    var pairs = query.split('&');
    for (var i in pairs) {
      if (typeof(pairs[i]) == 'string') {
        var pair = pairs[i].split('=');
        // Ignore the 'q' path argument, if present.
        if (pair[0] != 'q' && pair[1]) {
          args[decodeURIComponent(pair[0].replace(/\+/g, ' '))] = decodeURIComponent(pair[1].replace(/\+/g, ' '));
        }
      }
    }
    return args;
  };

  /**
 * Helper function to return a view's arguments based on a path.
 */
  Drupal.Views.parseViewArgs = function (href, viewPath) {

    // Provide language prefix.
    if (Drupal.settings.pathPrefix) {
      var viewPath = Drupal.settings.pathPrefix + viewPath;
    }
    var returnObj = {};
    var path = Drupal.Views.getPath(href);
    // Ensure we have a correct path.
    if (viewPath && path.substring(0, viewPath.length + 1) == viewPath + '/') {
      var args = decodeURIComponent(path.substring(viewPath.length + 1, path.length));
      returnObj.view_args = args;
      returnObj.view_path = path;
    }
    return returnObj;
  };

  /**
 * Strip off the protocol plus domain from an href.
 */
  Drupal.Views.pathPortion = function (href) {
    // Remove e.g. http://example.com if present.
    var protocol = window.location.protocol;
    if (href.substring(0, protocol.length) == protocol) {
      // 2 is the length of the '//' that normally follows the protocol.
      href = href.substring(href.indexOf('/', protocol.length + 2));
    }
    return href;
  };

  /**
 * Return the Drupal path portion of an href.
 */
  Drupal.Views.getPath = function (href) {
    href = Drupal.Views.pathPortion(href);
    href = href.substring(Drupal.settings.basePath.length, href.length);
    // 3 is the length of the '?q=' added to the url without clean urls.
    if (href.substring(0, 3) == '?q=') {
      href = href.substring(3, href.length);
    }
    var chars = ['#', '?', '&'];
    for (var i in chars) {
      if (href.indexOf(chars[i]) > -1) {
        href = href.substr(0, href.indexOf(chars[i]));
      }
    }
    return href;
  };

})(jQuery);
;/*})'"*/;/*})'"*/
/*
 * jQuery UI Touch Punch 0.2.2
 *
 * Copyright 2011, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 * jquery.ui.widget.js
 * jquery.ui.mouse.js
 */
(function(b){b.support.touch="ontouchend" in document;if(!b.support.touch){return;}var c=b.ui.mouse.prototype,e=c._mouseInit,a;function d(g,h){if(g.originalEvent.touches.length>1){return;}g.preventDefault();var i=g.originalEvent.changedTouches[0],f=document.createEvent("MouseEvents");f.initMouseEvent(h,true,true,window,1,i.screenX,i.screenY,i.clientX,i.clientY,false,false,false,false,0,null);g.target.dispatchEvent(f);}c._touchStart=function(g){var f=this;if(a||!f._mouseCapture(g.originalEvent.changedTouches[0])){return;}a=true;f._touchMoved=false;d(g,"mouseover");d(g,"mousemove");d(g,"mousedown");};c._touchMove=function(f){if(!a){return;}this._touchMoved=true;d(f,"mousemove");};c._touchEnd=function(f){if(!a){return;}d(f,"mouseup");d(f,"mouseout");if(!this._touchMoved){d(f,"click");}a=false;};c._mouseInit=function(){var f=this;f.element.bind("touchstart",b.proxy(f,"_touchStart")).bind("touchmove",b.proxy(f,"_touchMove")).bind("touchend",b.proxy(f,"_touchEnd"));e.call(f);};})(jQuery);
;/*})'"*/;/*})'"*/
/*
 * Zoom In/Out Sliders Full Collection  v2.2
 *
 * Copyright 2012-2013, LambertGroup
 *
 */

(function($) {

	function animate_singular_text(elem,current_obj,options) {
		if (options.responsive) {
			newCss='';
			if (elem.css('font-size').lastIndexOf('px')!=-1) {
				fontSize=elem.css('font-size').substr(0,elem.css('font-size').lastIndexOf('px'));
				newCss+='font-size:'+fontSize/(options.origWidth/options.width)+'px;';
			} else if (elem.css('font-size').lastIndexOf('em')!=-1) {
				fontSize=elem.css('font-size').substr(0,elem.css('font-size').lastIndexOf('em'));
				newCss+='font-size:'+fontSize/(options.origWidth/options.width)+'em;';
			}

			if (elem.css('line-height').lastIndexOf('px')!=-1) {
				lineHeight=elem.css('line-height').substr(0,elem.css('line-height').lastIndexOf('px'));
				newCss+='line-height:'+lineHeight/(options.origWidth/options.width)+'px;';
			} else if (elem.css('line-height').lastIndexOf('em')!=-1) {
				lineHeight=elem.css('line-height').substr(0,elem.css('line-height').lastIndexOf('em'));
				newCss+='line-height:'+lineHeight/(options.origWidth/options.width)+'em;';
			}

			elem.wrapInner('<div class="newFS" style="'+newCss+'" />');

		}

		var leftPos=elem.attr('data-final-left');
		var topPos=elem.attr('data-final-top');
		if (options.responsive) {
			leftPos=parseInt(leftPos/(options.origWidth/options.width),10);
			topPos=parseInt(topPos/(options.origWidth/options.width),10);
		}

        var opacity_aux=1;
		if (current_obj.isVideoPlaying==true)
		   opacity_aux=0;
        elem.animate({
                opacity: opacity_aux,
                left:leftPos+'px',
                top: topPos+'px'
              }, elem.attr('data-duration')*1000, function() {
                if (current_obj.isVideoPlaying==true) {
                   var alltexts = $(current_obj.currentImg.attr('data-text-id')).children();
				   alltexts.css("opacity",0);
		        }
              });
	};




	function animate_texts(current_obj,options,bannerscollection_zoominout_the,bannerControls) {
		$(current_obj.currentImg.attr('data-text-id')).css("display","block");
		var thetexts = $(current_obj.currentImg.attr('data-text-id')).children();

		var i=0;
		currentText_arr=Array();
		thetexts.each(function() {
			currentText_arr[i] = $(this);


		  var theLeft=currentText_arr[i].attr('data-initial-left');
		  var theTop=currentText_arr[i].attr('data-initial-top');
		  if (options.responsive) {
				theLeft=parseInt(theLeft/(options.origWidth/options.width),10);
				theTop=parseInt(theTop/(options.origWidth/options.width),10);
		  }

			currentText_arr[i].css({
				"left":theLeft+"px",
				"top":theTop+"px",
				"opacity":parseInt(currentText_arr[i].attr('data-fade-start'),10)/100
			});


            var currentText=currentText_arr[i];
            setTimeout(function() { animate_singular_text(currentText,current_obj,options);}, (currentText_arr[i].attr('data-delay')*1000));

            i++;
        });
	};


	function initialPositioning(cur_i,options, bannerscollection_zoominout_container,origImgsDimensions,imgs) {
		var ver_ie=getInternetExplorerVersion();
		if (cur_i==-1)
			cur_i=0;

		var mycurImage=$(imgs[cur_i]);
		var cur_horizontalPosition=options.horizontalPosition;
	    if (mycurImage.attr('data-horizontalPosition')!=undefined && mycurImage.attr('data-horizontalPosition')!='') {
           cur_horizontalPosition=mycurImage.attr('data-horizontalPosition');
        }

		var cur_verticalPosition=options.verticalPosition;
	    if (mycurImage.attr('data-verticalPosition')!=undefined && mycurImage.attr('data-verticalPosition')!='') {
           cur_verticalPosition=mycurImage.attr('data-verticalPosition');
        }

		var cur_initialZoom=options.initialZoom;
	    if (mycurImage.attr('data-initialZoom')!=undefined && mycurImage.attr('data-initialZoom')!='') {
           cur_initialZoom=Number(mycurImage.attr('data-initialZoom'));
        }

		var cur_finalZoom=options.finalZoom;
	    if (mycurImage.attr('data-finalZoom')!=undefined && mycurImage.attr('data-finalZoom')!='') {
           cur_finalZoom=Number(mycurImage.attr('data-finalZoom'));
        }


		var origDim=origImgsDimensions[cur_i].split(";");
		if (options.responsive) {
			origDim[0]=origDim[0]/(options.origWidth/options.width);
			origDim[1]=origDim[1]/(options.origWidth/options.width);
		}

		if (options.width100Proc && options.height100Proc) {
			if (origDim[1]*Math.min(cur_finalZoom,cur_initialZoom)<options.height) {
				newH=options.height/Math.min(cur_finalZoom,cur_initialZoom);
				newW=newH*(origDim[0]/origDim[1])
				origDim[0]=newW;
				origDim[1]=newH;
			}
		}



		var imgCurInside = $('#contentHolderUnit_'+cur_i, bannerscollection_zoominout_container).find('img:first');
		var finalWidth=parseInt(cur_finalZoom*origDim[0],10);
		var finalHeight=parseInt(cur_finalZoom*origDim[1],10);

		imgCurInside.css({
			"width":parseInt(cur_initialZoom*origDim[0],10)+"px",
			"height":parseInt(cur_initialZoom*origDim[1],10)+"px"
		});


		var cur_left=0;
		switch(cur_horizontalPosition)
		{
		case 'left':
			cur_left=0;
			break;
		case 'center':
			cur_left=(options.width-parseInt(cur_initialZoom*origDim[0],10))/2;
			break;
		case 'right':
			cur_left=options.width-parseInt(cur_initialZoom*origDim[0],10);
			break;
		default:
			cur_left=0;
		}

		var cur_top=0;
		switch(cur_verticalPosition)
		{
		case 'top':
			cur_top=-2;
			break;
		case 'center':
			cur_top=(options.height-parseInt(cur_initialZoom*origDim[1],10))/2;
			break;
		case 'bottom':
			cur_top=options.height-parseInt(cur_initialZoom*origDim[1],10)+2;
			break;
		default:
			cur_top=0;
		}



		imgCurInside.css({
			"left":parseInt(cur_left,10)+"px",
			"top":parseInt(cur_top,10)+"px",
			"opacity":options.initialOpacity
		});

		if (ver_ie==-1 || (ver_ie!=-1 && ver_ie>=10)) {
			imgCurInside.css({
				"-webkit-transform-origin":cur_horizontalPosition+" "+cur_verticalPosition,
				"-moz-transform-origin":cur_horizontalPosition+" "+cur_verticalPosition,
				"-o-transform-origin":cur_horizontalPosition+" "+cur_verticalPosition,
				"transform-origin":cur_horizontalPosition+" "+cur_verticalPosition
			});

		}


	}


	function bannerscollection_zoominout_reset_animate_image(current_obj,options,imgs) {
		var ver_ie=getInternetExplorerVersion();
		var myImage=$(imgs[current_obj.current_img_no]);
		var current_initialZoom=options.initialZoom;
		if (myImage.attr('data-initialZoom')!=undefined && myImage.attr('data-initialZoom')!='') {
		   current_initialZoom=Number(myImage.attr('data-initialZoom'));
		}
		var current_finalZoom=options.finalZoom;
		if (myImage.attr('data-finalZoom')!=undefined && myImage.attr('data-finalZoom')!='') {
		   current_finalZoom=Number(myImage.attr('data-finalZoom'));
		}


		if (current_initialZoom!=current_finalZoom) {
			if (ver_ie!=-1 && ver_ie<10) {
				clearInterval(current_obj.msiInterval);
				current_obj.current_imgInside.css("filter",'progid:DXImageTransform.Microsoft.Matrix(FilterType="bilinear",M11=1, M12=0, M21=0, M22=1, Dx=0, Dy=0)');
			} else {

			  current_obj.current_imgInside.css({
				  "-webkit-transition-duration":"0s",
				  "-moz-transition-duration":"0s",
				  "-o-transition-duration":"0s",
				  "transition-duration":"0s",
				  "-webkit-transform":"scale(1)",
				  "-moz-transform":"scale(1)",
				  "-o-transform":"scale(1)",
				  "transform":"scale(1)"
			  });

			}
		}
	}


	function bannerscollection_zoominout_animate_image(current_obj,options, bannerscollection_zoominout_container,origImgsDimensions,imgs) {
		var myImage=$(imgs[current_obj.current_img_no]);
		var ver_ie=getInternetExplorerVersion();

		var current_horizontalPosition=options.horizontalPosition;
		if (myImage.attr('data-horizontalPosition')!=undefined && myImage.attr('data-horizontalPosition')!='') {
		   current_horizontalPosition=myImage.attr('data-horizontalPosition');
		}
		var current_verticalPosition=options.verticalPosition;
		if (myImage.attr('data-verticalPosition')!=undefined && myImage.attr('data-verticalPosition')!='') {
		   current_verticalPosition=myImage.attr('data-verticalPosition');
		}

		var current_duration=options.duration;
		if (myImage.attr('data-duration')!=undefined && myImage.attr('data-duration')!='') {
		   current_duration=Number(myImage.attr('data-duration'));
		}

		var current_initialZoom=options.initialZoom;
		if (myImage.attr('data-initialZoom')!=undefined && myImage.attr('data-initialZoom')!='') {
		   current_initialZoom=Number(myImage.attr('data-initialZoom'));
		}
		var current_finalZoom=options.finalZoom;
		if (myImage.attr('data-finalZoom')!=undefined && myImage.attr('data-finalZoom')!='') {
		   current_finalZoom=Number(myImage.attr('data-finalZoom'));
		}


		current_obj.current_imgInside = $('#contentHolderUnit_'+current_obj.current_img_no, bannerscollection_zoominout_container).find('img:first');

		var origCurDim=origImgsDimensions[current_obj.current_img_no].split(";");
		if (options.responsive) {
			origCurDim[0]=origCurDim[0]/(options.origWidth/options.width);
			origCurDim[1]=origCurDim[1]/(options.origWidth/options.width);
		}


		if (current_initialZoom!=current_finalZoom) {
						if (ver_ie!=-1 && ver_ie<10) {
							if (options.width100Proc)
								current_duration=current_duration+options.durationIEfix;
							current_obj.curZoom=1;
							zoomStep=0;
							current_obj.cur_marginLeft=0;
							current_obj.cur_marginTop=0;
							current_obj.msiInitialTime=(new Date).getTime();

							current_obj.msiInterval=setInterval(function() {


								nowx = (new Date).getTime();
								if ( (nowx-current_obj.msiInitialTime) > (current_duration*1000) ) {
									clearInterval(current_obj.msiInterval);
								} else {
									zoomStep=(nowx-current_obj.msiInitialTime)*Math.abs(current_initialZoom-current_finalZoom)/(current_duration*1000);
									if (current_initialZoom<=current_finalZoom)
										current_obj.curZoom=1+zoomStep;
									else
										current_obj.curZoom=1-zoomStep;


									if (current_horizontalPosition=='center') {
										current_obj.cur_marginLeft=(1-current_obj.curZoom)*current_initialZoom*origCurDim[0]/2;
									} else if (current_horizontalPosition=='right') {
										current_obj.cur_marginLeft=(1-current_obj.curZoom)*current_initialZoom*origCurDim[0];
									}


									if (current_verticalPosition=='center') {
										current_obj.cur_marginTop=(1-current_obj.curZoom)*current_initialZoom*origCurDim[1]/2;
									} else if (current_verticalPosition=='bottom') {
										current_obj.cur_marginTop=(1-current_obj.curZoom)*current_initialZoom*origCurDim[1];
									}

									current_obj.current_imgInside.css({filter:'progid:DXImageTransform.Microsoft.Matrix(FilterType="bilinear",M11='+current_obj.curZoom+', M12=0, M21=0, M22='+current_obj.curZoom+', Dx=' + current_obj.cur_marginLeft + ',Dy=' + current_obj.cur_marginTop + ')'});
								}
							}, 25);
						} else {
								zoomVal=current_finalZoom/current_initialZoom;
								current_obj.current_imgInside.css({
									"-webkit-transition-duration":current_duration+"s",
									"-moz-transition-duration":current_duration+"s",
									"-o-transition-duration":current_duration+"s",
									"transition-duration":current_duration+"s",
									"-webkit-transition-timing-function":"ease",
									"-moz-transition-timing-function":"ease",
									"-o-transition-timing-function":"ease",
									"transition-timing-function":"ease",
									"-webkit-transform":"scale("+zoomVal+") rotate(0.1deg)",
									"-moz-transform":"scale("+zoomVal+") rotate(0.1deg)",
									"-o-transform":"scale("+zoomVal+")",
									"transform":"scale("+zoomVal+") rotate(0.1deg)",
									"perspective":"0",
									"-webkit-perspective":"0"
								});


						}
		}

	}


	//circ
	function the_arc(current_obj,options) {
			nowx = (new Date).getTime();
			if (!current_obj.mouseOverBanner && options.showCircleTimer) {
				current_obj.ctx.clearRect(0,0,current_obj.canvas.width,current_obj.canvas.height);

                current_obj.ctx.beginPath();
                current_obj.ctx.globalAlpha=options.behindCircleAlpha/100;
                current_obj.ctx.arc(options.circleRadius+2*options.circleLineWidth, options.circleRadius+2*options.circleLineWidth, options.circleRadius, 0, 2 * Math.PI, false);
                current_obj.ctx.lineWidth = options.circleLineWidth+2;
                current_obj.ctx.strokeStyle = options.behindCircleColor;
                current_obj.ctx.stroke();


                current_obj.ctx.beginPath();
                current_obj.ctx.globalAlpha=options.circleAlpha/100;
                current_obj.ctx.arc(options.circleRadius+2*options.circleLineWidth, options.circleRadius+2*options.circleLineWidth, options.circleRadius, 0, ((current_obj.timeElapsed+nowx)-current_obj.arcInitialTime)/1000*2/options.autoPlay*Math.PI,  false);
                current_obj.ctx.lineWidth = options.circleLineWidth;
                current_obj.ctx.strokeStyle = options.circleColor;
                current_obj.ctx.stroke();
             }
    }



    // navigation
	function bannerscollection_zoominout_navigation(direction,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb){
		var navigateAllowed=true;
		if ((!options.loop && current_obj.current_img_no+direction>=total_images) || (!options.loop && current_obj.current_img_no+direction<0))
			navigateAllowed=false;

		if (navigateAllowed && !current_obj.slideIsRunning) {
			current_obj.slideIsRunning=true;

			$('.newFS', bannerscollection_zoominout_container ).contents().unwrap();
			current_obj.arcInitialTime=(new Date).getTime();
			current_obj.timeElapsed=0;
			if (options.showCircleTimer) {
					clearInterval(current_obj.intervalID);

					current_obj.ctx.clearRect(0,0,current_obj.canvas.width,current_obj.canvas.height);
					current_obj.ctx.beginPath();
					current_obj.ctx.globalAlpha=options.behindCircleAlpha/100;
					current_obj.ctx.arc(options.circleRadius+2*options.circleLineWidth, options.circleRadius+2*options.circleLineWidth, options.circleRadius, 0, 2 * Math.PI, false);
					current_obj.ctx.lineWidth = options.circleLineWidth+2;
					current_obj.ctx.strokeStyle = options.behindCircleColor;
					current_obj.ctx.stroke();


					current_obj.ctx.beginPath();
					current_obj.ctx.globalAlpha=options.circleAlpha/100;
					current_obj.ctx.arc(options.circleRadius+2*options.circleLineWidth, options.circleRadius+2*options.circleLineWidth, options.circleRadius, 0, 0,  false);
					current_obj.ctx.lineWidth = options.circleLineWidth;
					current_obj.ctx.strokeStyle = options.circleColor;
					current_obj.ctx.stroke();

					current_obj.intervalID=setInterval(function(){the_arc(current_obj,options)}, 125);
			}

		    if (!current_obj.bottomNavClicked) {
				current_obj.previous_current_img_no=current_obj.current_img_no;
			}
			current_obj.bottomNavClicked=false;

			$(current_obj.currentImg.attr('data-text-id')).css("display","none");


			//deactivate previous
			if (options.skin=="opportune") {
               $(bottomNavButs[current_obj.current_img_no]).removeClass('bottomNavButtonON');
            }
            //thumbs deactivate previous
            if (options.skin!="opportune") {
               $(thumbsHolder_Thumbs[current_obj.current_img_no]).removeClass('thumbsHolder_ThumbON');
			}

			bannerscollection_zoominout_playOver.css('display','none');


			//set current img
			if (current_obj.current_img_no+direction>=total_images) {
				current_obj.current_img_no=0;
			} else if (current_obj.current_img_no+direction<0) {
				current_obj.current_img_no=total_images-1;
			} else {
				current_obj.current_img_no+=direction;
			}


			if (options.skin=="opportune") {
			   $(bottomNavButs[current_obj.current_img_no]).addClass('bottomNavButtonON');
			}


			//thumbs activate current
			if (options.skin!="opportune") {
			   $(thumbsHolder_Thumbs[current_obj.current_img_no]).addClass('thumbsHolder_ThumbON');
			   //auto scroll carousel if needed
			   currentCarouselLeft=bannerscollection_zoominout_thumbsHolder.css('left').substr(0,bannerscollection_zoominout_thumbsHolder.css('left').lastIndexOf('px'));
			   if (current_obj.current_img_no===0 || current_obj.current_img_no===total_images-1) {
				  carouselScroll(0,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,options,total_images,thumbsHolder_Thumb,current_obj);
			   } else {
				 carouselScroll(1001,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,options,total_images,thumbsHolder_Thumb,current_obj);
			  }
            }


			if (options.fadeSlides) {
				$('#contentHolderUnit_'+current_obj.current_img_no, bannerscollection_zoominout_container).css({
					'opacity':1,
					'z-index':0,
					'display':'block'
				});
				$('#contentHolderUnit_'+current_obj.previous_current_img_no, bannerscollection_zoominout_container).css({
					'z-index':1,
					'display':'block'
				});

				//alert ( $('#contentHolderUnit_'+current_obj.current_img_no, bannerscollection_zoominout_container).html() );
				$('#contentHolderUnit_'+current_obj.previous_current_img_no, bannerscollection_zoominout_container).animate({
					'opacity':0
				  }, 800, 'easeOutQuad', function() {
					// Animation complete.
					  current_obj.slideIsRunning=false;
					  if (options.fadeSlides) {
						$('#contentHolderUnit_'+current_obj.current_img_no, bannerscollection_zoominout_container).css({
							'z-index':1
						});
						$('#contentHolderUnit_'+current_obj.previous_current_img_no, bannerscollection_zoominout_container).css({
							'z-index':0,
							'display':'none'
						});
					  }
					  bannerscollection_zoominout_reset_animate_image(current_obj,options,imgs);
					  current_obj.currentImg = $(imgs[current_obj.current_img_no]);
					  bannerscollection_zoominout_animate_image(current_obj,options, bannerscollection_zoominout_container,origImgsDimensions,imgs);

					  if (current_obj.currentImg.attr('data-video')=='true')
						bannerscollection_zoominout_playOver.css('display','block');

					  //reinit content to stop videos
					  if ($(imgs[current_obj.previous_current_img_no]).attr('data-video')=='true')
							$('#contentHolderUnit_'+current_obj.previous_current_img_no, bannerscollection_zoominout_container).html($(imgs[current_obj.previous_current_img_no]).html());

					  //reposition previous image
					  initialPositioning(current_obj.previous_current_img_no,options, bannerscollection_zoominout_container,origImgsDimensions,imgs);

					  animate_texts(current_obj,options,bannerscollection_zoominout_the,bannerControls);

					  if (options.autoPlay>0 && total_images>1 && !current_obj.mouseOverBanner) {
						  clearTimeout(current_obj.timeoutID);
						  current_obj.timeoutID=setTimeout(function(){ bannerscollection_zoominout_navigation(1,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb)},options.autoPlay*1000);
					  }
				});
			} else {
				bannerscollection_zoominout_contentHolder.animate({
					'left':+(-1)*current_obj.current_img_no*options.width+'px'
				  }, 800, 'easeOutQuad', function() {
					// Animation complete.
					  current_obj.slideIsRunning=false;
					  bannerscollection_zoominout_reset_animate_image(current_obj,options,imgs);
					  current_obj.currentImg = $(imgs[current_obj.current_img_no]);
					  bannerscollection_zoominout_animate_image(current_obj,options, bannerscollection_zoominout_container,origImgsDimensions,imgs);

					  if (current_obj.currentImg.attr('data-video')=='true')
						bannerscollection_zoominout_playOver.css('display','block');

					  //reinit content to stop videos
					  if ($(imgs[current_obj.previous_current_img_no]).attr('data-video')=='true')
							$('#contentHolderUnit_'+current_obj.previous_current_img_no, bannerscollection_zoominout_container).html($(imgs[current_obj.previous_current_img_no]).html());

					  //reposition previous image
					  initialPositioning(current_obj.previous_current_img_no,options, bannerscollection_zoominout_container,origImgsDimensions,imgs);

					  animate_texts(current_obj,options,bannerscollection_zoominout_the,bannerControls);

					  if (options.autoPlay>0 && total_images>1 && !current_obj.mouseOverBanner) {
						  clearTimeout(current_obj.timeoutID);
						  current_obj.timeoutID=setTimeout(function(){ bannerscollection_zoominout_navigation(1,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb)},options.autoPlay*1000);
					  }
				});
			}


		} // if navigateAllowed

	};







    function carouselScroll(direction,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,options,total_images,thumbsHolder_Thumb,current_obj) {
		currentCarouselLeft=bannerscollection_zoominout_thumbsHolder.css('left').substr(0,bannerscollection_zoominout_thumbsHolder.css('left').lastIndexOf('px'));
		if (direction===1 || direction===-1) {
			current_obj.isCarouselScrolling=true;
			bannerscollection_zoominout_thumbsHolder.css('opacity','0.5');
			bannerscollection_zoominout_thumbsHolder.animate({
			    opacity: 1,
			    left: '+='+direction*current_obj.carouselStep
			  }, 500, 'easeOutCubic', function() {
			      // Animation complete.
				  disableCarouselNav(current_obj,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,options,total_images,thumbsHolder_Thumb);
				  current_obj.isCarouselScrolling=false;
			});
		} else {
				if ( currentCarouselLeft != (-1) * Math.floor( current_obj.current_img_no/options.numberOfThumbsPerScreen )*current_obj.carouselStep) {
					current_obj.isCarouselScrolling=true;
					bannerscollection_zoominout_thumbsHolder.css('opacity','0.5');
					bannerscollection_zoominout_thumbsHolder.animate({
					    opacity: 1,
					    left: (-1) * Math.floor( current_obj.current_img_no/options.numberOfThumbsPerScreen )*current_obj.carouselStep
					  }, 500, 'easeOutCubic', function() {
					      // Animation complete.
						  disableCarouselNav(current_obj,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,options,total_images,thumbsHolder_Thumb);
						  current_obj.isCarouselScrolling=false;
					});
				}
		}


	};

	function disableCarouselNav(current_obj,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,options,total_images,thumbsHolder_Thumb) {
		currentCarouselLeft=bannerscollection_zoominout_thumbsHolder.css('left').substr(0,bannerscollection_zoominout_thumbsHolder.css('left').lastIndexOf('px'));
		if (currentCarouselLeft <0 ) {
			if (bannerscollection_zoominout_carouselLeftNav.hasClass('carouselLeftNavDisabled'))
				bannerscollection_zoominout_carouselLeftNav.removeClass('carouselLeftNavDisabled');
		} else {
			bannerscollection_zoominout_carouselLeftNav.addClass('carouselLeftNavDisabled');
		}

		if (Math.abs(currentCarouselLeft-current_obj.carouselStep)<(thumbsHolder_Thumb.width()+current_obj.thumbMarginLeft)*total_images) {
			if (bannerscollection_zoominout_carouselRightNav.hasClass('carouselRightNavDisabled'))
				bannerscollection_zoominout_carouselRightNav.removeClass('carouselRightNavDisabled');
		} else {
			bannerscollection_zoominout_carouselRightNav.addClass('carouselRightNavDisabled');
		}
	};




			function rearangethumbs(current_obj,options,total_images,bannerscollection_zoominout_container,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb,bannerscollection_zoominout_thumbsHolderVisibleWrapper,bannerscollection_zoominout_thumbsHolderWrapper) {
						//thumbs

						if (options.skin!="opportune") {
							bannerscollection_zoominout_thumbsHolderWrapper.css({
								"top":options.height+"px",
								"margin-top":parseInt(options.thumbsWrapperMarginTop/(options.origWidth/options.width),10)+"px",
								"height":parseInt(options.origthumbsHolderWrapperH/(options.origWidth/options.width),10)+"px"
							});

							bgTopCorrection=0;

							bannerscollection_zoominout_carouselLeftNav.css('background-position','0px '+((bannerscollection_zoominout_thumbsHolderWrapper.height()-options.origthumbsHolderWrapperH)/2+bgTopCorrection)+'px');
							bannerscollection_zoominout_carouselRightNav.css('background-position','0px '+((bannerscollection_zoominout_thumbsHolderWrapper.height()-options.origthumbsHolderWrapperH)/2+bgTopCorrection)+'px');

							bannerscollection_zoominout_thumbsHolderVisibleWrapper.css('width',options.width-bannerscollection_zoominout_carouselLeftNav.width()-bannerscollection_zoominout_carouselRightNav.width());
							options.origWidthThumbsHolderVisibleWrapper=options.origWidth-bannerscollection_zoominout_carouselLeftNav.width()-bannerscollection_zoominout_carouselRightNav.width()	;


							thumbsHolder_Thumbs.css({
								'width':parseInt(options.origThumbW/(options.origWidthThumbsHolderVisibleWrapper/bannerscollection_zoominout_thumbsHolderVisibleWrapper.width()),10)+'px',
								'height':parseInt(options.origThumbH/(options.origWidthThumbsHolderVisibleWrapper/bannerscollection_zoominout_thumbsHolderVisibleWrapper.width()),10)+'px'

							});


							if (options.numberOfThumbsPerScreen >= total_images) {
								bannerscollection_zoominout_thumbsHolderVisibleWrapper.css('left',parseInt((bannerscollection_zoominout_thumbsHolderWrapper.width() - (thumbsHolder_Thumb.width()+current_obj.thumbMarginLeft)*total_images)/2,10)+'px');
							}


							var imageInside = $('.thumbsHolder_ThumbOFF', bannerscollection_zoominout_container).find('img:first');

							imageInside.css({
								"width":thumbsHolder_Thumbs.width()+"px",
								"height":thumbsHolder_Thumbs.height()+"px",
								"margin-top":parseInt((bannerscollection_zoominout_thumbsHolderWrapper.height()-thumbsHolder_Thumbs.height())/2,10)+"px"
							});



							current_obj.thumbMarginLeft=Math.floor( (bannerscollection_zoominout_thumbsHolderWrapper.width()-bannerscollection_zoominout_carouselLeftNav.width()-bannerscollection_zoominout_carouselRightNav.width()-thumbsHolder_Thumb.width()*options.numberOfThumbsPerScreen)/(options.numberOfThumbsPerScreen-1) );
							thumb_i=-1;
							bannerscollection_zoominout_thumbsHolder.children().each(function() {
								thumb_i++;
								theThumb = $(this);
								theThumb.css('background-position','center '+(options.thumbsOnMarginTop/(options.origWidth/options.width))+'px');
								if ( thumb_i<=0 ) {
									theThumb.css('margin-left',Math.floor( ( bannerscollection_zoominout_thumbsHolderWrapper.width()-bannerscollection_zoominout_carouselLeftNav.width()-bannerscollection_zoominout_carouselRightNav.width()-(current_obj.thumbMarginLeft+theThumb.width())*(options.numberOfThumbsPerScreen-1) - theThumb.width() )/2 )+'px');
								} else {
									theThumb.css('margin-left',current_obj.thumbMarginLeft+'px');
								}
							});

							current_obj.carouselStep=(thumbsHolder_Thumb.width()+current_obj.thumbMarginLeft)*options.numberOfThumbsPerScreen;

						}
			}






			function doResize(current_obj,options,total_images,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolderVisibleWrapper,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bottomNavButs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb,bannerscollection_zoominout_leftNav,bottomNavBut,bannerscollection_zoominout_bottomNav,bannerscollection_zoominout_thumbsHolderVisibleWrapper,bannerscollection_zoominout_thumbsHolderWrapper) {

					var bodyOverflow_initial=$('body').css('overflow');
					var newTextLeft=0
					$('body').css('overflow','hidden');

					/*responsiveWidth=bannerscollection_zoominout_the.parent().parent().width();
					responsiveHeight=bannerscollection_zoominout_the.parent().parent().height();*/
					if (options.enableTouchScreen && options.fadeSlides) {
						responsiveWidth=bannerscollection_zoominout_the.parent().parent().parent().width();
						responsiveHeight=bannerscollection_zoominout_the.parent().parent().parent().height();
					} else {
						responsiveWidth=bannerscollection_zoominout_the.parent().parent().width();
						responsiveHeight=bannerscollection_zoominout_the.parent().parent().height();
					}



					if (options.responsiveRelativeToBrowser) {
						responsiveWidth=$(window).width();
						responsiveHeight=$(window).height();
					}


					if (options.width100Proc) {
						options.width=responsiveWidth;
					}

					if (options.height100Proc) {
						options.height=responsiveHeight;
					}

					if (options.origWidth!=responsiveWidth || options.width100Proc) {
						if (options.origWidth>responsiveWidth || options.width100Proc) {
							options.width=responsiveWidth;
						} else if (!options.width100Proc) {
							options.width=options.origWidth;
						}
						if (!options.height100Proc)
							options.height=options.width/current_obj.bannerRatio;

						if (options.enableTouchScreen && options.responsive && options.fadeSlides)
							options.width-=1;


						//set banner size
						bannerscollection_zoominout_container.width(options.width);
						bannerscollection_zoominout_container.height(options.height);

						bannerscollection_zoominout_contentHolderVisibleWrapper.width(options.width);
						bannerscollection_zoominout_contentHolderVisibleWrapper.height(options.height);

						bannerscollection_zoominout_contentHolder.width(options.width);
						bannerscollection_zoominout_contentHolder.height(options.height);

						bannerControls.css('margin-top',parseInt((options.height-bannerscollection_zoominout_leftNav.height())/2,10)+'px');


						bannerscollection_zoominout_reset_animate_image(current_obj,options,imgs);
						contentHolderUnit = $('.contentHolderUnit', bannerscollection_zoominout_container);
						contentHolderUnit.width(options.width);
						contentHolderUnit.height(options.height);

						if (options.enableTouchScreen && options.fadeSlides) {
							bannerscollection_zoominout_container.parent().width(options.width+1);
							bannerscollection_zoominout_container.parent().height(options.height);
						}

						holderWidth=options.width*total_images;
						for (i=0; i<total_images; i++) {
							initialPositioning(i,options, bannerscollection_zoominout_container,origImgsDimensions,imgs);
							if (options.fadeSlides) {
								newTextLeft=0;
							} else {
								newTextLeft=parseInt(i*options.width,10);
							}
							//reposition text
							$($(imgs[i]).attr('data-text-id')).css({
								'width':bannerscollection_zoominout_the.width()+'px',
								'left':newTextLeft,
								'top':bannerControls.css('top')
							});

						}



						bannerscollection_zoominout_contentHolder.width(holderWidth);

						if (options.skin=="opportune") {
							bannerscollection_zoominout_bottomNav.css({
								"left":parseInt((bannerscollection_zoominout_container.width()-bannerscollection_zoominout_bottomNav.width())/2,10)+"px",
								"top":options.height+"px"
							});
							if (options.width100Proc && options.height100Proc) {
								// nothing
							} else {
								bannerscollection_zoominout_bottomNav.css('margin-top',parseInt(options.thumbsWrapperMarginTop/(options.origWidth/options.width),10)+'px');
							}
						} else {
							rearangethumbs(current_obj,options,total_images,bannerscollection_zoominout_container,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb,bannerscollection_zoominout_thumbsHolderVisibleWrapper,bannerscollection_zoominout_thumbsHolderWrapper);
						}




					//playover
					bannerscollection_zoominout_playOver.css({
						'left':parseInt((options.width-bannerscollection_zoominout_playOver.width())/2,10)+'px',
						'top':parseInt((options.height-bannerscollection_zoominout_playOver.height())/2,10)+'px'
					});


					clearTimeout(current_obj.timeoutID);

					bannerscollection_zoominout_navigation(1,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb);


					}


					$('body').css('overflow',bodyOverflow_initial);
			}



			function getInternetExplorerVersion()
			// -1 - not IE
			// 7,8,9 etc
			{
			   var rv = -1; // Return value assumes failure.
			   if (navigator.appName == 'Microsoft Internet Explorer')
			   {
				  var ua = navigator.userAgent;
				  var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
				  if (re.exec(ua) != null)
					 rv = parseFloat( RegExp.$1 );
			   }
			   return parseInt(rv,10);
			}



	$.fn.bannerscollection_zoominout = function(options) {

		var options = $.extend({},$.fn.bannerscollection_zoominout.defaults, options);

		return this.each(function() {
			var bannerscollection_zoominout_the = $(this);
					responsiveWidth=bannerscollection_zoominout_the.parent().width();
					responsiveHeight=bannerscollection_zoominout_the.parent().height();
					if (options.responsiveRelativeToBrowser) {
						responsiveWidth=$(window).width();
						responsiveHeight=$(window).height();
					}
					options.origWidth=options.width;
					if (options.width100Proc)
						options.width=responsiveWidth;

					options.origHeight=options.height;
					if (options.height100Proc) {
						options.height=responsiveHeight;
					}

					if (options.responsive && (options.origWidth!=responsiveWidth || options.width100Proc)) {
						if (options.origWidth>responsiveWidth || options.width100Proc) {
							options.width=responsiveWidth;
						} else {
							options.width=options.origWidth;
						}
						if (!options.height100Proc)
							options.height=options.width/(options.origWidth/options.origHeight);
					}

					if (options.enableTouchScreen && options.responsive && options.fadeSlides) {
						options.width-=1;
					}



			//the controllers
			var bannerscollection_zoominout_wrap = $('<div></div>').addClass('bannerscollection_zoominout').addClass(options.skin);
			var bannerControlsDef = $('<div class="bannerControls">   <div class="leftNav"></div>   <div class="rightNav"></div>      </div>  <div class="contentHolderVisibleWrapper"><div class="contentHolder"></div></div>   <div class="playOver"></div>  <div class="thumbsHolderWrapper"><div class="thumbsHolderVisibleWrapper"><div class="thumbsHolder"></div></div></div> <canvas class="mycanvas"></canvas>');
			bannerscollection_zoominout_the.wrap(bannerscollection_zoominout_wrap);
			bannerscollection_zoominout_the.after(bannerControlsDef);



			//the elements
			var bannerscollection_zoominout_container = bannerscollection_zoominout_the.parent('.bannerscollection_zoominout');
			var bannerControls = $('.bannerControls', bannerscollection_zoominout_container);


			var bannerscollection_zoominout_contentHolderVisibleWrapper = $('.contentHolderVisibleWrapper', bannerscollection_zoominout_container);
			var bannerscollection_zoominout_contentHolder = $('.contentHolder', bannerscollection_zoominout_container);


			var bottomNav_aux=$('<div class="bottomNav"></div>');

			bannerscollection_zoominout_the.after(bottomNav_aux);

			if (!options.showAllControllers)
				bannerControls.css("display","none");




			var bannerscollection_zoominout_leftNav = $('.leftNav', bannerscollection_zoominout_container);
			var bannerscollection_zoominout_rightNav = $('.rightNav', bannerscollection_zoominout_container);
			bannerscollection_zoominout_leftNav.css("display","none");
			bannerscollection_zoominout_rightNav.css("display","none");
			if (options.showNavArrows) {
				if (options.showOnInitNavArrows) {
					bannerscollection_zoominout_leftNav.css("display","block");
					bannerscollection_zoominout_rightNav.css("display","block");
				}
			}

			var bannerscollection_zoominout_bottomNav = $('.bottomNav', bannerscollection_zoominout_container);
			var bannerscollection_zoominout_bottomOverThumb;
			if (options.skin=="opportune") {
				bannerscollection_zoominout_bottomNav.css({
					"display":"block",
					"top":options.height+"px"
				});
				if (options.width100Proc && options.height100Proc) {
					bannerscollection_zoominout_bottomNav.css("margin-top",options.thumbsWrapperMarginTop+'px');
				} else {
					bannerscollection_zoominout_bottomNav.css("margin-top",options.thumbsWrapperMarginTop/(options.origWidth/options.width)+'px');
				}
			}

			if (!options.showBottomNav) {
				bannerscollection_zoominout_bottomNav.css("display","none");
			}
			if (!options.showOnInitBottomNav) {
				bannerscollection_zoominout_bottomNav.css("left","-5000px");
			}




            //thumbs
			var bannerscollection_zoominout_thumbsHolderWrapper = $('.thumbsHolderWrapper', bannerscollection_zoominout_container);
            var bannerscollection_zoominout_thumbsHolderVisibleWrapper = $('.thumbsHolderVisibleWrapper', bannerscollection_zoominout_container);
			var bannerscollection_zoominout_thumbsHolder = $('.thumbsHolder', bannerscollection_zoominout_container);

			var bannerscollection_zoominout_carouselLeftNav;
			var bannerscollection_zoominout_carouselRightNav;
			bannerscollection_zoominout_carouselLeftNav=$('<div class="carouselLeftNav"></div>');
			bannerscollection_zoominout_carouselRightNav=$('<div class="carouselRightNav"></div>');
			bannerscollection_zoominout_thumbsHolderWrapper.append(bannerscollection_zoominout_carouselLeftNav);
			bannerscollection_zoominout_thumbsHolderWrapper.append(bannerscollection_zoominout_carouselRightNav);
			bannerscollection_zoominout_carouselRightNav.css('right','0');

			bannerscollection_zoominout_thumbsHolder.css('width',bannerscollection_zoominout_carouselLeftNav.width()+'px');

			if (!options.showBottomNav || !options.showOnInitBottomNav) {
				bannerscollection_zoominout_thumbsHolderWrapper.css({
					"opacity":0,
					"display":"none"
				});
			}


			if (options.skin!="opportune") {
					bannerscollection_zoominout_thumbsHolderWrapper.css('margin-top',parseInt(options.thumbsWrapperMarginTop/(options.origWidth/options.width),10)+'px');
			}

			var ver_ie=getInternetExplorerVersion();



			if (options.enableTouchScreen) {
				if (options.fadeSlides) {
					var randomNo=Math.floor(Math.random()*100000);

					bannerscollection_zoominout_container.wrap('<div id="zoominoutParent_'+randomNo+'" style="position:relative;" />');
					$('#zoominoutParent_'+randomNo).width(options.width+1);
					$('#zoominoutParent_'+randomNo).height(options.height);
				}


				if (ver_ie!=-1 && ver_ie==9 && options.fadeSlides && options.skin=="opportune") {
					//nothing
				} else {
          // bannerscollection_zoominout_contentHolder.css('cursor','url('+options.absUrl+'skins/hand.cur),url('+options.absUrl+'skins/hand.cur),move');
          // bannerscollection_zoominout_container.css('cursor','url('+options.absUrl+'skins/hand.cur),url('+options.absUrl+'skins/hand.cur),move');
				}
				bannerscollection_zoominout_contentHolder.css('left','0');
				if (options.fadeSlides) {
					if (ver_ie!=-1 && ver_ie==9 && options.fadeSlides && options.skin=="opportune") {
						//nothing
					} else {
							bannerscollection_zoominout_container.draggable({
								axis: 'x',
								containment: "parent",
								/*revert: true,
								distance:10,*/
								start: function(event, ui) {
									origLeft=$(this).css('left');
									bannerscollection_zoominout_playOver.css('display','none');
								},
								stop: function(event, ui) {
									if (!current_obj.slideIsRunning) {
										finalLeft=$(this).css('left');
										direction=1;
										if (origLeft<finalLeft) {
											direction=-1;
										}
										//alert (direction+' -- '+origLeft+ ' < '+finalLeft);
										$(this).css('left','0px');
										bannerscollection_zoominout_navigation(direction,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb);
									}
								}
							});
					}
				} else  {
						bannerscollection_zoominout_contentHolder.draggable({
							axis: 'x',
							distance:10,
							start: function(event, ui) {
								origLeft=parseInt($(this).css('left'),10);
								bannerscollection_zoominout_playOver.css('display','none');
							},
							stop: function(event, ui) {
								if (!current_obj.slideIsRunning) {
									finalLeft=parseInt($(this).css('left'),10);
									direction=1;
									if (origLeft<finalLeft) {
										direction=-1;
									}
									bannerscollection_zoominout_navigation(direction,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb);
								}
							}
						});
				}

			}




			//the vars
			var bannerscollection_zoominout_playOver=$('.playOver', bannerscollection_zoominout_container);
			bannerscollection_zoominout_playOver.css({
				'left':parseInt((options.width-bannerscollection_zoominout_playOver.width())/2,10)+'px',
				'top':parseInt((options.height-bannerscollection_zoominout_playOver.height())/2,10)+'px'
			});

			var current_obj = {
					current_img_no:0,
					currentImg:0,
					previous_current_img_no:0,
					slideIsRunning:false,
					mouseOverBanner:false,
					isVideoPlaying:false,
					bottomNavClicked:false,
					current_imgInside:'',
					windowWidth:0,
					carouselStep:0,
					thumbMarginLeft:0,
					timeoutID:'',
					intervalID:'',
					arcInitialTime:(new Date).getTime(),
					timeElapsed:0,
					canvas:'',
					ctx:'',
					bannerRatio:options.origWidth/options.origHeight,
					msiInterval:'',
					msiInitialTime:(new Date).getTime(),
					curZoom:0,
					cur_marginLeft:0,
					cur_marginTop:0
				};


			current_obj.canvas = $('.mycanvas', bannerscollection_zoominout_container)[0];
			current_obj.canvas.width=2*options.circleRadius+4*options.circleLineWidth;
			current_obj.canvas.height=2*options.circleRadius+4*options.circleLineWidth;


			if (ver_ie!=-1 && ver_ie<9) {
			   options.showCircleTimer=false;
			}
			if (options.showCircleTimer) {
				current_obj.ctx = current_obj.canvas.getContext('2d');
			}

			var origImgsDimensions=new Array();


			var previousBottomHovered=0;
			var i = 0;


			//set banner size
			bannerscollection_zoominout_container.width(options.width);
			bannerscollection_zoominout_container.height(options.height);

			bannerscollection_zoominout_contentHolderVisibleWrapper.width(options.width);
			bannerscollection_zoominout_contentHolderVisibleWrapper.height(options.height);

			bannerscollection_zoominout_contentHolder.width(options.width);
			bannerscollection_zoominout_contentHolder.height(options.height);

			bannerControls.css('margin-top',parseInt((options.height-bannerscollection_zoominout_leftNav.height())/2,10)+'px');




			//get images
			var theul=bannerscollection_zoominout_the.find('ul:first');

			var total_images=0;
			var imgs = theul.children();
			var content_HolderUnit;
			var holderWidth=0;
			var bottomNavBut;
			var bottomNavWidth=0;
			var bottomNavMarginTop=0;
			var imgInside;
			var thumbsHolder_Thumb;
			var thumbsHolder_MarginTop=0;
			var myopacity=0;
			var newTextLeft=0;
			imgs.each(function() {
	            current_obj.currentImg = $(this);
	            if(!current_obj.currentImg.is('li')){
	            	current_obj.currentImg = current_obj.currentImg.find('li:first');
	            }


	            if(current_obj.currentImg.is('li')){
	            	total_images++;
					myzindex=0;
					mydisplay='none';
					if (total_images==1) {
						myzindex=1;
						mydisplay='block';
					}
	            	content_HolderUnit = $('<div class="contentHolderUnit" rel="'+ (total_images-1) +'" id="contentHolderUnit_'+ (total_images-1) +'">'+current_obj.currentImg.html()+'</div>');
					if (options.fadeSlides) {
						content_HolderUnit.css({
							'position':'absolute',
							'top':0,
							'left':0,
							'z-index':myzindex,
							'display':mydisplay
						});
					} else {
						content_HolderUnit.css({
							'position':'relative',
							'float':'left'
						});
					}
	            	content_HolderUnit.width(options.width);
	            	content_HolderUnit.height(options.height);
	            	bannerscollection_zoominout_contentHolder.append(content_HolderUnit);
	            	holderWidth=holderWidth+options.width;

	            	current_obj.current_img_no=total_images-1;
	            	imgInside = $('#contentHolderUnit_'+current_obj.current_img_no, bannerscollection_zoominout_container).find('img:first');
	            	origImgsDimensions[total_images-1]=imgInside.width()+';'+imgInside.height();
	            	initialPositioning((total_images-1),options, bannerscollection_zoominout_container,origImgsDimensions,imgs);

		            //generate bottomNav
		            if (options.skin=="opportune") {
		                       bottomNavBut = $('<div class="bottomNavButtonOFF" rel="'+ (total_images-1) +'"></div>');
		                       bannerscollection_zoominout_bottomNav.append(bottomNavBut);


		                       bottomNavWidth+=parseInt(bottomNavBut.css('padding-left').substring(0, bottomNavBut.css('padding-left').length-2),10)+bottomNavBut.width();
                               bottomNavMarginTop=parseInt((bannerscollection_zoominout_bottomNav.height()-parseInt(bottomNavBut.css('height').substring(0, bottomNavBut.css('height').length-2)))/2,10);
                               bottomNavBut.css('margin-top',bottomNavMarginTop+'px');

                   }


		            //thumbs generate thumbsHolder
              if (options.skin!="opportune") {
					image_name=$(imgs[total_images-1]).attr('data-bottom-thumb');
					thumbsHolder_Thumb = $('<div class="thumbsHolder_ThumbOFF" rel="'+ (total_images-1) +'"><img src="'+ image_name + '"></div>');
		            bannerscollection_zoominout_thumbsHolder.append(thumbsHolder_Thumb);
		            if (options.origThumbW==0) {

					   	if (options.numberOfThumbsPerScreen==0) {
							options.numberOfThumbsPerScreen=Math.floor((options.origWidth-bannerscollection_zoominout_carouselLeftNav.width()-bannerscollection_zoominout_carouselRightNav.width())/thumbsHolder_Thumb.width());
						}
						options.origThumbW=thumbsHolder_Thumb.width();
						options.origThumbH=thumbsHolder_Thumb.height();
						options.origthumbsHolderWrapperH=bannerscollection_zoominout_thumbsHolderWrapper.height();
						current_obj.thumbMarginLeft=Math.floor( (options.origWidth-bannerscollection_zoominout_carouselLeftNav.width()-bannerscollection_zoominout_carouselRightNav.width()-thumbsHolder_Thumb.width()*options.numberOfThumbsPerScreen)/(options.numberOfThumbsPerScreen-1) );
                    }


		            bannerscollection_zoominout_thumbsHolder.css('width',bannerscollection_zoominout_thumbsHolder.width()+current_obj.thumbMarginLeft+thumbsHolder_Thumb.width()+'px');

		            thumbsHolder_MarginTop=parseInt((bannerscollection_zoominout_thumbsHolderWrapper.height()-parseInt(thumbsHolder_Thumb.css('height').substring(0, thumbsHolder_Thumb.css('height').length-2)))/2,10);

                }




		            if (options.fadeSlides) {
						newTextLeft=0;
					} else {
						newTextLeft=parseInt((total_images-1)*options.width,10);
					}
					bannerscollection_zoominout_contentHolder.append($(current_obj.currentImg.attr('data-text-id')));
					$(current_obj.currentImg.attr('data-text-id')).css({
						'width':bannerscollection_zoominout_the.width()+'px',
						'left':newTextLeft,
						'top':bannerControls.css('top')
					});

	            }

	        });
			bannerscollection_zoominout_contentHolder.width(holderWidth);

			bannerscollection_zoominout_bottomNav.width(bottomNavWidth);
			if (options.showOnInitBottomNav) {
				bannerscollection_zoominout_bottomNav.css("left",parseInt((bannerscollection_zoominout_container.width()-bottomNavWidth)/2,10)+'px');
			}


			//thumbs
        if (options.skin!="opportune") {
			bannerscollection_zoominout_thumbsHolderVisibleWrapper.css({
				'width':(options.origWidth-bannerscollection_zoominout_carouselLeftNav.width()-bannerscollection_zoominout_carouselRightNav.width()),
				'left':bannerscollection_zoominout_carouselLeftNav.width()+'px'
			});


			current_obj.carouselStep=(thumbsHolder_Thumb.width()+current_obj.thumbMarginLeft)*options.numberOfThumbsPerScreen;
			//disable left nav
			bannerscollection_zoominout_carouselLeftNav.addClass('carouselLeftNavDisabled');

			//disable right nav and center thumbs
			if (options.numberOfThumbsPerScreen >= total_images) {
				bannerscollection_zoominout_carouselRightNav.addClass('carouselRightNavDisabled');
				bannerscollection_zoominout_carouselLeftNav.css('display','none');
				bannerscollection_zoominout_carouselRightNav.css('display','none');
				bannerscollection_zoominout_thumbsHolderVisibleWrapper.css('left',parseInt((bannerscollection_zoominout_thumbsHolderWrapper.width() - (thumbsHolder_Thumb.width()+current_obj.thumbMarginLeft)*total_images)/2,10)+'px');
			}

			bannerscollection_zoominout_thumbsHolderWrapper.css("top",options.height+'px');


			var img_inside = $('.thumbsHolder_ThumbOFF', bannerscollection_zoominout_container).find('img:first');
			img_inside.css("margin-top",thumbsHolder_MarginTop+"px");
			options.origthumbsHolder_MarginTop=thumbsHolder_MarginTop;

         }

		var thumbsHolder_Thumbs=$('.thumbsHolder_ThumbOFF', bannerscollection_zoominout_container);
		rearangethumbs(current_obj,options,total_images,bannerscollection_zoominout_container,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb,bannerscollection_zoominout_thumbsHolderVisibleWrapper,bannerscollection_zoominout_thumbsHolderWrapper);

			//for youtube iframes
			$("iframe", bannerscollection_zoominout_container).each(function(){
			      var ifr_source = $(this).attr('src');
				  var wmode = "?wmode=transparent";
				  if ( ifr_source.indexOf('?')!=-1 )
				  	wmode = "&wmode=transparent";
			      $(this).attr('src',ifr_source+wmode);
			});




	        //initialize first number image
			current_obj.current_img_no=0;
 			/*if (options.fadeSlides) {
				  $('#contentHolderUnit_'+current_obj.current_img_no, bannerscollection_zoominout_container).css({
					  'z-index':1
				  });
			}*/



			current_obj.currentImg = $(imgs[0]);
			var firstImg=bannerscollection_zoominout_container.find('img:first');

			if (firstImg[0].complete) {
				$('.myloader', bannerscollection_zoominout_container).css('display','none');
				bannerscollection_zoominout_animate_image(current_obj,options, bannerscollection_zoominout_container,origImgsDimensions,imgs);
				animate_texts(current_obj,options,bannerscollection_zoominout_the,bannerControls);
			} else {
			firstImg.load(function() {
				$('.myloader', bannerscollection_zoominout_container).css('display','none');
				bannerscollection_zoominout_animate_image(current_obj,options, bannerscollection_zoominout_container,origImgsDimensions,imgs);
				animate_texts(current_obj,options,bannerscollection_zoominout_the,bannerControls);
			});
			}




			//pause on hover
			bannerscollection_zoominout_container.mouseenter(function() {
               	if (options.pauseOnMouseOver) {
					current_obj.mouseOverBanner=true;
					clearTimeout(current_obj.timeoutID);
					nowx = (new Date).getTime();
					current_obj.timeElapsed=current_obj.timeElapsed+(nowx-current_obj.arcInitialTime);
				}


				if (options.autoHideNavArrows && options.showNavArrows) {
					bannerscollection_zoominout_leftNav.css("display","block");
					bannerscollection_zoominout_rightNav.css("display","block");
				}
                if (options.autoHideBottomNav && options.showBottomNav) {
				    if (options.skin=="opportune") {
					   bannerscollection_zoominout_bottomNav.css({
						   "display":"block",
						   "left":parseInt((bannerscollection_zoominout_container.width()-bottomNavWidth)/2,10)+"px"
					   });
                     } else {
						 	if (options.thumbsWrapperMarginTop<0 && current_obj.isVideoPlaying) {
                       			//nothing
							} else {
								if (options.showBottomNav) {
									bannerscollection_zoominout_thumbsHolderWrapper.css({
										"display":"block"
									});
									bannerscollection_zoominout_thumbsHolderWrapper
									.stop()
									.animate({
										opacity:1
									}, 500, 'swing', function() {
									 //complete
									});
								}
							}
                     }

				}
			});

			bannerscollection_zoominout_container.mouseleave(function() {
				if (options.pauseOnMouseOver) {
					current_obj.mouseOverBanner=false;
					nowx = (new Date).getTime();
				}


				if (options.autoHideNavArrows && options.showNavArrows && !current_obj.isVideoPlaying) {
					bannerscollection_zoominout_leftNav.css("display","none");
					bannerscollection_zoominout_rightNav.css("display","none");
				}
				if (options.autoHideBottomNav && options.showBottomNav) {
				   if (options.skin=="opportune") {
       					bannerscollection_zoominout_bottomNav.css("display","none");
				   } else	 {
           				bannerscollection_zoominout_thumbsHolderWrapper
									.stop()
									.animate({
										opacity:0
									}, 300, 'swing', function() {
									 //complete
									});
				   }
				}

				if (options.autoPlay>0 && total_images>1 && !current_obj.isVideoPlaying && options.pauseOnMouseOver) {
					clearTimeout(current_obj.timeoutID);


				    current_obj.arcInitialTime = (new Date).getTime();
					var new_delay = parseInt(options.autoPlay*1000-((current_obj.timeElapsed+nowx)-current_obj.arcInitialTime),10);
					current_obj.timeoutID=setTimeout(function(){ bannerscollection_zoominout_navigation(1,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb)},new_delay);
				}
			});


			var contentHolderUnit=$('.contentHolderUnit', bannerscollection_zoominout_contentHolder);
			if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1 && navigator.userAgent.indexOf('Android') == -1) {
				contentHolderUnit.css("z-index","1");
			} else if (navigator.userAgent.indexOf('Chrome') != -1 && navigator.userAgent.indexOf('Android') == -1) {
				contentHolderUnit.css("z-index","1");
			}
			contentHolderUnit.click(function() {
				var i=$(this).attr('rel');
				//alert (i+' -- '+current_obj.current_img_no);
				if ($(imgs[current_obj.current_img_no]).attr('data-video')=='true') {
					if (i!=current_obj.current_img_no) {
						current_obj.isVideoPlaying=false;
					} else {
						clearTimeout(current_obj.timeoutID);
						bannerscollection_zoominout_reset_animate_image(current_obj,options,imgs);

						imgInside = $(this).find('img:first');
						imgInside.css('display','none');
						bannerscollection_zoominout_playOver.css('display','none');
						var texts = $(current_obj.currentImg.attr('data-text-id')).children();
				        texts.css("opacity",0);
                        current_obj.isVideoPlaying=true;

						if (options.thumbsWrapperMarginTop<0) {
                       			bannerscollection_zoominout_thumbsHolderWrapper.css("display","none");
 								if (options.skin=="opportune") {
					   				bannerscollection_zoominout_bottomNav.css("display","none");
								}
						}
						if (options.showCircleTimer) {
								clearInterval(current_obj.intervalID);

								current_obj.ctx.clearRect(0,0,current_obj.canvas.width,current_obj.canvas.height);
								current_obj.ctx.beginPath();
								current_obj.ctx.globalAlpha=0;
								current_obj.ctx.arc(options.circleRadius+2*options.circleLineWidth, options.circleRadius+2*options.circleLineWidth, options.circleRadius, 0, 0, false);
								current_obj.ctx.lineWidth = options.circleLineWidth+2;
								current_obj.ctx.strokeStyle = options.behindCircleColor;
								current_obj.ctx.stroke();


								current_obj.ctx.beginPath();
								current_obj.ctx.globalAlpha=0;
								current_obj.ctx.arc(options.circleRadius+2*options.circleLineWidth, options.circleRadius+2*options.circleLineWidth, options.circleRadius, 0, 0,  false);
								current_obj.ctx.lineWidth = options.circleLineWidth;
								current_obj.ctx.strokeStyle = options.circleColor;
								current_obj.ctx.stroke();

						}
					}
				}

				var mycurImg=$(imgs[current_obj.current_img_no]);
				if (mycurImg.attr('data-link')!=undefined && i==current_obj.current_img_no && mycurImg.attr('data-link')!='') {
					var cur_target=options.target;

					if (mycurImg.attr('data-target')!=undefined && mycurImg.attr('data-target')!=''){
						cur_target=mycurImg.attr('data-target');
					}

					if (cur_target=="_blank")
						window.open(mycurImg.attr('data-link'));
					else
						window.location = mycurImg.attr('data-link');
				}
			});


			bannerscollection_zoominout_playOver.click(function() {
				bannerscollection_zoominout_playOver.css('display','none');
				clearTimeout(current_obj.timeoutID);
				bannerscollection_zoominout_reset_animate_image(current_obj,options,imgs);

				imgInside = $('#contentHolderUnit_'+current_obj.current_img_no, bannerscollection_zoominout_container).find('img:first');
				imgInside.css('display','none');
				var all_texts = $(current_obj.currentImg.attr('data-text-id')).children();
				all_texts.css("opacity",0);
				current_obj.isVideoPlaying=true;

						if (options.thumbsWrapperMarginTop<0) {
                       			bannerscollection_zoominout_thumbsHolderWrapper.css("display","none");
								if (options.skin=="opportune") {
					   				bannerscollection_zoominout_bottomNav.css("display","none");
								}
						}

						if (options.showCircleTimer) {
								clearInterval(current_obj.intervalID);

								current_obj.ctx.clearRect(0,0,current_obj.canvas.width,current_obj.canvas.height);
								current_obj.ctx.beginPath();
								current_obj.ctx.globalAlpha=0;
								current_obj.ctx.arc(options.circleRadius+2*options.circleLineWidth, options.circleRadius+2*options.circleLineWidth, options.circleRadius, 0, 0, false);
								current_obj.ctx.lineWidth = options.circleLineWidth+2;
								current_obj.ctx.strokeStyle = options.behindCircleColor;
								current_obj.ctx.stroke();


								current_obj.ctx.beginPath();
								current_obj.ctx.globalAlpha=0;
								current_obj.ctx.arc(options.circleRadius+2*options.circleLineWidth, options.circleRadius+2*options.circleLineWidth, options.circleRadius, 0, 0,  false);
								current_obj.ctx.lineWidth = options.circleLineWidth;
								current_obj.ctx.strokeStyle = options.circleColor;
								current_obj.ctx.stroke();

						}
			});



			//controllers
			bannerscollection_zoominout_leftNav.click(function() {
				if (!current_obj.slideIsRunning) {
					current_obj.isVideoPlaying=false;

					if (options.showBottomNav) {
						bannerscollection_zoominout_thumbsHolderWrapper.css({
							"opacity":1,
							"display":"block"
						});

						if (options.skin=="opportune") {
					   		bannerscollection_zoominout_bottomNav.css("display","block");
						}
					}


					clearTimeout(current_obj.timeoutID);
					bannerscollection_zoominout_navigation(-1,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb);
				}
			});
			bannerscollection_zoominout_rightNav.click(function() {
				if (!current_obj.slideIsRunning) {
					current_obj.isVideoPlaying=false;

					if (options.showBottomNav) {
						bannerscollection_zoominout_thumbsHolderWrapper.css({
							"opacity":1,
							"display":"block"
						});
						if (options.skin=="opportune") {
					   		bannerscollection_zoominout_bottomNav.css("display","block");
						}
					}

					clearTimeout(current_obj.timeoutID);
					bannerscollection_zoominout_navigation(1,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb);
				}
			});











			var TO = false;
			$(window).resize(function() {
				var ver_ie=getInternetExplorerVersion();
				doResizeNow=true;
				if (navigator.userAgent.indexOf('Android') != -1) {
					if (options.windowOrientationScreenSize0==0 && window.orientation==0)
						options.windowOrientationScreenSize0=$(window).width();

					if (options.windowOrientationScreenSize90==0 && window.orientation==90)
						options.windowOrientationScreenSize90=$(window).height();

					if (options.windowOrientationScreenSize_90==0 && window.orientation==-90)
						options.windowOrientationScreenSize_90=$(window).height();

					if (options.windowOrientationScreenSize0 && window.orientation==0 && $(window).width()>options.windowOrientationScreenSize0)
						doResizeNow=false;

					if (options.windowOrientationScreenSize90 && window.orientation==90 && $(window).height()>options.windowOrientationScreenSize90)
						doResizeNow=false;

					if (options.windowOrientationScreenSize_90 && window.orientation==-90 && $(window).height()>options.windowOrientationScreenSize_90)
						doResizeNow=false;


					if (current_obj.windowWidth==0) {
						doResizeNow=false;
						current_obj.windowWidth=$(window).width();
					}

				}
				if (ver_ie!=-1 && ver_ie==9 && current_obj.windowWidth==0)
					doResizeNow=false;


				if (current_obj.windowWidth==$(window).width()) {
					doResizeNow=false;
					if (options.windowCurOrientation!=window.orientation && navigator.userAgent.indexOf('Android') != -1) {
						options.windowCurOrientation=window.orientation;
						doResizeNow=true;
					}
				} else
					current_obj.windowWidth=$(window).width();



				if (options.responsive && doResizeNow) {
					 if(TO !== false)
						clearTimeout(TO);


					 TO = setTimeout(function(){ doResize(current_obj,options,total_images,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolderVisibleWrapper,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bottomNavButs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb,bannerscollection_zoominout_leftNav,bottomNavBut,bannerscollection_zoominout_bottomNav,bannerscollection_zoominout_thumbsHolderVisibleWrapper,bannerscollection_zoominout_thumbsHolderWrapper) }, 300); //200 is time in miliseconds
				}
			});



			//bottom nav
			var bottomNavButs=$('.bottomNavButtonOFF', bannerscollection_zoominout_container);
            if (options.skin=="opportune") {


			bottomNavButs.click(function() {
				if (!current_obj.slideIsRunning) {
					current_obj.isVideoPlaying=false;

					var currentBut=$(this);
					var i=currentBut.attr('rel');
					//deactivate previous
					$(bottomNavButs[current_obj.current_img_no]).removeClass('bottomNavButtonON');
					current_obj.previous_current_img_no=current_obj.current_img_no;
					current_obj.bottomNavClicked=true;


					current_obj.current_img_no=i-1;
					clearTimeout(current_obj.timeoutID);

					bannerscollection_zoominout_navigation(1,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb);

				}
			});

			bottomNavButs.mouseenter(function() {
				var currentBut=$(this);
				var i=currentBut.attr('rel');



				if (options.showPreviewThumbs) {
					bannerscollection_zoominout_bottomOverThumb = $('<div class="bottomOverThumb"></div>');
					currentBut.append(bannerscollection_zoominout_bottomOverThumb);
					var image_name=$(imgs[i]).attr('data-bottom-thumb');
					var previous_image=$(imgs[previousBottomHovered]).attr('data-bottom-thumb');
					var thumb_marginLeft=80; //80 thumb width, 4 border
					var thumb_marginLeftFinal=-80;
					if (previousBottomHovered>i) {
					   thumb_marginLeft=-80;
					   thumb_marginLeftFinal=80;
		             }
					var thumb_marginTop=-80;
					bannerscollection_zoominout_bottomOverThumb.html('');
                    bannerscollection_zoominout_bottomOverThumb.html('<div class="innerBottomOverThumb"><img src="'+ previous_image + '"style="margin:0px;" id="oldThumb"><img src="'+ image_name + '" style="margin-top:'+thumb_marginTop+'px; margin-left:'+thumb_marginLeft+'px;" id="newThumb"></div>');
                    $('#newThumb')
                         .stop()
                         .animate({
                            marginLeft:'0px'
                          },150,function(){
                                bannerscollection_zoominout_bottomOverThumb.html('<div class="innerBottomOverThumb"><img src="'+ image_name + '"></div>'); //opera fix
                          });
                    $('#oldThumb')
                         .stop()
                         .animate({
                            marginLeft:thumb_marginLeftFinal+'px'
                          },150,function(){
                                //
                          });
					previousBottomHovered=i;
				}

				currentBut.addClass('bottomNavButtonON');
			});

			bottomNavButs.mouseleave(function() {
				var currentBut=$(this);
				var i=currentBut.attr('rel');

				if (options.showPreviewThumbs) {
					bannerscollection_zoominout_bottomOverThumb.remove();
				}

				if (current_obj.current_img_no!=i)
					currentBut.removeClass('bottomNavButtonON');
			});

            } //if (options.skin=="opportune") {





			//thumbs bottom nav
			thumbsHolder_Thumbs.mousedown(function() {
				if (!current_obj.slideIsRunning) {
					arrowClicked=true;
				    current_obj.isVideoPlaying=false;
					var currentBut=$(this);
					var i=currentBut.attr('rel');
					//deactivate previous
					$(thumbsHolder_Thumbs[current_obj.current_img_no]).removeClass('thumbsHolder_ThumbON');
					current_obj.previous_current_img_no=current_obj.current_img_no;
					current_obj.bottomNavClicked=true;

					current_obj.current_img_no=i-1;
					clearTimeout(current_obj.timeoutID);

					bannerscollection_zoominout_navigation(1,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb);
				}
			});
			thumbsHolder_Thumbs.mouseup(function() {
				arrowClicked=false;
			});

			thumbsHolder_Thumbs.mouseenter(function() {
				var currentBut=$(this);
				var i=currentBut.attr('rel');

				currentBut.addClass('thumbsHolder_ThumbON');
			});

			thumbsHolder_Thumbs.mouseleave(function() {
				var currentBut=$(this);
				var i=currentBut.attr('rel');

				if (current_obj.current_img_no!=i)
					currentBut.removeClass('thumbsHolder_ThumbON');
			});


			//carousel controllers
			bannerscollection_zoominout_carouselLeftNav.click(function() {
				if (!current_obj.isCarouselScrolling) {
					currentCarouselLeft=bannerscollection_zoominout_thumbsHolder.css('left').substr(0,bannerscollection_zoominout_thumbsHolder.css('left').lastIndexOf('px'));

					if (currentCarouselLeft <0 )
						carouselScroll(1,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,options,total_images,thumbsHolder_Thumb,current_obj);
				}
			});


			bannerscollection_zoominout_carouselRightNav.click(function() {
				if (!current_obj.isCarouselScrolling) {
					currentCarouselLeft=bannerscollection_zoominout_thumbsHolder.css('left').substr(0,bannerscollection_zoominout_thumbsHolder.css('left').lastIndexOf('px'));
					if (Math.abs(currentCarouselLeft-current_obj.carouselStep)<(thumbsHolder_Thumb.width()+current_obj.thumbMarginLeft)*total_images)
						carouselScroll(-1,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,options,total_images,thumbsHolder_Thumb,current_obj);
				}
			});




			//first start autoplay
			if (options.skin=="opportune") {
			   $(bottomNavButs[current_obj.current_img_no]).addClass('bottomNavButtonON');
			}
			//thumbs
			$(thumbsHolder_Thumbs[current_obj.current_img_no]).addClass('thumbsHolder_ThumbON');




			if (options.autoPlay>0 && total_images>1) {
				if (options.showCircleTimer) {
					current_obj.intervalID=setInterval(function(){the_arc(current_obj,options)}, 125);
				}
                current_obj.timeoutID=setTimeout(function(){ bannerscollection_zoominout_navigation(1,current_obj,options,total_images,bottomNavButs,imgs,bannerscollection_zoominout_the,bannerControls,bannerscollection_zoominout_contentHolder,bannerscollection_zoominout_container,bannerscollection_zoominout_playOver,origImgsDimensions,thumbsHolder_Thumbs,bannerscollection_zoominout_thumbsHolder,bannerscollection_zoominout_carouselLeftNav,bannerscollection_zoominout_carouselRightNav,thumbsHolder_Thumb)},options.autoPlay*1000);

			}

			if ($(imgs[current_obj.current_img_no]).attr('data-video')=='true')
				bannerscollection_zoominout_playOver.css('display','block');


		});
	};


	//
	// plugin skins
	//
	$.fn.bannerscollection_zoominout.defaults = {
			skin: 'opportune',
			width:918,
			height:382,
			width100Proc:false,
			height100Proc:false,
			autoPlay:16,
			fadeSlides:true,
			loop:true,


			horizontalPosition:'center',
			verticalPosition:'center',
			initialZoom:1,
			finalZoom:0.8,

			duration:20,
			durationIEfix:30,

			initialOpacity:1,

			target:"_blank",

			pauseOnMouseOver:true,
			showCircleTimer:true,
			showCircleTimerIE8IE7:false,
			circleRadius:10,
			circleLineWidth:4,
			circleColor: "#FF0000",
			circleAlpha: 100,
			behindCircleColor: "#000000",
			behindCircleAlpha: 50,
			responsive:true,
			responsiveRelativeToBrowser:true,

			numberOfThumbsPerScreen:0,

			thumbsOnMarginTop:0,
			thumbsWrapperMarginTop:0,
			showAllControllers:true,
			showNavArrows:true,
			showOnInitNavArrows:true, // o1
			autoHideNavArrows:true, // o1
			showBottomNav:true,
			showOnInitBottomNav:true, // o2
			autoHideBottomNav:false, // o2
			showPreviewThumbs:true,
			enableTouchScreen:true,
			absUrl:'',

			origWidth:0,
			origHeight:0,
			origThumbW:0,
			origThumbH:0,
			origthumbsHolderWrapperH:0,
			origthumbsHolder_MarginTop:0,
			windowOrientationScreenSize0:0,
			windowOrientationScreenSize90:0,
			windowOrientationScreenSize_90:0,
			windowCurOrientation:0

	};

})(jQuery);
;/*})'"*/;/*})'"*/
(function($, Drupal, undefined) {

  Drupal.behaviors.KenBurnsGallery = {
    attach: function(context, settings) {

      var kbImages = [];

      if ($('#kb').length > 0) {

        // if (settings.RelaProperty !== undefined) {
        //   kbImages = settings.RelaProperty.imageListKB;
        // }

        // var kb = $("#kb").Kenburns({
        //   images: kbImages,
        //   scale: 0.9,
        //   duration: 10000,
        //   fadeSpeed: 1000,
        //   ease3d: 'ease',
        // });
        var dur = 6;
        if (typeof Drupal.settings.relaKB !== 'undefined') {
          dur = parseInt(Drupal.settings.relaKB.duration);
        }

        $('#bannerscollection_zoominout_majestic', context).bannerscollection_zoominout({
          skin: 'opportune',
          responsive: true,
          pauseOnMouseOver:false,
          height:1600,
          width:1069,
          width100Proc: true,
          height100Proc: true,
          showNavArrows: false,
          showBottomNav: false,
          pauseOnMouseOver: false,
          showPreviewThumbs: false,
          showCircleTimer: false,
          duration: dur,
          autoPlay: dur - 1,
          enableTouchScreen: false,
          responsiveRelativeToBrowser:false
        });


      }

    }
  }








})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
/**
 * @file
 * Handles AJAX fetching of views, including filter submission and response.
 */
(function ($) {

  /**
   * Attaches the AJAX behavior to exposed filter forms and key views links.
   */
  Drupal.behaviors.ViewsAjaxView = {};
  Drupal.behaviors.ViewsAjaxView.attach = function() {
    if (Drupal.settings && Drupal.settings.views && Drupal.settings.views.ajaxViews) {
      $.each(Drupal.settings.views.ajaxViews, function(i, settings) {
        Drupal.views.instances[i] = new Drupal.views.ajaxView(settings);
      });
    }
  };

  Drupal.views = {};
  Drupal.views.instances = {};

  /**
   * JavaScript object for a certain view.
   */
  Drupal.views.ajaxView = function(settings) {
    var selector = '.view-dom-id-' + settings.view_dom_id;
    this.$view = $(selector);

    // If view is not present return to prevent errors.
    if (!this.$view.length) {
      return;
    }

    // Retrieve the path to use for views' ajax.
    var ajax_path = Drupal.settings.views.ajax_path;

    // If there are multiple views this might've ended up showing up multiple
    // times.
    if (ajax_path.constructor.toString().indexOf("Array") != -1) {
      ajax_path = ajax_path[0];
    }

    // Check if there are any GET parameters to send to views.
    var queryString = window.location.search || '';
    if (queryString !== '') {
      // Remove the question mark and Drupal path component if any.
      var queryString = queryString.slice(1).replace(/q=[^&]+&?|&?render=[^&]+/, '');
      if (queryString !== '') {
        // If there is a '?' in ajax_path, clean url are on and & should be
        // used to add parameters.
        queryString = ((/\?/.test(ajax_path)) ? '&' : '?') + queryString;
      }
    }

    this.element_settings = {
      url: ajax_path + queryString,
      submit: settings,
      setClick: true,
      event: 'click',
      selector: selector,
      progress: {
        type: 'throbber'
      }
    };

    this.settings = settings;

    // Add the ajax to exposed forms.
    this.$exposed_form = $('#views-exposed-form-' + settings.view_dom_id.replace(/_/g, '-'));
    this.$exposed_form.once(jQuery.proxy(this.attachExposedFormAjax, this));

    // Store Drupal.ajax objects here for all pager links.
    this.links = [];

    // Add the ajax to pagers.
    this.$view
      .once(jQuery.proxy(this.attachPagerAjax, this));

    // Add a trigger to update this view specifically. In order to trigger a
    // refresh use the following code.
    //
    // @code
    // jQuery('.view-name').trigger('RefreshView');
    // @endcode
    // Add a trigger to update this view specifically.
    var self_settings = this.element_settings;
    self_settings.event = 'RefreshView';
    var self = this;
    this.$view.once('refresh', function () {
      self.refreshViewAjax = new Drupal.ajax(self.selector, self.$view, self_settings);
    });
  };

  Drupal.views.ajaxView.prototype.attachExposedFormAjax = function() {
    var button = $('input[type=submit], button[type=submit], input[type=image]', this.$exposed_form);
    button = button[0];

    // Call the autocomplete submit before doing AJAX.
    $(button).click(function () {
      if (Drupal.autocompleteSubmit) {
        Drupal.autocompleteSubmit();
      }
    });

    this.exposedFormAjax = new Drupal.ajax($(button).attr('id'), button, this.element_settings);
  };

  /**
   * Attach the ajax behavior to each link.
   */
  Drupal.views.ajaxView.prototype.attachPagerAjax = function() {
    this.$view.find('ul.pager > li > a, ol.pager > li > a, th.views-field a, .attachment .views-summary a')
      .each(jQuery.proxy(this.attachPagerLinkAjax, this));
  };

  /**
   * Attach the ajax behavior to a single link.
   */
  Drupal.views.ajaxView.prototype.attachPagerLinkAjax = function(id, link) {
    var $link = $(link);
    var viewData = {};
    var href = $link.attr('href');
    // Don't attach to pagers inside nested views.
    if ($link.closest('.view')[0] !== this.$view[0] &&
      $link.closest('.view').parent().hasClass('attachment') === false) {
      return;
    }

    // Provide a default page if none has been set. This must be done
    // prior to merging with settings to avoid accidentally using the
    // page landed on instead of page 1.
    if (typeof(viewData.page) === 'undefined') {
      viewData.page = 0;
    }

    // Construct an object using the settings defaults and then overriding
    // with data specific to the link.
    $.extend(
      viewData,
      this.settings,
      Drupal.Views.parseQueryString(href),
      // Extract argument data from the URL.
      Drupal.Views.parseViewArgs(href, this.settings.view_base_path)
    );

    // For anchor tags, these will go to the target of the anchor rather
    // than the usual location.
    $.extend(viewData, Drupal.Views.parseViewArgs(href, this.settings.view_base_path));

    // Construct an object using the element settings defaults,
    // then overriding submit with viewData.
    var pager_settings = $.extend({}, this.element_settings);
    pager_settings.submit = viewData;
    this.pagerAjax = new Drupal.ajax(false, $link, pager_settings);
    this.links.push(this.pagerAjax);
  };

  Drupal.ajax.prototype.commands.viewsScrollTop = function (ajax, response, status) {
    // Scroll to the top of the view. This will allow users
    // to browse newly loaded content after e.g. clicking a pager
    // link.
    var offset = $(response.selector).offset();
    // We can't guarantee that the scrollable object should be
    // the body, as the view could be embedded in something
    // more complex such as a modal popup. Recurse up the DOM
    // and scroll the first element that has a non-zero top.
    var scrollTarget = response.selector;
    while ($(scrollTarget).scrollTop() == 0 && $(scrollTarget).parent()) {
      scrollTarget = $(scrollTarget).parent();
    }
    // Only scroll upward.
    if (offset.top - 10 < $(scrollTarget).scrollTop()) {
      $(scrollTarget).animate({scrollTop: (offset.top - 10)}, 500);
    }
  };

})(jQuery);
;/*})'"*/;/*})'"*/
/**
 * @file
 * Adds draggable functionality to the html list display of the view.
 */

(function($) {
  Drupal.behaviors.draggableViews = {
    attach: function(context, settings) {
      $(Drupal.settings.draggableviews_row_class).each(function(index, row_class) {
        if (Drupal.settings.draggableviews_multilist != 0) {
          return;
        }

        $('.views-form .' + row_class + ':not(.draggableviews-processed)', context)
          // Add class for theming.
          .addClass('draggableviews-processed')
          // Add sortable effect.
          .sortable({
            update: function(event, ui) {
              $(".draggableviews-weight").each(function(i, Val) {
                $(this).val(i);
              });

              if (!Drupal.settings.draggableviews_hide_confirmation) {
                if (!$(this).hasClass('draggableviews-changed')) {
                  // If view is not ajaxified.
                  if (!Drupal.settings.draggableviews_ajax) {
                    $('<div class="draggableviews-changed-warning messages warning">' + Drupal.t('Changes made in this list will not be saved until the form is submitted.') + '</div>')
                      .insertBefore($(this).parents('form div.item-list')).hide().fadeIn('slow');
                    $(this).addClass('draggableviews-changed');
                  } else {
                    // If view ajaxified.
                    if ($('.draggableviews-changed-notice').length) {
                      $('.draggableviews-changed-notice').fadeIn('slow').delay(3000).fadeOut('slow')
                    } else {
                      $('<div class="draggableviews-changed-notice messages warning">' + Drupal.t('Order of this view has been changed.') + '</div>')
                        .insertBefore($(this).parents('form div.item-list')).hide().fadeIn('slow').delay(3000).fadeOut('slow');
                      $(this).addClass('draggableviews-changed');
                    }
                  }
                }
              }
              // If Ajax enabled, we should submit the form.
              if (Drupal.settings.draggableviews_ajax) {
                $(this).parent().parent().find('.form-actions [id^="edit-submit"]').trigger('mousedown');
              }
            },
            containment: 'parent',
            cursor: 'move',
            tolerance: 'pointer',
          });
        if (Drupal.settings.draggableviews_ajax) {
          $('.views-form .' + row_class).parent().parent().find('.form-actions [id^="edit-submit"]').hide();
        }
      });
    }
  }
})(jQuery);
;/*})'"*/;/*})'"*/
(function($) {

/**
 * Drupal FieldGroup object.
 */
Drupal.FieldGroup = Drupal.FieldGroup || {};
Drupal.FieldGroup.Effects = Drupal.FieldGroup.Effects || {};
Drupal.FieldGroup.groupWithfocus = null;

Drupal.FieldGroup.setGroupWithfocus = function(element) {
  element.css({display: 'block'});
  Drupal.FieldGroup.groupWithfocus = element;
}

/**
 * Implements Drupal.FieldGroup.processHook().
 */
Drupal.FieldGroup.Effects.processFieldset = {
  execute: function (context, settings, type) {
    if (type == 'form') {
      // Add required fields mark to any fieldsets containing required fields
      $('fieldset.fieldset', context).once('fieldgroup-effects', function(i) {
        if ($(this).is('.required-fields') && $(this).find('.form-required').length > 0) {
          $('legend span.fieldset-legend', $(this)).eq(0).append(' ').append($('.form-required').eq(0).clone());
        }
        if ($('.error', $(this)).length) {
          $('legend span.fieldset-legend', $(this)).eq(0).addClass('error');
          Drupal.FieldGroup.setGroupWithfocus($(this));
        }
      });
    }
  }
}

/**
 * Implements Drupal.FieldGroup.processHook().
 */
Drupal.FieldGroup.Effects.processAccordion = {
  execute: function (context, settings, type) {
    $('div.field-group-accordion-wrapper', context).once('fieldgroup-effects', function () {
      var wrapper = $(this);

      // Get the index to set active.
      var active_index = false;
      wrapper.find('.accordion-item').each(function(i) {
        if ($(this).hasClass('field-group-accordion-active')) {
          active_index = i;
        }
      });

      wrapper.accordion({
        heightStyle: "content",
        active: active_index,
        collapsible: true,
        changestart: function(event, ui) {
          if ($(this).hasClass('effect-none')) {
            ui.options.animated = false;
          }
          else {
            ui.options.animated = 'slide';
          }
        }
      });

      if (type == 'form') {

        var $firstErrorItem = false;

        // Add required fields mark to any element containing required fields
        wrapper.find('div.field-group-accordion-item').each(function(i) {

          if ($(this).is('.required-fields') && $(this).find('.form-required').length > 0) {
            $('h3.ui-accordion-header a').eq(i).append(' ').append($('.form-required').eq(0).clone());
          }
          if ($('.error', $(this)).length) {
            // Save first error item, for focussing it.
            if (!$firstErrorItem) {
              $firstErrorItem = $(this).parent().accordion("activate" , i);
            }
            $('h3.ui-accordion-header').eq(i).addClass('error');
          }
        });

        // Save first error item, for focussing it.
        if (!$firstErrorItem) {
          $('.ui-accordion-content-active', $firstErrorItem).css({height: 'auto', width: 'auto', display: 'block'});
        }

      }
    });
  }
}

/**
 * Implements Drupal.FieldGroup.processHook().
 */
Drupal.FieldGroup.Effects.processHtabs = {
  execute: function (context, settings, type) {
    if (type == 'form') {
      // Add required fields mark to any element containing required fields
      $('fieldset.horizontal-tabs-pane', context).once('fieldgroup-effects', function(i) {
        if ($(this).is('.required-fields') && $(this).find('.form-required').length > 0) {
          $(this).data('horizontalTab').link.find('strong:first').after($('.form-required').eq(0).clone()).after(' ');
        }
        if ($('.error', $(this)).length) {
          $(this).data('horizontalTab').link.parent().addClass('error');
          Drupal.FieldGroup.setGroupWithfocus($(this));
          $(this).data('horizontalTab').focus();
        }
      });
    }
  }
}

/**
 * Implements Drupal.FieldGroup.processHook().
 */
Drupal.FieldGroup.Effects.processTabs = {
  execute: function (context, settings, type) {
    if (type == 'form') {

      var errorFocussed = false;

      // Add required fields mark to any fieldsets containing required fields
      $('fieldset.vertical-tabs-pane', context).once('fieldgroup-effects', function(i) {
        if ($(this).is('.required-fields') && $(this).find('.form-required').length > 0) {
          $(this).data('verticalTab').link.find('strong:first').after($('.form-required').eq(0).clone()).after(' ');
        }
        if ($('.error', $(this)).length) {
          $(this).data('verticalTab').link.parent().addClass('error');
          // Focus the first tab with error.
          if (!errorFocussed) {
            Drupal.FieldGroup.setGroupWithfocus($(this));
            $(this).data('verticalTab').focus();
            errorFocussed = true;
          }
        }
      });
    }
  }
}

/**
 * Implements Drupal.FieldGroup.processHook().
 *
 * TODO clean this up meaning check if this is really
 *      necessary.
 */
Drupal.FieldGroup.Effects.processDiv = {
  execute: function (context, settings, type) {

    $('div.collapsible', context).once('fieldgroup-effects', function() {
      var $wrapper = $(this);

      // Turn the legend into a clickable link, but retain span.field-group-format-toggler
      // for CSS positioning.

      var $toggler = $('span.field-group-format-toggler:first', $wrapper);
      var $link = $('<a class="field-group-format-title" href="#"></a>');
      $link.prepend($toggler.contents());

      // Add required field markers if needed
      if ($(this).is('.required-fields') && $(this).find('.form-required').length > 0) {
        $link.append(' ').append($('.form-required').eq(0).clone());
      }

      $link.appendTo($toggler);

      // .wrapInner() does not retain bound events.
      $link.click(function () {
        var wrapper = $wrapper.get(0);
        // Don't animate multiple times.
        if (!wrapper.animating) {
          wrapper.animating = true;
          var speed = $wrapper.hasClass('speed-fast') ? 300 : 1000;
          if ($wrapper.hasClass('effect-none') && $wrapper.hasClass('speed-none')) {
            $('> .field-group-format-wrapper', wrapper).toggle();
          }
          else if ($wrapper.hasClass('effect-blind')) {
            $('> .field-group-format-wrapper', wrapper).toggle('blind', {}, speed);
          }
          else {
            $('> .field-group-format-wrapper', wrapper).toggle(speed);
          }
          wrapper.animating = false;
        }
        $wrapper.toggleClass('collapsed');
        return false;
      });

    });
  }
};

/**
 * Behaviors.
 */
Drupal.behaviors.fieldGroup = {
  attach: function (context, settings) {
    settings.field_group = settings.field_group || Drupal.settings.field_group;
    if (settings.field_group == undefined) {
      return;
    }

    // Execute all of them.
    $.each(Drupal.FieldGroup.Effects, function (func) {
      // We check for a wrapper function in Drupal.field_group as
      // alternative for dynamic string function calls.
      var type = func.toLowerCase().replace("process", "");
      if (settings.field_group[type] != undefined && $.isFunction(this.execute)) {
        this.execute(context, settings, settings.field_group[type]);
      }
    });

    // Fixes css for fieldgroups under vertical tabs.
    $('.fieldset-wrapper .fieldset > legend').css({display: 'block'});
    $('.vertical-tabs fieldset.fieldset').addClass('default-fallback');

    // Add a new ID to each fieldset.
    $('.group-wrapper .horizontal-tabs-panes > fieldset', context).once('group-wrapper-panes-processed', function() {
      // Tats bad, but we have to keep the actual id to prevent layouts to break.
      var fieldgroupID = 'field_group-' + $(this).attr('id');
      $(this).attr('id', fieldgroupID);
    });
    // Set the hash in url to remember last userselection.
    $('.group-wrapper ul li').once('group-wrapper-ul-processed', function() {
      var fieldGroupNavigationListIndex = $(this).index();
      $(this).children('a').click(function() {
        var fieldset = $('.group-wrapper fieldset').get(fieldGroupNavigationListIndex);
        // Grab the first id, holding the wanted hashurl.
        var hashUrl = $(fieldset).attr('id').replace(/^field_group-/, '').split(' ')[0];
        window.location.hash = hashUrl;
      });
    });

  }
};

})(jQuery);
;/*})'"*/;/*})'"*/
/**
 * Owl carousel
 * @version 2.0.0
 * @author Bartosz Wojciechowski
 * @license The MIT License (MIT)
 * @todo Lazy Load Icon
 * @todo prevent animationend bubling
 * @todo itemsScaleUp
 * @todo Test Zepto
 * @todo stagePadding calculate wrong active classes
 */
;
(function($, window, document, undefined) {

  var drag, state, e;

  /**
   * Template for status information about drag and touch events.
   * @private
   */
  drag = {
    start: 0,
    startX: 0,
    startY: 0,
    current: 0,
    currentX: 0,
    currentY: 0,
    offsetX: 0,
    offsetY: 0,
    distance: null,
    startTime: 0,
    endTime: 0,
    updatedX: 0,
    targetEl: null
  };

  /**
   * Template for some status informations.
   * @private
   */
  state = {
    isTouch: false,
    isScrolling: false,
    isSwiping: false,
    direction: false,
    inMotion: false
  };

  /**
   * Event functions references.
   * @private
   */
  e = {
    _onDragStart: null,
    _onDragMove: null,
    _onDragEnd: null,
    _transitionEnd: null,
    _resizer: null,
    _responsiveCall: null,
    _goToLoop: null,
    _checkVisibile: null
  };

  /**
   * Creates a carousel.
   * @class The Owl Carousel.
   * @public
   * @param {HTMLElement|jQuery} element - The element to create the carousel for.
   * @param {Object} [options] - The options
   */
  function Owl(element, options) {

    /**
     * Current settings for the carousel.
     * @public
     */
    this.settings = null;

    /**
     * Current options set by the caller including defaults.
     * @public
     */
    this.options = $.extend({}, Owl.Defaults, options);

    /**
     * Plugin element.
     * @public
     */
    this.$element = $(element);

    /**
     * Caches informations about drag and touch events.
     */
    this.drag = $.extend({}, drag);

    /**
     * Caches some status informations.
     * @protected
     */
    this.state = $.extend({}, state);

    /**
     * @protected
     * @todo Must be documented
     */
    this.e = $.extend({}, e);

    /**
     * References to the running plugins of this carousel.
     * @protected
     */
    this._plugins = {};

    /**
 *    Currently suppressed events to prevent them from beeing retriggered.
     * @protected
     */
    this._supress = {};

    /**
     * Absolute current position.
     * @protected
     */
    this._current = null;

    /**
     * Animation speed in milliseconds.
     * @protected
     */
    this._speed = null;

    /**
     * Coordinates of all items in pixel.
     * @todo The name of this member is missleading.
     * @protected
     */
    this._coordinates = [];

    /**
     * Current breakpoint.
     * @todo Real media queries would be nice.
     * @protected
     */
    this._breakpoint = null;

    /**
     * Current width of the plugin element.
     */
    this._width = null;

    /**
     * All real items.
     * @protected
     */
    this._items = [];

    /**
     * All cloned items.
     * @protected
     */
    this._clones = [];

    /**
     * Merge values of all items.
     * @todo Maybe this could be part of a plugin.
     * @protected
     */
    this._mergers = [];

    /**
     * Invalidated parts within the update process.
     * @protected
     */
    this._invalidated = {};

    /**
     * Ordered list of workers for the update process.
     * @protected
     */
    this._pipe = [];

    $.each(Owl.Plugins, $.proxy(function(key, plugin) {
      this._plugins[key[0].toLowerCase() + key.slice(1)] = new plugin(this);
    }, this));

    $.each(Owl.Pipe, $.proxy(function(priority, worker) {
      this._pipe.push({
        'filter': worker.filter,
        'run': $.proxy(worker.run, this)
      });
    }, this));

    this.setup();
    this.initialize();
  }

  /**
   * Default options for the carousel.
   * @public
   */
  Owl.Defaults = {
    items: 3,
    loop: false,
    center: false,

    mouseDrag: true,
    touchDrag: true,
    pullDrag: true,
    freeDrag: false,

    margin: 0,
    stagePadding: 0,

    merge: false,
    mergeFit: true,
    autoWidth: false,

    startPosition: 0,
    rtl: false,

    smartSpeed: 250,
    fluidSpeed: false,
    dragEndSpeed: false,

    responsive: {},
    responsiveRefreshRate: 200,
    responsiveBaseElement: window,
    responsiveClass: false,

    fallbackEasing: 'swing',

    info: false,

    nestedItemSelector: false,
    itemElement: 'div',
    stageElement: 'div',

    // Classes and Names
    themeClass: 'owl-theme',
    baseClass: 'owl-carousel',
    itemClass: 'owl-item',
    centerClass: 'center',
    activeClass: 'active'
  };

  /**
   * Enumeration for width.
   * @public
   * @readonly
   * @enum {String}
   */
  Owl.Width = {
    Default: 'default',
    Inner: 'inner',
    Outer: 'outer'
  };

  /**
   * Contains all registered plugins.
   * @public
   */
  Owl.Plugins = {};

  /**
   * Update pipe.
   */
  Owl.Pipe = [{
    filter: ['width', 'items', 'settings'],
    run: function(cache) {
      cache.current = this._items && this._items[this.relative(this._current)];
    }
  }, {
    filter: ['items', 'settings'],
    run: function() {
      var cached = this._clones,
        clones = this.$stage.children('.cloned');

      if (clones.length !== cached.length || (!this.settings.loop && cached.length > 0)) {
        this.$stage.children('.cloned').remove();
        this._clones = [];
      }
    }
  }, {
    filter: ['items', 'settings'],
    run: function() {
      var i, n,
        clones = this._clones,
        items = this._items,
        delta = this.settings.loop ? clones.length - Math.max(this.settings.items * 2, 4) : 0;

      for (i = 0, n = Math.abs(delta / 2); i < n; i++) {
        if (delta > 0) {
          this.$stage.children().eq(items.length + clones.length - 1).remove();
          clones.pop();
          this.$stage.children().eq(0).remove();
          clones.pop();
        } else {
          clones.push(clones.length / 2);
          this.$stage.append(items[clones[clones.length - 1]].clone().addClass('cloned'));
          clones.push(items.length - 1 - (clones.length - 1) / 2);
          this.$stage.prepend(items[clones[clones.length - 1]].clone().addClass('cloned'));
        }
      }
    }
  }, {
    filter: ['width', 'items', 'settings'],
    run: function() {
      var rtl = (this.settings.rtl ? 1 : -1),
        width = (this.width() / this.settings.items).toFixed(3),
        coordinate = 0,
        merge, i, n;

      this._coordinates = [];
      for (i = 0, n = this._clones.length + this._items.length; i < n; i++) {
        merge = this._mergers[this.relative(i)];
        merge = (this.settings.mergeFit && Math.min(merge, this.settings.items)) || merge;
        coordinate += (this.settings.autoWidth ? this._items[this.relative(i)].width() + this.settings.margin : width * merge) * rtl;

        this._coordinates.push(coordinate);
      }
    }
  }, {
    filter: ['width', 'items', 'settings'],
    run: function() {
      var i, n, width = (this.width() / this.settings.items).toFixed(3),
        css = {
          'width': Math.abs(this._coordinates[this._coordinates.length - 1]) + this.settings.stagePadding * 2,
          'padding-left': this.settings.stagePadding || '',
          'padding-right': this.settings.stagePadding || ''
        };

      this.$stage.css(css);

      css = {
        'width': this.settings.autoWidth ? 'auto' : width - this.settings.margin
      };
      css[this.settings.rtl ? 'margin-left' : 'margin-right'] = this.settings.margin;

      if (!this.settings.autoWidth && $.grep(this._mergers, function(v) {
          return v > 1
        }).length > 0) {
        for (i = 0, n = this._coordinates.length; i < n; i++) {
          css.width = Math.abs(this._coordinates[i]) - Math.abs(this._coordinates[i - 1] || 0) - this.settings.margin;
          this.$stage.children().eq(i).css(css);
        }
      } else {
        this.$stage.children().css(css);
      }
    }
  }, {
    filter: ['width', 'items', 'settings'],
    run: function(cache) {
      cache.current && this.reset(this.$stage.children().index(cache.current));
    }
  }, {
    filter: ['position'],
    run: function() {
      this.animate(this.coordinates(this._current));
    }
  }, {
    filter: ['width', 'position', 'items', 'settings'],
    run: function() {
      var rtl = this.settings.rtl ? 1 : -1,
        padding = this.settings.stagePadding * 2,
        begin = this.coordinates(this.current()) + padding,
        end = begin + this.width() * rtl,
        inner, outer, matches = [],
        i, n;

      for (i = 0, n = this._coordinates.length; i < n; i++) {
        inner = this._coordinates[i - 1] || 0;
        outer = Math.abs(this._coordinates[i]) + padding * rtl;

        if ((this.op(inner, '<=', begin) && (this.op(inner, '>', end))) ||
          (this.op(outer, '<', begin) && this.op(outer, '>', end))) {
          matches.push(i);
        }
      }

      this.$stage.children('.' + this.settings.activeClass).removeClass(this.settings.activeClass);
      this.$stage.children(':eq(' + matches.join('), :eq(') + ')').addClass(this.settings.activeClass);

      if (this.settings.center) {
        this.$stage.children('.' + this.settings.centerClass).removeClass(this.settings.centerClass);
        this.$stage.children().eq(this.current()).addClass(this.settings.centerClass);
      }
    }
  }];

  /**
   * Initializes the carousel.
   * @protected
   */
  Owl.prototype.initialize = function() {
    this.trigger('initialize');

    this.$element
      .addClass(this.settings.baseClass)
      .addClass(this.settings.themeClass)
      .toggleClass('owl-rtl', this.settings.rtl);

    // check support
    this.browserSupport();

    if (this.settings.autoWidth && this.state.imagesLoaded !== true) {
      var imgs, nestedSelector, width;
      imgs = this.$element.find('img');
      nestedSelector = this.settings.nestedItemSelector ? '.' + this.settings.nestedItemSelector : undefined;
      width = this.$element.children(nestedSelector).width();

      if (imgs.length && width <= 0) {
        this.preloadAutoWidthImages(imgs);
        return false;
      }
    }

    this.$element.addClass('owl-loading');

    // create stage
    this.$stage = $('<' + this.settings.stageElement + ' class="owl-stage"/>')
      .wrap('<div class="owl-stage-outer">');

    // append stage
    this.$element.append(this.$stage.parent());

    // append content
    this.replace(this.$element.children().not(this.$stage.parent()));

    // set view width
    this._width = this.$element.width();

    // update view
    this.refresh();

    this.$element.removeClass('owl-loading').addClass('owl-loaded');

    // attach generic events
    this.eventsCall();

    // attach generic events
    this.internalEvents();

    // attach custom control events
    this.addTriggerableEvents();

    this.trigger('initialized');
  };

  /**
   * Setups the current settings.
   * @todo Remove responsive classes. Why should adaptive designs be brought into IE8?
   * @todo Support for media queries by using `matchMedia` would be nice.
   * @public
   */
  Owl.prototype.setup = function() {
    var viewport = this.viewport(),
      overwrites = this.options.responsive,
      match = -1,
      settings = null;

    if (!overwrites) {
      settings = $.extend({}, this.options);
    } else {
      $.each(overwrites, function(breakpoint) {
        if (breakpoint <= viewport && breakpoint > match) {
          match = Number(breakpoint);
        }
      });

      settings = $.extend({}, this.options, overwrites[match]);
      delete settings.responsive;

      // responsive class
      if (settings.responsiveClass) {
        this.$element.attr('class', function(i, c) {
          return c.replace(/\b owl-responsive-\S+/g, '');
        }).addClass('owl-responsive-' + match);
      }
    }

    if (this.settings === null || this._breakpoint !== match) {
      this.trigger('change', {
        property: {
          name: 'settings',
          value: settings
        }
      });
      this._breakpoint = match;
      this.settings = settings;
      this.invalidate('settings');
      this.trigger('changed', {
        property: {
          name: 'settings',
          value: this.settings
        }
      });
    }
  };

  /**
   * Updates option logic if necessery.
   * @protected
   */
  Owl.prototype.optionsLogic = function() {
    // Toggle Center class
    this.$element.toggleClass('owl-center', this.settings.center);

    // if items number is less than in body
    if (this.settings.loop && this._items.length < this.settings.items) {
      this.settings.loop = false;
    }

    if (this.settings.autoWidth) {
      this.settings.stagePadding = false;
      this.settings.merge = false;
    }
  };

  /**
   * Prepares an item before add.
   * @todo Rename event parameter `content` to `item`.
   * @protected
   * @returns {jQuery|HTMLElement} - The item container.
   */
  Owl.prototype.prepare = function(item) {
    var event = this.trigger('prepare', {
      content: item
    });

    if (!event.data) {
      event.data = $('<' + this.settings.itemElement + '/>')
        .addClass(this.settings.itemClass).append(item)
    }

    this.trigger('prepared', {
      content: event.data
    });

    return event.data;
  };

  /**
   * Updates the view.
   * @public
   */
  Owl.prototype.update = function() {
    var i = 0,
      n = this._pipe.length,
      filter = $.proxy(function(p) {
        return this[p]
      }, this._invalidated),
      cache = {};

    while (i < n) {
      if (this._invalidated.all || $.grep(this._pipe[i].filter, filter).length > 0) {
        this._pipe[i].run(cache);
      }
      i++;
    }

    this._invalidated = {};
  };

  /**
   * Gets the width of the view.
   * @public
   * @param {Owl.Width} [dimension=Owl.Width.Default] - The dimension to return.
   * @returns {Number} - The width of the view in pixel.
   */
  Owl.prototype.width = function(dimension) {
    dimension = dimension || Owl.Width.Default;
    switch (dimension) {
      case Owl.Width.Inner:
      case Owl.Width.Outer:
        return this._width;
      default:
        return this._width - this.settings.stagePadding * 2 + this.settings.margin;
    }
  };

  /**
   * Refreshes the carousel primarily for adaptive purposes.
   * @public
   */
  Owl.prototype.refresh = function() {
    if (this._items.length === 0) {
      return false;
    }

    var start = new Date().getTime();

    this.trigger('refresh');

    this.setup();

    this.optionsLogic();

    // hide and show methods helps here to set a proper widths,
    // this prevents scrollbar to be calculated in stage width
    this.$stage.addClass('owl-refresh');

    this.update();

    this.$stage.removeClass('owl-refresh');

    this.state.orientation = window.orientation;

    this.watchVisibility();

    this.trigger('refreshed');
  };

  /**
   * Save internal event references and add event based functions.
   * @protected
   */
  Owl.prototype.eventsCall = function() {
    // Save events references
    this.e._onDragStart = $.proxy(function(e) {
      this.onDragStart(e);
    }, this);
    this.e._onDragMove = $.proxy(function(e) {
      this.onDragMove(e);
    }, this);
    this.e._onDragEnd = $.proxy(function(e) {
      this.onDragEnd(e);
    }, this);
    this.e._onResize = $.proxy(function(e) {
      this.onResize(e);
    }, this);
    this.e._transitionEnd = $.proxy(function(e) {
      this.transitionEnd(e);
    }, this);
    this.e._preventClick = $.proxy(function(e) {
      this.preventClick(e);
    }, this);
  };

  /**
   * Checks window `resize` event.
   * @protected
   */
  Owl.prototype.onThrottledResize = function() {
    window.clearTimeout(this.resizeTimer);
    this.resizeTimer = window.setTimeout(this.e._onResize, this.settings.responsiveRefreshRate);
  };

  /**
   * Checks window `resize` event.
   * @protected
   */
  Owl.prototype.onResize = function() {
    if (!this._items.length) {
      return false;
    }

    if (this._width === this.$element.width()) {
      return false;
    }

    if (this.trigger('resize').isDefaultPrevented()) {
      return false;
    }

    this._width = this.$element.width();

    this.invalidate('width');

    this.refresh();

    this.trigger('resized');
  };

  /**
   * Checks for touch/mouse drag event type and add run event handlers.
   * @protected
   */
  Owl.prototype.eventsRouter = function(event) {
    var type = event.type;

    if (type === "mousedown" || type === "touchstart") {
      this.onDragStart(event);
    } else if (type === "mousemove" || type === "touchmove") {
      this.onDragMove(event);
    } else if (type === "mouseup" || type === "touchend") {
      this.onDragEnd(event);
    } else if (type === "touchcancel") {
      this.onDragEnd(event);
    }
  };

  /**
   * Checks for touch/mouse drag options and add necessery event handlers.
   * @protected
   */
  Owl.prototype.internalEvents = function() {
    var isTouch = isTouchSupport(),
      isTouchIE = isTouchSupportIE();

    if (this.settings.mouseDrag) {
      this.$stage.on('mousedown', $.proxy(function(event) {
        this.eventsRouter(event)
      }, this));
      this.$stage.on('dragstart', function() {
        return false
      });
      this.$stage.get(0).onselectstart = function() {
        return false
      };
    } else {
      this.$element.addClass('owl-text-select-on');
    }

    if (this.settings.touchDrag && !isTouchIE) {
      this.$stage.on('touchstart touchcancel', $.proxy(function(event) {
        this.eventsRouter(event)
      }, this));
    }

    // catch transitionEnd event
    if (this.transitionEndVendor) {
      this.on(this.$stage.get(0), this.transitionEndVendor, this.e._transitionEnd, false);
    }

    // responsive
    if (this.settings.responsive !== false) {
      this.on(window, 'resize', $.proxy(this.onThrottledResize, this));
    }
  };

  /**
   * Handles touchstart/mousedown event.
   * @protected
   * @param {Event} event - The event arguments.
   */
  Owl.prototype.onDragStart = function(event) {
    var ev, isTouchEvent, pageX, pageY, animatedPos;

    ev = event.originalEvent || event || window.event;

    // prevent right click
    if (ev.which === 3 || this.state.isTouch) {
      return false;
    }

    if (ev.type === 'mousedown') {
      this.$stage.addClass('owl-grab');
    }

    this.trigger('drag');
    this.drag.startTime = new Date().getTime();
    this.speed(0);
    this.state.isTouch = true;
    this.state.isScrolling = false;
    this.state.isSwiping = false;
    this.drag.distance = 0;

    pageX = getTouches(ev).x;
    pageY = getTouches(ev).y;

    // get stage position left
    this.drag.offsetX = this.$stage.position().left;
    this.drag.offsetY = this.$stage.position().top;

    if (this.settings.rtl) {
      this.drag.offsetX = this.$stage.position().left + this.$stage.width() - this.width() +
        this.settings.margin;
    }

    // catch position // ie to fix
    if (this.state.inMotion && this.support3d) {
      animatedPos = this.getTransformProperty();
      this.drag.offsetX = animatedPos;
      this.animate(animatedPos);
      this.state.inMotion = true;
    } else if (this.state.inMotion && !this.support3d) {
      this.state.inMotion = false;
      return false;
    }

    this.drag.startX = pageX - this.drag.offsetX;
    this.drag.startY = pageY - this.drag.offsetY;

    this.drag.start = pageX - this.drag.startX;
    this.drag.targetEl = ev.target || ev.srcElement;
    this.drag.updatedX = this.drag.start;

    // to do/check
    // prevent links and images dragging;
    if (this.drag.targetEl.tagName === "IMG" || this.drag.targetEl.tagName === "A") {
      this.drag.targetEl.draggable = false;
    }

    $(document).on('mousemove.owl.dragEvents mouseup.owl.dragEvents touchmove.owl.dragEvents touchend.owl.dragEvents', $.proxy(function(event) {
      this.eventsRouter(event)
    }, this));
  };

  /**
   * Handles the touchmove/mousemove events.
   * @todo Simplify
   * @protected
   * @param {Event} event - The event arguments.
   */
  Owl.prototype.onDragMove = function(event) {
    var ev, isTouchEvent, pageX, pageY, minValue, maxValue, pull;

    if (!this.state.isTouch) {
      return;
    }

    if (this.state.isScrolling) {
      return;
    }

    ev = event.originalEvent || event || window.event;

    pageX = getTouches(ev).x;
    pageY = getTouches(ev).y;

    // Drag Direction
    this.drag.currentX = pageX - this.drag.startX;
    this.drag.currentY = pageY - this.drag.startY;
    this.drag.distance = this.drag.currentX - this.drag.offsetX;

    // Check move direction
    if (this.drag.distance < 0) {
      this.state.direction = this.settings.rtl ? 'right' : 'left';
    } else if (this.drag.distance > 0) {
      this.state.direction = this.settings.rtl ? 'left' : 'right';
    }
    // Loop
    if (this.settings.loop) {
      if (this.op(this.drag.currentX, '>', this.coordinates(this.minimum())) && this.state.direction === 'right') {
        this.drag.currentX -= (this.settings.center && this.coordinates(0)) - this.coordinates(this._items.length);
      } else if (this.op(this.drag.currentX, '<', this.coordinates(this.maximum())) && this.state.direction === 'left') {
        this.drag.currentX += (this.settings.center && this.coordinates(0)) - this.coordinates(this._items.length);
      }
    } else {
      // pull
      minValue = this.settings.rtl ? this.coordinates(this.maximum()) : this.coordinates(this.minimum());
      maxValue = this.settings.rtl ? this.coordinates(this.minimum()) : this.coordinates(this.maximum());
      pull = this.settings.pullDrag ? this.drag.distance / 5 : 0;
      this.drag.currentX = Math.max(Math.min(this.drag.currentX, minValue + pull), maxValue + pull);
    }

    // Lock browser if swiping horizontal

    if ((this.drag.distance > 8 || this.drag.distance < -8)) {
      if (ev.preventDefault !== undefined) {
        ev.preventDefault();
      } else {
        ev.returnValue = false;
      }
      this.state.isSwiping = true;
    }

    this.drag.updatedX = this.drag.currentX;

    // Lock Owl if scrolling
    if ((this.drag.currentY > 16 || this.drag.currentY < -16) && this.state.isSwiping === false) {
      this.state.isScrolling = true;
      this.drag.updatedX = this.drag.start;
    }

    this.animate(this.drag.updatedX);
  };

  /**
   * Handles the touchend/mouseup events.
   * @protected
   */
  Owl.prototype.onDragEnd = function(event) {
    var compareTimes, distanceAbs, closest;

    if (!this.state.isTouch) {
      return;
    }

    if (event.type === 'mouseup') {
      this.$stage.removeClass('owl-grab');
    }

    this.trigger('dragged');

    // prevent links and images dragging;
    this.drag.targetEl.removeAttribute("draggable");

    // remove drag event listeners

    this.state.isTouch = false;
    this.state.isScrolling = false;
    this.state.isSwiping = false;

    // to check
    if (this.drag.distance === 0 && this.state.inMotion !== true) {
      this.state.inMotion = false;
      return false;
    }

    // prevent clicks while scrolling

    this.drag.endTime = new Date().getTime();
    compareTimes = this.drag.endTime - this.drag.startTime;
    distanceAbs = Math.abs(this.drag.distance);

    // to test
    if (distanceAbs > 3 || compareTimes > 300) {
      this.removeClick(this.drag.targetEl);
    }

    closest = this.closest(this.drag.updatedX);

    this.speed(this.settings.dragEndSpeed || this.settings.smartSpeed);
    this.current(closest);
    this.invalidate('position');
    this.update();

    // if pullDrag is off then fire transitionEnd event manually when stick
    // to border
    if (!this.settings.pullDrag && this.drag.updatedX === this.coordinates(closest)) {
      this.transitionEnd();
    }

    this.drag.distance = 0;

    $(document).off('.owl.dragEvents');
  };

  /**
   * Attaches `preventClick` to disable link while swipping.
   * @protected
   * @param {HTMLElement} [target] - The target of the `click` event.
   */
  Owl.prototype.removeClick = function(target) {
    this.drag.targetEl = target;
    $(target).on('click.preventClick', this.e._preventClick);
    // to make sure click is removed:
    window.setTimeout(function() {
      $(target).off('click.preventClick');
    }, 300);
  };

  /**
   * Suppresses click event.
   * @protected
   * @param {Event} ev - The event arguments.
   */
  Owl.prototype.preventClick = function(ev) {
    if (ev.preventDefault) {
      ev.preventDefault();
    } else {
      ev.returnValue = false;
    }
    if (ev.stopPropagation) {
      ev.stopPropagation();
    }
    $(ev.target).off('click.preventClick');
  };

  /**
   * Catches stage position while animate (only CSS3).
   * @protected
   * @returns
   */
  Owl.prototype.getTransformProperty = function() {
    var transform, matrix3d;

    transform = window.getComputedStyle(this.$stage.get(0), null).getPropertyValue(this.vendorName + 'transform');
    // var transform = this.$stage.css(this.vendorName + 'transform')
    transform = transform.replace(/matrix(3d)?\(|\)/g, '').split(',');
    matrix3d = transform.length === 16;

    return matrix3d !== true ? transform[4] : transform[12];
  };

  /**
   * Gets absolute position of the closest item for a coordinate.
   * @todo Setting `freeDrag` makes `closest` not reusable. See #165.
   * @protected
   * @param {Number} coordinate - The coordinate in pixel.
   * @return {Number} - The absolute position of the closest item.
   */
  Owl.prototype.closest = function(coordinate) {
    var position = -1,
      pull = 30,
      width = this.width(),
      coordinates = this.coordinates();

    if (!this.settings.freeDrag) {
      // check closest item
      $.each(coordinates, $.proxy(function(index, value) {
        if (coordinate > value - pull && coordinate < value + pull) {
          position = index;
        } else if (this.op(coordinate, '<', value) &&
          this.op(coordinate, '>', coordinates[index + 1] || value - width)) {
          position = this.state.direction === 'left' ? index + 1 : index;
        }
        return position === -1;
      }, this));
    }

    if (!this.settings.loop) {
      // non loop boundries
      if (this.op(coordinate, '>', coordinates[this.minimum()])) {
        position = coordinate = this.minimum();
      } else if (this.op(coordinate, '<', coordinates[this.maximum()])) {
        position = coordinate = this.maximum();
      }
    }

    return position;
  };

  /**
   * Animates the stage.
   * @public
   * @param {Number} coordinate - The coordinate in pixels.
   */
  Owl.prototype.animate = function(coordinate) {
    this.trigger('translate');
    this.state.inMotion = this.speed() > 0;

    if (this.support3d) {
      this.$stage.css({
        transform: 'translate3d(' + coordinate + 'px' + ',0px, 0px)',
        transition: (this.speed() / 1000) + 's'
      });
    } else if (this.state.isTouch) {
      this.$stage.css({
        left: coordinate + 'px'
      });
    } else {
      this.$stage.animate({
        left: coordinate
      }, this.speed() / 1000, this.settings.fallbackEasing, $.proxy(function() {
        if (this.state.inMotion) {
          this.transitionEnd();
        }
      }, this));
    }
  };

  /**
   * Sets the absolute position of the current item.
   * @public
   * @param {Number} [position] - The new absolute position or nothing to leave it unchanged.
   * @returns {Number} - The absolute position of the current item.
   */
  Owl.prototype.current = function(position) {
    if (position === undefined) {
      return this._current;
    }

    if (this._items.length === 0) {
      return undefined;
    }

    position = this.normalize(position);

    if (this._current !== position) {
      var event = this.trigger('change', {
        property: {
          name: 'position',
          value: position
        }
      });

      if (event.data !== undefined) {
        position = this.normalize(event.data);
      }

      this._current = position;

      this.invalidate('position');

      this.trigger('changed', {
        property: {
          name: 'position',
          value: this._current
        }
      });
    }

    return this._current;
  };

  /**
   * Invalidates the given part of the update routine.
   * @param {String} part - The part to invalidate.
   */
  Owl.prototype.invalidate = function(part) {
    this._invalidated[part] = true;
  }

  /**
   * Resets the absolute position of the current item.
   * @public
   * @param {Number} position - The absolute position of the new item.
   */
  Owl.prototype.reset = function(position) {
    position = this.normalize(position);

    if (position === undefined) {
      return;
    }

    this._speed = 0;
    this._current = position;

    this.suppress(['translate', 'translated']);

    this.animate(this.coordinates(position));

    this.release(['translate', 'translated']);
  };

  /**
   * Normalizes an absolute or a relative position for an item.
   * @public
   * @param {Number} position - The absolute or relative position to normalize.
   * @param {Boolean} [relative=false] - Whether the given position is relative or not.
   * @returns {Number} - The normalized position.
   */
  Owl.prototype.normalize = function(position, relative) {
    var n = (relative ? this._items.length : this._items.length + this._clones.length);

    if (!$.isNumeric(position) || n < 1) {
      return undefined;
    }

    if (this._clones.length) {
      position = ((position % n) + n) % n;
    } else {
      position = Math.max(this.minimum(relative), Math.min(this.maximum(relative), position));
    }

    return position;
  };

  /**
   * Converts an absolute position for an item into a relative position.
   * @public
   * @param {Number} position - The absolute position to convert.
   * @returns {Number} - The converted position.
   */
  Owl.prototype.relative = function(position) {
    position = this.normalize(position);
    position = position - this._clones.length / 2;
    return this.normalize(position, true);
  };

  /**
   * Gets the maximum position for an item.
   * @public
   * @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
   * @returns {Number}
   */
  Owl.prototype.maximum = function(relative) {
    var maximum, width, i = 0,
      coordinate,
      settings = this.settings;

    if (relative) {
      return this._items.length - 1;
    }

    if (!settings.loop && settings.center) {
      maximum = this._items.length - 1;
    } else if (!settings.loop && !settings.center) {
      maximum = this._items.length - settings.items;
    } else if (settings.loop || settings.center) {
      maximum = this._items.length + settings.items;
    } else if (settings.autoWidth || settings.merge) {
      revert = settings.rtl ? 1 : -1;
      width = this.$stage.width() - this.$element.width();
      while (coordinate = this.coordinates(i)) {
        if (coordinate * revert >= width) {
          break;
        }
        maximum = ++i;
      }
    } else {
      throw 'Can not detect maximum absolute position.'
    }

    return maximum;
  };

  /**
   * Gets the minimum position for an item.
   * @public
   * @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
   * @returns {Number}
   */
  Owl.prototype.minimum = function(relative) {
    if (relative) {
      return 0;
    }

    return this._clones.length / 2;
  };

  /**
   * Gets an item at the specified relative position.
   * @public
   * @param {Number} [position] - The relative position of the item.
   * @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
   */
  Owl.prototype.items = function(position) {
    if (position === undefined) {
      return this._items.slice();
    }

    position = this.normalize(position, true);
    return this._items[position];
  };

  /**
   * Gets an item at the specified relative position.
   * @public
   * @param {Number} [position] - The relative position of the item.
   * @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
   */
  Owl.prototype.mergers = function(position) {
    if (position === undefined) {
      return this._mergers.slice();
    }

    position = this.normalize(position, true);
    return this._mergers[position];
  };

  /**
   * Gets the absolute positions of clones for an item.
   * @public
   * @param {Number} [position] - The relative position of the item.
   * @returns {Array.<Number>} - The absolute positions of clones for the item or all if no position was given.
   */
  Owl.prototype.clones = function(position) {
    var odd = this._clones.length / 2,
      even = odd + this._items.length,
      map = function(index) {
        return index % 2 === 0 ? even + index / 2 : odd - (index + 1) / 2
      };

    if (position === undefined) {
      return $.map(this._clones, function(v, i) {
        return map(i)
      });
    }

    return $.map(this._clones, function(v, i) {
      return v === position ? map(i) : null
    });
  };

  /**
   * Sets the current animation speed.
   * @public
   * @param {Number} [speed] - The animation speed in milliseconds or nothing to leave it unchanged.
   * @returns {Number} - The current animation speed in milliseconds.
   */
  Owl.prototype.speed = function(speed) {
    if (speed !== undefined) {
      this._speed = speed;
    }

    return this._speed;
  };

  /**
   * Gets the coordinate of an item.
   * @todo The name of this method is missleanding.
   * @public
   * @param {Number} position - The absolute position of the item within `minimum()` and `maximum()`.
   * @returns {Number|Array.<Number>} - The coordinate of the item in pixel or all coordinates.
   */
  Owl.prototype.coordinates = function(position) {
    var coordinate = null;

    if (position === undefined) {
      return $.map(this._coordinates, $.proxy(function(coordinate, index) {
        return this.coordinates(index);
      }, this));
    }

    if (this.settings.center) {
      coordinate = this._coordinates[position];
      coordinate += (this.width() - coordinate + (this._coordinates[position - 1] || 0)) / 2 * (this.settings.rtl ? -1 : 1);
    } else {
      coordinate = this._coordinates[position - 1] || 0;
    }

    return coordinate;
  };

  /**
   * Calculates the speed for a translation.
   * @protected
   * @param {Number} from - The absolute position of the start item.
   * @param {Number} to - The absolute position of the target item.
   * @param {Number} [factor=undefined] - The time factor in milliseconds.
   * @returns {Number} - The time in milliseconds for the translation.
   */
  Owl.prototype.duration = function(from, to, factor) {
    return Math.min(Math.max(Math.abs(to - from), 1), 6) * Math.abs((factor || this.settings.smartSpeed));
  };

  /**
   * Slides to the specified item.
   * @public
   * @param {Number} position - The position of the item.
   * @param {Number} [speed] - The time in milliseconds for the transition.
   */
  Owl.prototype.to = function(position, speed) {
    if (this.settings.loop) {
      var distance = position - this.relative(this.current()),
        revert = this.current(),
        before = this.current(),
        after = this.current() + distance,
        direction = before - after < 0 ? true : false,
        items = this._clones.length + this._items.length;

      if (after < this.settings.items && direction === false) {
        revert = before + this._items.length;
        this.reset(revert);
      } else if (after >= items - this.settings.items && direction === true) {
        revert = before - this._items.length;
        this.reset(revert);
      }
      window.clearTimeout(this.e._goToLoop);
      this.e._goToLoop = window.setTimeout($.proxy(function() {
        this.speed(this.duration(this.current(), revert + distance, speed));
        this.current(revert + distance);
        this.update();
      }, this), 30);
    } else {
      this.speed(this.duration(this.current(), position, speed));
      this.current(position);
      this.update();
    }
  };

  /**
   * Slides to the next item.
   * @public
   * @param {Number} [speed] - The time in milliseconds for the transition.
   */
  Owl.prototype.next = function(speed) {
    speed = speed || false;
    this.to(this.relative(this.current()) + 1, speed);
  };

  /**
   * Slides to the previous item.
   * @public
   * @param {Number} [speed] - The time in milliseconds for the transition.
   */
  Owl.prototype.prev = function(speed) {
    speed = speed || false;
    this.to(this.relative(this.current()) - 1, speed);
  };

  /**
   * Handles the end of an animation.
   * @protected
   * @param {Event} event - The event arguments.
   */
  Owl.prototype.transitionEnd = function(event) {

    // if css2 animation then event object is undefined
    if (event !== undefined) {
      event.stopPropagation();

      // Catch only owl-stage transitionEnd event
      if ((event.target || event.srcElement || event.originalTarget) !== this.$stage.get(0)) {
        return false;
      }
    }

    this.state.inMotion = false;
    this.trigger('translated');
  };

  /**
   * Gets viewport width.
   * @protected
   * @return {Number} - The width in pixel.
   */
  Owl.prototype.viewport = function() {
    var width;
    if (this.options.responsiveBaseElement !== window) {
      width = $(this.options.responsiveBaseElement).width();
    } else if (window.innerWidth) {
      width = window.innerWidth;
    } else if (document.documentElement && document.documentElement.clientWidth) {
      width = document.documentElement.clientWidth;
    } else {
      throw 'Can not detect viewport width.';
    }
    return width;
  };

  /**
   * Replaces the current content.
   * @public
   * @param {HTMLElement|jQuery|String} content - The new content.
   */
  Owl.prototype.replace = function(content) {
    this.$stage.empty();
    this._items = [];

    if (content) {
      content = (content instanceof jQuery) ? content : $(content);
    }

    if (this.settings.nestedItemSelector) {
      content = content.find('.' + this.settings.nestedItemSelector);
    }

    content.filter(function() {
      return this.nodeType === 1;
    }).each($.proxy(function(index, item) {
      item = this.prepare(item);
      this.$stage.append(item);
      this._items.push(item);
      this._mergers.push(item.find('[data-merge]').andSelf('[data-merge]').attr('data-merge') * 1 || 1);
    }, this));

    this.reset($.isNumeric(this.settings.startPosition) ? this.settings.startPosition : 0);

    this.invalidate('items');
  };

  /**
   * Adds an item.
   * @todo Use `item` instead of `content` for the event arguments.
   * @public
   * @param {HTMLElement|jQuery|String} content - The item content to add.
   * @param {Number} [position] - The relative position at which to insert the item otherwise the item will be added to the end.
   */
  Owl.prototype.add = function(content, position) {
    position = position === undefined ? this._items.length : this.normalize(position, true);

    this.trigger('add', {
      content: content,
      position: position
    });

    if (this._items.length === 0 || position === this._items.length) {
      this.$stage.append(content);
      this._items.push(content);
      this._mergers.push(content.find('[data-merge]').andSelf('[data-merge]').attr('data-merge') * 1 || 1);
    } else {
      this._items[position].before(content);
      this._items.splice(position, 0, content);
      this._mergers.splice(position, 0, content.find('[data-merge]').andSelf('[data-merge]').attr('data-merge') * 1 || 1);
    }

    this.invalidate('items');

    this.trigger('added', {
      content: content,
      position: position
    });
  };

  /**
   * Removes an item by its position.
   * @todo Use `item` instead of `content` for the event arguments.
   * @public
   * @param {Number} position - The relative position of the item to remove.
   */
  Owl.prototype.remove = function(position) {
    position = this.normalize(position, true);

    if (position === undefined) {
      return;
    }

    this.trigger('remove', {
      content: this._items[position],
      position: position
    });

    this._items[position].remove();
    this._items.splice(position, 1);
    this._mergers.splice(position, 1);

    this.invalidate('items');

    this.trigger('removed', {
      content: null,
      position: position
    });
  };

  /**
   * Adds triggerable events.
   * @protected
   */
  Owl.prototype.addTriggerableEvents = function() {
    var handler = $.proxy(function(callback, event) {
      return $.proxy(function(e) {
        if (e.relatedTarget !== this) {
          this.suppress([event]);
          callback.apply(this, [].slice.call(arguments, 1));
          this.release([event]);
        }
      }, this);
    }, this);

    $.each({
      'next': this.next,
      'prev': this.prev,
      'to': this.to,
      'destroy': this.destroy,
      'refresh': this.refresh,
      'replace': this.replace,
      'add': this.add,
      'remove': this.remove
    }, $.proxy(function(event, callback) {
      this.$element.on(event + '.owl.carousel', handler(callback, event + '.owl.carousel'));
    }, this));

  };

  /**
   * Watches the visibility of the carousel element.
   * @protected
   */
  Owl.prototype.watchVisibility = function() {

    // test on zepto
    if (!isElVisible(this.$element.get(0))) {
      this.$element.addClass('owl-hidden');
      window.clearInterval(this.e._checkVisibile);
      this.e._checkVisibile = window.setInterval($.proxy(checkVisible, this), 500);
    }

    function isElVisible(el) {
      return el.offsetWidth > 0 && el.offsetHeight > 0;
    }

    function checkVisible() {
      if (isElVisible(this.$element.get(0))) {
        this.$element.removeClass('owl-hidden');
        this.refresh();
        window.clearInterval(this.e._checkVisibile);
      }
    }
  };

  /**
   * Preloads images with auto width.
   * @protected
   * @todo Still to test
   */
  Owl.prototype.preloadAutoWidthImages = function(imgs) {
    var loaded, that, $el, img;

    loaded = 0;
    that = this;
    imgs.each(function(i, el) {
      $el = $(el);
      img = new Image();

      img.onload = function() {
        loaded++;
        $el.attr('src', img.src);
        $el.css('opacity', 1);
        if (loaded >= imgs.length) {
          that.state.imagesLoaded = true;
          that.initialize();
        }
      };

      img.src = $el.attr('src') || $el.attr('data-src') || $el.attr('data-src-retina');
    });
  };

  /**
   * Destroys the carousel.
   * @public
   */
  Owl.prototype.destroy = function() {

    if (this.$element.hasClass(this.settings.themeClass)) {
      this.$element.removeClass(this.settings.themeClass);
    }

    if (this.settings.responsive !== false) {
      $(window).off('resize.owl.carousel');
    }

    if (this.transitionEndVendor) {
      this.off(this.$stage.get(0), this.transitionEndVendor, this.e._transitionEnd);
    }

    for (var i in this._plugins) {
      this._plugins[i].destroy();
    }

    if (this.settings.mouseDrag || this.settings.touchDrag) {
      this.$stage.off('mousedown touchstart touchcancel');
      $(document).off('.owl.dragEvents');
      this.$stage.get(0).onselectstart = function() {};
      this.$stage.off('dragstart', function() {
        return false
      });
    }

    // remove event handlers in the ".owl.carousel" namespace
    this.$element.off('.owl');

    this.$stage.children('.cloned').remove();
    this.e = null;
    this.$element.removeData('owlCarousel');

    this.$stage.children().contents().unwrap();
    this.$stage.children().unwrap();
    this.$stage.unwrap();
  };

  /**
   * Operators to calculate right-to-left and left-to-right.
   * @protected
   * @param {Number} [a] - The left side operand.
   * @param {String} [o] - The operator.
   * @param {Number} [b] - The right side operand.
   */
  Owl.prototype.op = function(a, o, b) {
    var rtl = this.settings.rtl;
    switch (o) {
      case '<':
        return rtl ? a > b : a < b;
      case '>':
        return rtl ? a < b : a > b;
      case '>=':
        return rtl ? a <= b : a >= b;
      case '<=':
        return rtl ? a >= b : a <= b;
      default:
        break;
    }
  };

  /**
   * Attaches to an internal event.
   * @protected
   * @param {HTMLElement} element - The event source.
   * @param {String} event - The event name.
   * @param {Function} listener - The event handler to attach.
   * @param {Boolean} capture - Wether the event should be handled at the capturing phase or not.
   */
  Owl.prototype.on = function(element, event, listener, capture) {
    if (element.addEventListener) {
      element.addEventListener(event, listener, capture);
    } else if (element.attachEvent) {
      element.attachEvent('on' + event, listener);
    }
  };

  /**
   * Detaches from an internal event.
   * @protected
   * @param {HTMLElement} element - The event source.
   * @param {String} event - The event name.
   * @param {Function} listener - The attached event handler to detach.
   * @param {Boolean} capture - Wether the attached event handler was registered as a capturing listener or not.
   */
  Owl.prototype.off = function(element, event, listener, capture) {
    if (element.removeEventListener) {
      element.removeEventListener(event, listener, capture);
    } else if (element.detachEvent) {
      element.detachEvent('on' + event, listener);
    }
  };

  /**
   * Triggers an public event.
   * @protected
   * @param {String} name - The event name.
   * @param {*} [data=null] - The event data.
   * @param {String} [namespace=.owl.carousel] - The event namespace.
   * @returns {Event} - The event arguments.
   */
  Owl.prototype.trigger = function(name, data, namespace) {
    var status = {
        item: {
          count: this._items.length,
          index: this.current()
        }
      },
      handler = $.camelCase(
        $.grep(['on', name, namespace], function(v) {
          return v
        })
        .join('-').toLowerCase()
      ),
      event = $.Event(
        [name, 'owl', namespace || 'carousel'].join('.').toLowerCase(),
        $.extend({
          relatedTarget: this
        }, status, data)
      );

    if (!this._supress[name]) {
      $.each(this._plugins, function(name, plugin) {
        if (plugin.onTrigger) {
          plugin.onTrigger(event);
        }
      });

      this.$element.trigger(event);

      if (this.settings && typeof this.settings[handler] === 'function') {
        this.settings[handler].apply(this, event);
      }
    }

    return event;
  };

  /**
   * Suppresses events.
   * @protected
   * @param {Array.<String>} events - The events to suppress.
   */
  Owl.prototype.suppress = function(events) {
    $.each(events, $.proxy(function(index, event) {
      this._supress[event] = true;
    }, this));
  }

  /**
   * Releases suppressed events.
   * @protected
   * @param {Array.<String>} events - The events to release.
   */
  Owl.prototype.release = function(events) {
    $.each(events, $.proxy(function(index, event) {
      delete this._supress[event];
    }, this));
  }

  /**
   * Checks the availability of some browser features.
   * @protected
   */
  Owl.prototype.browserSupport = function() {
    this.support3d = isPerspective();

    if (this.support3d) {
      this.transformVendor = isTransform();

      // take transitionend event name by detecting transition
      var endVendors = ['transitionend', 'webkitTransitionEnd', 'transitionend', 'oTransitionEnd'];
      this.transitionEndVendor = endVendors[isTransition()];

      // take vendor name from transform name
      this.vendorName = this.transformVendor.replace(/Transform/i, '');
      this.vendorName = this.vendorName !== '' ? '-' + this.vendorName.toLowerCase() + '-' : '';
    }

    this.state.orientation = window.orientation;
  };

  /**
   * Get touch/drag coordinats.
   * @private
   * @param {event} - mousedown/touchstart event
   * @returns {object} - Contains X and Y of current mouse/touch position
   */

  function getTouches(event) {
    if (event.touches !== undefined) {
      return {
        x: event.touches[0].pageX,
        y: event.touches[0].pageY
      };
    }

    if (event.touches === undefined) {
      if (event.pageX !== undefined) {
        return {
          x: event.pageX,
          y: event.pageY
        };
      }

      if (event.pageX === undefined) {
        return {
          x: event.clientX,
          y: event.clientY
        };
      }
    }
  }

  /**
   * Checks for CSS support.
   * @private
   * @param {Array} array - The CSS properties to check for.
   * @returns {Array} - Contains the supported CSS property name and its index or `false`.
   */
  function isStyleSupported(array) {
    var p, s, fake = document.createElement('div'),
      list = array;
    for (p in list) {
      s = list[p];
      if (typeof fake.style[s] !== 'undefined') {
        fake = null;
        return [s, p];
      }
    }
    return [false];
  }

  /**
   * Checks for CSS transition support.
   * @private
   * @todo Realy bad design
   * @returns {Number}
   */
  function isTransition() {
    return isStyleSupported(['transition', 'WebkitTransition', 'MozTransition', 'OTransition'])[1];
  }

  /**
   * Checks for CSS transform support.
   * @private
   * @returns {String} The supported property name or false.
   */
  function isTransform() {
    return isStyleSupported(['transform', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform'])[0];
  }

  /**
   * Checks for CSS perspective support.
   * @private
   * @returns {String} The supported property name or false.
   */
  function isPerspective() {
    return isStyleSupported(['perspective', 'webkitPerspective', 'MozPerspective', 'OPerspective', 'MsPerspective'])[0];
  }

  /**
   * Checks wether touch is supported or not.
   * @private
   * @returns {Boolean}
   */
  function isTouchSupport() {
    return 'ontouchstart' in window || !!(navigator.msMaxTouchPoints);
  }

  /**
   * Checks wether touch is supported or not for IE.
   * @private
   * @returns {Boolean}
   */
  function isTouchSupportIE() {
    return window.navigator.msPointerEnabled;
  }

  /**
   * The jQuery Plugin for the Owl Carousel
   * @public
   */
  $.fn.owlCarousel = function(options) {
    return this.each(function() {
      if (!$(this).data('owlCarousel')) {
        $(this).data('owlCarousel', new Owl(this, options));
      }
    });
  };

  /**
   * The constructor for the jQuery Plugin
   * @public
   */
  $.fn.owlCarousel.Constructor = Owl;

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

/**
 * Lazy Plugin
 * @version 2.0.0
 * @author Bartosz Wojciechowski
 * @license The MIT License (MIT)
 */
;
(function($, window, document, undefined) {

  /**
   * Creates the lazy plugin.
   * @class The Lazy Plugin
   * @param {Owl} carousel - The Owl Carousel
   */
  var Lazy = function(carousel) {

    /**
     * Reference to the core.
     * @protected
     * @type {Owl}
     */
    this._core = carousel;

    /**
     * Already loaded items.
     * @protected
     * @type {Array.<jQuery>}
     */
    //this._loaded = [];

    /**
     * Event handlers.
     * @protected
     * @type {Object}
     */
    this._handlers = {
      'initialized.owl.carousel change.owl.carousel': $.proxy(function(e) {
        if (!e.namespace) {
          return;
        }

        if (!this._core.settings || !this._core.settings.lazyLoad) {
          return;
        }

        if ((e.property && e.property.name == 'position') || e.type == 'initialized') {
          var settings = this._core.settings,
            n = (settings.center && Math.ceil(settings.items / 2) || settings.items),
            i = ((settings.center && n * -1) || 0),
            position = ((e.property && e.property.value) || this._core.current()) + i,
            clones = this._core.clones().length,
            load = $.proxy(function(i, v) {
              this.load(v)
            }, this);

          while (i++ < n) {
            this.load(clones / 2 + this._core.relative(position));
            clones && $.each(this._core.clones(this._core.relative(position++)), load);
          }
        }
      }, this)
    };

    // set the default options
    this._core.options = $.extend({}, Lazy.Defaults, this._core.options);

    // register event handler
    this._core.$element.on(this._handlers);
  }

  /**
   * Default options.
   * @public
   */
  Lazy.Defaults = {
    lazyLoad: false
  }

  /**
   * Loads all resources of an item at the specified position.
   * @param {Number} position - The absolute position of the item.
   * @protected
   */
  Lazy.prototype.load = function(position) {
    var $item = this._core.$stage.children().eq(position),
      $elements = $item && $item.find('.owl-lazy');

    // if (!$elements || $.inArray($item.get(0), this._loaded) > -1) {
    //   return;
    // }

    $elements.each($.proxy(function(index, element) {
      var $element = $(element),
        image,
        url = (window.devicePixelRatio > 1 && $element.attr('data-src-retina')) || $element.attr('data-src');

      this._core.trigger('load', {
        element: $element,
        url: url
      }, 'lazy');

      if ($element.is('img')) {
        $element.one('load.owl.lazy', $.proxy(function() {
          $element.css('opacity', 1);
          this._core.trigger('loaded', {
            element: $element,
            url: url
          }, 'lazy');
        }, this)).attr('src', url);
      } else {
        image = new Image();
        image.onload = $.proxy(function() {
          $element.css({
            'background-image': 'url(' + url + ')',
            'opacity': '1'
          });
          this._core.trigger('loaded', {
            element: $element,
            url: url
          }, 'lazy');
        }, this);
        image.src = url;
      }
    }, this));

    //this._loaded.push($item.get(0));
  }

  /**
   * Destroys the plugin.
   * @public
   */
  Lazy.prototype.destroy = function() {
    var handler, property;

    for (handler in this.handlers) {
      this._core.$element.off(handler, this.handlers[handler]);
    }
    for (property in Object.getOwnPropertyNames(this)) {
      typeof this[property] != 'function' && (this[property] = null);
    }
  }

  $.fn.owlCarousel.Constructor.Plugins.Lazy = Lazy;

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

/**
 * AutoHeight Plugin
 * @version 2.0.0
 * @author Bartosz Wojciechowski
 * @license The MIT License (MIT)
 */
;
(function($, window, document, undefined) {

  /**
   * Creates the auto height plugin.
   * @class The Auto Height Plugin
   * @param {Owl} carousel - The Owl Carousel
   */
  var AutoHeight = function(carousel) {
    /**
     * Reference to the core.
     * @protected
     * @type {Owl}
     */
    this._core = carousel;

    /**
     * All event handlers.
     * @protected
     * @type {Object}
     */
    this._handlers = {
      'initialized.owl.carousel': $.proxy(function() {
        if (this._core.settings.autoHeight) {
          this.update();
        }
      }, this),
      'changed.owl.carousel': $.proxy(function(e) {
        if (this._core.settings.autoHeight && e.property.name == 'position') {
          this.update();
        }
      }, this),
      'loaded.owl.lazy': $.proxy(function(e) {
        if (this._core.settings.autoHeight && e.element.closest('.' + this._core.settings.itemClass) ===
          this._core.$stage.children().eq(this._core.current())) {
          this.update();
        }
      }, this)
    };

    // set default options
    this._core.options = $.extend({}, AutoHeight.Defaults, this._core.options);

    // register event handlers
    this._core.$element.on(this._handlers);
  };

  /**
   * Default options.
   * @public
   */
  AutoHeight.Defaults = {
    autoHeight: false,
    autoHeightClass: 'owl-height'
  };

  /**
   * Updates the view.
   */
  AutoHeight.prototype.update = function() {
    this._core.$stage.parent()
      .height(this._core.$stage.children().eq(this._core.current()).height())
      .addClass(this._core.settings.autoHeightClass);
  };

  AutoHeight.prototype.destroy = function() {
    var handler, property;

    for (handler in this._handlers) {
      this._core.$element.off(handler, this._handlers[handler]);
    }
    for (property in Object.getOwnPropertyNames(this)) {
      typeof this[property] != 'function' && (this[property] = null);
    }
  };

  $.fn.owlCarousel.Constructor.Plugins.AutoHeight = AutoHeight;

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

/**
 * Video Plugin
 * @version 2.0.0
 * @author Bartosz Wojciechowski
 * @license The MIT License (MIT)
 */
;
(function($, window, document, undefined) {

  /**
   * Creates the video plugin.
   * @class The Video Plugin
   * @param {Owl} carousel - The Owl Carousel
   */
  var Video = function(carousel) {
    /**
     * Reference to the core.
     * @protected
     * @type {Owl}
     */
    this._core = carousel;

    /**
     * Cache all video URLs.
     * @protected
     * @type {Object}
     */
    this._videos = {};

    /**
     * Current playing item.
     * @protected
     * @type {jQuery}
     */
    this._playing = null;

    /**
     * Whether this is in fullscreen or not.
     * @protected
     * @type {Boolean}
     */
    this._fullscreen = false;

    /**
     * All event handlers.
     * @protected
     * @type {Object}
     */
    this._handlers = {
      'resize.owl.carousel': $.proxy(function(e) {
        if (this._core.settings.video && !this.isInFullScreen()) {
          e.preventDefault();
        }
      }, this),
      'refresh.owl.carousel changed.owl.carousel': $.proxy(function(e) {
        if (this._playing) {
          this.stop();
        }
      }, this),
      'prepared.owl.carousel': $.proxy(function(e) {
        var $element = $(e.content).find('.owl-video');
        if ($element.length) {
          $element.css('display', 'none');
          this.fetch($element, $(e.content));
        }
      }, this)
    };

    // set default options
    this._core.options = $.extend({}, Video.Defaults, this._core.options);

    // register event handlers
    this._core.$element.on(this._handlers);

    this._core.$element.on('click.owl.video', '.owl-video-play-icon', $.proxy(function(e) {
      this.play(e);
    }, this));
  };

  /**
   * Default options.
   * @public
   */
  Video.Defaults = {
    video: false,
    videoHeight: false,
    videoWidth: false
  };

  /**
   * Gets the video ID and the type (YouTube/Vimeo only).
   * @protected
   * @param {jQuery} target - The target containing the video data.
   * @param {jQuery} item - The item containing the video.
   */
  Video.prototype.fetch = function(target, item) {

    var type = target.attr('data-vimeo-id') ? 'vimeo' : 'youtube',
      id = target.attr('data-vimeo-id') || target.attr('data-youtube-id'),
      width = target.attr('data-width') || this._core.settings.videoWidth,
      height = target.attr('data-height') || this._core.settings.videoHeight,
      url = target.attr('href');

    if (url) {
      id = url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);

      if (id[3].indexOf('youtu') > -1) {
        type = 'youtube';
      } else if (id[3].indexOf('vimeo') > -1) {
        type = 'vimeo';
      } else {
        throw new Error('Video URL not supported.');
      }
      id = id[6];
    } else {
      throw new Error('Missing video URL.');
    }

    this._videos[url] = {
      type: type,
      id: id,
      width: width,
      height: height
    };

    item.attr('data-video', url);

    this.thumbnail(target, this._videos[url]);
  };

  /**
   * Creates video thumbnail.
   * @protected
   * @param {jQuery} target - The target containing the video data.
   * @param {Object} info - The video info object.
   * @see `fetch`
   */
  Video.prototype.thumbnail = function(target, video) {

    var tnLink,
      icon,
      path,
      dimensions = video.width && video.height ? 'style="width:' + video.width + 'px;height:' + video.height + 'px;"' : '',
      customTn = target.find('img'),
      srcType = 'src',
      lazyClass = '',
      settings = this._core.settings,
      create = function(path) {
        icon = '<div class="owl-video-play-icon"></div>';

        if (settings.lazyLoad) {
          tnLink = '<div class="owl-video-tn ' + lazyClass + '" ' + srcType + '="' + path + '"></div>';
        } else {
          tnLink = '<div class="owl-video-tn" style="opacity:1;background-image:url(' + path + ')"></div>';
        }
        target.after(tnLink);
        target.after(icon);
      };

    // wrap video content into owl-video-wrapper div
    target.wrap('<div class="owl-video-wrapper"' + dimensions + '></div>');

    if (this._core.settings.lazyLoad) {
      srcType = 'data-src';
      lazyClass = 'owl-lazy';
    }

    // custom thumbnail
    if (customTn.length) {
      create(customTn.attr(srcType));
      customTn.remove();
      return false;
    }

    if (video.type === 'youtube') {
      path = "http://img.youtube.com/vi/" + video.id + "/hqdefault.jpg";
      create(path);
    } else if (video.type === 'vimeo') {
      $.ajax({
        type: 'GET',
        url: 'http://vimeo.com/api/v2/video/' + video.id + '.json',
        jsonp: 'callback',
        dataType: 'jsonp',
        success: function(data) {
          path = data[0].thumbnail_large;
          create(path);
        }
      });
    }
  };

  /**
   * Stops the current video.
   * @public
   */
  Video.prototype.stop = function() {
    this._core.trigger('stop', null, 'video');
    this._playing.find('.owl-video-frame').remove();
    this._playing.removeClass('owl-video-playing');
    this._playing = null;
  };

  /**
   * Starts the current video.
   * @public
   * @param {Event} ev - The event arguments.
   */
  Video.prototype.play = function(ev) {
    this._core.trigger('play', null, 'video');

    if (this._playing) {
      this.stop();
    }

    var target = $(ev.target || ev.srcElement),
      item = target.closest('.' + this._core.settings.itemClass),
      video = this._videos[item.attr('data-video')],
      width = video.width || '100%',
      height = video.height || this._core.$stage.height(),
      html, wrap;

    if (video.type === 'youtube') {
      html = '<iframe width="' + width + '" height="' + height + '" src="http://www.youtube.com/embed/' +
        video.id + '?autoplay=1&v=' + video.id + '" frameborder="0" allowfullscreen></iframe>';
    } else if (video.type === 'vimeo') {
      html = '<iframe src="http://player.vimeo.com/video/' + video.id + '?autoplay=1" width="' + width +
        '" height="' + height +
        '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
    }

    item.addClass('owl-video-playing');
    this._playing = item;

    wrap = $('<div style="height:' + height + 'px; width:' + width + 'px" class="owl-video-frame">' +
      html + '</div>');
    target.after(wrap);
  };

  /**
   * Checks whether an video is currently in full screen mode or not.
   * @todo Bad style because looks like a readonly method but changes members.
   * @protected
   * @returns {Boolean}
   */
  Video.prototype.isInFullScreen = function() {

    // if Vimeo Fullscreen mode
    var element = document.fullscreenElement || document.mozFullScreenElement ||
      document.webkitFullscreenElement;

    if (element && $(element).parent().hasClass('owl-video-frame')) {
      this._core.speed(0);
      this._fullscreen = true;
    }

    if (element && this._fullscreen && this._playing) {
      return false;
    }

    // comming back from fullscreen
    if (this._fullscreen) {
      this._fullscreen = false;
      return false;
    }

    // check full screen mode and window orientation
    if (this._playing) {
      if (this._core.state.orientation !== window.orientation) {
        this._core.state.orientation = window.orientation;
        return false;
      }
    }

    return true;
  };

  /**
   * Destroys the plugin.
   */
  Video.prototype.destroy = function() {
    var handler, property;

    this._core.$element.off('click.owl.video');

    for (handler in this._handlers) {
      this._core.$element.off(handler, this._handlers[handler]);
    }
    for (property in Object.getOwnPropertyNames(this)) {
      typeof this[property] != 'function' && (this[property] = null);
    }
  };

  $.fn.owlCarousel.Constructor.Plugins.Video = Video;

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

/**
 * Animate Plugin
 * @version 2.0.0
 * @author Bartosz Wojciechowski
 * @license The MIT License (MIT)
 */
;
(function($, window, document, undefined) {

  /**
   * Creates the animate plugin.
   * @class The Navigation Plugin
   * @param {Owl} scope - The Owl Carousel
   */
  var Animate = function(scope) {
    this.core = scope;
    this.core.options = $.extend({}, Animate.Defaults, this.core.options);
    this.swapping = true;
    this.previous = undefined;
    this.next = undefined;

    this.handlers = {
      'change.owl.carousel': $.proxy(function(e) {
        if (e.property.name == 'position') {
          this.previous = this.core.current();
          this.next = e.property.value;
        }
      }, this),
      'drag.owl.carousel dragged.owl.carousel translated.owl.carousel': $.proxy(function(e) {
        this.swapping = e.type == 'translated';
      }, this),
      'translate.owl.carousel': $.proxy(function(e) {
        if (this.swapping && (this.core.options.animateOut || this.core.options.animateIn)) {
          this.swap();
        }
      }, this)
    };

    this.core.$element.on(this.handlers);
  };

  /**
   * Default options.
   * @public
   */
  Animate.Defaults = {
    animateOut: false,
    animateIn: false
  };

  /**
   * Toggles the animation classes whenever an translations starts.
   * @protected
   * @returns {Boolean|undefined}
   */
  Animate.prototype.swap = function() {

    if (this.core.settings.items !== 1 || !this.core.support3d) {
      return;
    }

    this.core.speed(0);

    var left,
      clear = $.proxy(this.clear, this),
      previous = this.core.$stage.children().eq(this.previous),
      next = this.core.$stage.children().eq(this.next),
      incoming = this.core.settings.animateIn,
      outgoing = this.core.settings.animateOut;

    if (this.core.current() === this.previous) {
      return;
    }

    if (outgoing) {
      left = this.core.coordinates(this.previous) - this.core.coordinates(this.next);
      previous.css({
          'left': left + 'px'
        })
        .addClass('animated owl-animated-out')
        .addClass(outgoing)
        .one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', clear);
    }

    if (incoming) {
      next.addClass('animated owl-animated-in')
        .addClass(incoming)
        .one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', clear);
    }
  };

  Animate.prototype.clear = function(e) {
    $(e.target).css({
        'left': ''
      })
      .removeClass('animated owl-animated-out owl-animated-in')
      .removeClass(this.core.settings.animateIn)
      .removeClass(this.core.settings.animateOut);
    this.core.transitionEnd();
  }

  /**
   * Destroys the plugin.
   * @public
   */
  Animate.prototype.destroy = function() {
    var handler, property;

    for (handler in this.handlers) {
      this.core.$element.off(handler, this.handlers[handler]);
    }
    for (property in Object.getOwnPropertyNames(this)) {
      typeof this[property] != 'function' && (this[property] = null);
    }
  };

  $.fn.owlCarousel.Constructor.Plugins.Animate = Animate;

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

/**
 * Autoplay Plugin
 * @version 2.0.0
 * @author Bartosz Wojciechowski
 * @license The MIT License (MIT)
 */
;
(function($, window, document, undefined) {

  /**
   * Creates the autoplay plugin.
   * @class The Autoplay Plugin
   * @param {Owl} scope - The Owl Carousel
   */
  var Autoplay = function(scope) {
    this.core = scope;
    this.core.options = $.extend({}, Autoplay.Defaults, this.core.options);

    this.handlers = {
      'translated.owl.carousel refreshed.owl.carousel': $.proxy(function() {
        this.autoplay();
      }, this),
      'play.owl.autoplay': $.proxy(function(e, t, s) {
        this.play(t, s);
      }, this),
      'stop.owl.autoplay': $.proxy(function() {
        this.stop();
      }, this),
      'mouseover.owl.autoplay': $.proxy(function() {
        if (this.core.settings.autoplayHoverPause) {
          this.pause();
        }
      }, this),
      'mouseleave.owl.autoplay': $.proxy(function() {
        if (this.core.settings.autoplayHoverPause) {
          this.autoplay();
        }
      }, this)
    };

    this.core.$element.on(this.handlers);
  };

  /**
   * Default options.
   * @public
   */
  Autoplay.Defaults = {
    autoplay: false,
    autoplayTimeout: 5000,
    autoplayHoverPause: false,
    autoplaySpeed: false
  };

  /**
   * @protected
   * @todo Must be documented.
   */
  Autoplay.prototype.autoplay = function() {
    if (this.core.settings.autoplay && !this.core.state.videoPlay) {
      window.clearInterval(this.interval);

      this.interval = window.setInterval($.proxy(function() {
        this.play();
      }, this), this.core.settings.autoplayTimeout);
    } else {
      window.clearInterval(this.interval);
    }
  };

  /**
   * Starts the autoplay.
   * @public
   * @param {Number} [timeout] - ...
   * @param {Number} [speed] - ...
   * @returns {Boolean|undefined} - ...
   * @todo Must be documented.
   */
  Autoplay.prototype.play = function(timeout, speed) {
    // if tab is inactive - doesnt work in <IE10
    if (document.hidden === true) {
      return;
    }

    if (this.core.state.isTouch || this.core.state.isScrolling ||
      this.core.state.isSwiping || this.core.state.inMotion) {
      return;
    }

    if (this.core.settings.autoplay === false) {
      window.clearInterval(this.interval);
      return;
    }

    this.core.next(this.core.settings.autoplaySpeed);
  };

  /**
   * Stops the autoplay.
   * @public
   */
  Autoplay.prototype.stop = function() {
    window.clearInterval(this.interval);
  };

  /**
   * Pauses the autoplay.
   * @public
   */
  Autoplay.prototype.pause = function() {
    window.clearInterval(this.interval);
  };

  /**
   * Destroys the plugin.
   */
  Autoplay.prototype.destroy = function() {
    var handler, property;

    window.clearInterval(this.interval);

    for (handler in this.handlers) {
      this.core.$element.off(handler, this.handlers[handler]);
    }
    for (property in Object.getOwnPropertyNames(this)) {
      typeof this[property] != 'function' && (this[property] = null);
    }
  };

  $.fn.owlCarousel.Constructor.Plugins.autoplay = Autoplay;

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

/**
 * Navigation Plugin
 * @version 2.0.0
 * @author Artus Kolanowski
 * @license The MIT License (MIT)
 */
;
(function($, window, document, undefined) {
  'use strict';

  /**
   * Creates the navigation plugin.
   * @class The Navigation Plugin
   * @param {Owl} carousel - The Owl Carousel.
   */
  var Navigation = function(carousel) {
    /**
     * Reference to the core.
     * @protected
     * @type {Owl}
     */
    this._core = carousel;

    /**
     * Indicates whether the plugin is initialized or not.
     * @protected
     * @type {Boolean}
     */
    this._initialized = false;

    /**
     * The current paging indexes.
     * @protected
     * @type {Array}
     */
    this._pages = [];

    /**
     * All DOM elements of the user interface.
     * @protected
     * @type {Object}
     */
    this._controls = {};

    /**
     * Markup for an indicator.
     * @protected
     * @type {Array.<String>}
     */
    this._templates = [];

    /**
     * The carousel element.
     * @type {jQuery}
     */
    this.$element = this._core.$element;

    /**
     * Overridden methods of the carousel.
     * @protected
     * @type {Object}
     */
    this._overrides = {
      next: this._core.next,
      prev: this._core.prev,
      to: this._core.to
    };

    /**
     * All event handlers.
     * @protected
     * @type {Object}
     */
    this._handlers = {
      'prepared.owl.carousel': $.proxy(function(e) {
        if (this._core.settings.dotsData) {
          this._templates.push($(e.content).find('[data-dot]').andSelf('[data-dot]').attr('data-dot'));
        }
      }, this),
      'add.owl.carousel': $.proxy(function(e) {
        if (this._core.settings.dotsData) {
          this._templates.splice(e.position, 0, $(e.content).find('[data-dot]').andSelf('[data-dot]').attr('data-dot'));
        }
      }, this),
      'remove.owl.carousel prepared.owl.carousel': $.proxy(function(e) {
        if (this._core.settings.dotsData) {
          this._templates.splice(e.position, 1);
        }
      }, this),
      'change.owl.carousel': $.proxy(function(e) {
        if (e.property.name == 'position') {
          if (!this._core.state.revert && !this._core.settings.loop && this._core.settings.navRewind) {
            var current = this._core.current(),
              maximum = this._core.maximum(),
              minimum = this._core.minimum();
            e.data = e.property.value > maximum ?
              current >= maximum ? minimum : maximum :
              e.property.value < minimum ? maximum : e.property.value;
          }
        }
      }, this),
      'changed.owl.carousel': $.proxy(function(e) {
        if (e.property.name == 'position') {
          this.draw();
        }
      }, this),
      'refreshed.owl.carousel': $.proxy(function() {
        if (!this._initialized) {
          this.initialize();
          this._initialized = true;
        }
        this._core.trigger('refresh', null, 'navigation');
        this.update();
        this.draw();
        this._core.trigger('refreshed', null, 'navigation');
      }, this)
    };

    // set default options
    this._core.options = $.extend({}, Navigation.Defaults, this._core.options);

    // register event handlers
    this.$element.on(this._handlers);
  }

  /**
   * Default options.
   * @public
   * @todo Rename `slideBy` to `navBy`
   */
  Navigation.Defaults = {
    nav: false,
    navRewind: true,
    navText: ['prev', 'next'],
    navSpeed: false,
    navElement: 'div',
    navContainer: false,
    navContainerClass: 'owl-nav',
    navClass: ['owl-prev', 'owl-next'],
    slideBy: 1,
    dotClass: 'owl-dot',
    dotsClass: 'owl-dots',
    dots: true,
    dotsEach: false,
    dotData: false,
    dotsSpeed: false,
    dotsContainer: false,
    controlsClass: 'owl-controls'
  }

  /**
   * Initializes the layout of the plugin and extends the carousel.
   * @protected
   */
  Navigation.prototype.initialize = function() {
    var $container, override,
      options = this._core.settings;

    // create the indicator template
    if (!options.dotsData) {
      this._templates = [$('<div>')
        .addClass(options.dotClass)
        .append($('<span>'))
        .prop('outerHTML')
      ];
    }

    // create controls container if needed
    if (!options.navContainer || !options.dotsContainer) {
      this._controls.$container = $('<div>')
        .addClass(options.controlsClass)
        .appendTo(this.$element);
    }

    // create DOM structure for absolute navigation
    this._controls.$indicators = options.dotsContainer ? $(options.dotsContainer) :
      $('<div>').hide().addClass(options.dotsClass).appendTo(this._controls.$container);

    this._controls.$indicators.on('click', 'div', $.proxy(function(e) {
      var index = $(e.target).parent().is(this._controls.$indicators) ?
        $(e.target).index() : $(e.target).parent().index();

      e.preventDefault();

      this.to(index, options.dotsSpeed);
    }, this));

    // create DOM structure for relative navigation
    $container = options.navContainer ? $(options.navContainer) :
      $('<div>').addClass(options.navContainerClass).prependTo(this._controls.$container);

    this._controls.$next = $('<' + options.navElement + '>');
    this._controls.$previous = this._controls.$next.clone();

    this._controls.$previous
      .addClass(options.navClass[0])
      .html(options.navText[0])
      .hide()
      .prependTo($container)
      .on('click', $.proxy(function(e) {
        this.prev(options.navSpeed);
      }, this));
    this._controls.$next
      .addClass(options.navClass[1])
      .html(options.navText[1])
      .hide()
      .appendTo($container)
      .on('click', $.proxy(function(e) {
        this.next(options.navSpeed);
      }, this));

    // override public methods of the carousel
    for (override in this._overrides) {
      this._core[override] = $.proxy(this[override], this);
    }
  }

  /**
   * Destroys the plugin.
   * @protected
   */
  Navigation.prototype.destroy = function() {
    var handler, control, property, override;

    for (handler in this._handlers) {
      this.$element.off(handler, this._handlers[handler]);
    }
    for (control in this._controls) {
      this._controls[control].remove();
    }
    for (override in this.overides) {
      this._core[override] = this._overrides[override];
    }
    for (property in Object.getOwnPropertyNames(this)) {
      typeof this[property] != 'function' && (this[property] = null);
    }
  }

  /**
   * Updates the internal state.
   * @protected
   */
  Navigation.prototype.update = function() {
    var i, j, k,
      options = this._core.settings,
      lower = this._core.clones().length / 2,
      upper = lower + this._core.items().length,
      size = options.center || options.autoWidth || options.dotData ?
      1 : options.dotsEach || options.items;

    if (options.slideBy !== 'page') {
      options.slideBy = Math.min(options.slideBy, options.items);
    }

    if (options.dots || options.slideBy == 'page') {
      this._pages = [];

      for (i = lower, j = 0, k = 0; i < upper; i++) {
        if (j >= size || j === 0) {
          this._pages.push({
            start: i - lower,
            end: i - lower + size - 1
          });
          j = 0, ++k;
        }
        j += this._core.mergers(this._core.relative(i));
      }
    }
  }

  /**
   * Draws the user interface.
   * @todo The option `dotData` wont work.
   * @protected
   */
  Navigation.prototype.draw = function() {
    var difference, i, html = '',
      options = this._core.settings,
      $items = this._core.$stage.children(),
      index = this._core.relative(this._core.current());

    if (options.nav && !options.loop && !options.navRewind) {
      this._controls.$previous.toggleClass('disabled', index <= 0);
      this._controls.$next.toggleClass('disabled', index >= this._core.maximum());
    }

    this._controls.$previous.toggle(options.nav);
    this._controls.$next.toggle(options.nav);

    if (options.dots) {
      difference = this._pages.length - this._controls.$indicators.children().length;
      if (options.dotData && difference !== 0) {

        for (i = 0; i < this._controls.$indicators.children().length; i++) {
          html += this._templates[this._core.relative(i)];
        }
        this._controls.$indicators.html(html);
      } else if (difference > 0) {
        html = new Array(difference + 1).join(this._templates[0]);
        this._controls.$indicators.append(html);
      } else if (difference < 0) {
        this._controls.$indicators.children().slice(difference).remove();
      }

      this._controls.$indicators.find('.active').removeClass('active');
      this._controls.$indicators.children().eq($.inArray(this.current(), this._pages)).addClass('active');
    }

    this._controls.$indicators.toggle(options.dots);
  }

  /**
   * Extends event data.
   * @protected
   * @param {Event} event - The event object which gets thrown.
   */
  Navigation.prototype.onTrigger = function(event) {
    var settings = this._core.settings;

    event.page = {
      index: $.inArray(this.current(), this._pages),
      count: this._pages.length,
      size: settings && (settings.center || settings.autoWidth || settings.dotData ?
        1 : settings.dotsEach || settings.items)
    };
  }

  /**
   * Gets the current page position of the carousel.
   * @protected
   * @returns {Number}
   */
  Navigation.prototype.current = function() {
    var index = this._core.relative(this._core.current());
    return $.grep(this._pages, function(o) {
      return o.start <= index && o.end >= index;
    }).pop();
  }

  /**
   * Gets the current succesor/predecessor position.
   * @protected
   * @returns {Number}
   */
  Navigation.prototype.getPosition = function(successor) {
    var position, length,
      options = this._core.settings;

    if (options.slideBy == 'page') {
      position = $.inArray(this.current(), this._pages);
      length = this._pages.length;
      successor ? ++position : --position;
      position = this._pages[((position % length) + length) % length].start;
    } else {
      position = this._core.relative(this._core.current());
      length = this._core.items().length;
      successor ? position += options.slideBy : position -= options.slideBy;
    }
    return position;
  }

  /**
   * Slides to the next item or page.
   * @public
   * @param {Number} [speed=false] - The time in milliseconds for the transition.
   */
  Navigation.prototype.next = function(speed) {
    $.proxy(this._overrides.to, this._core)(this.getPosition(true), speed);
  }

  /**
   * Slides to the previous item or page.
   * @public
   * @param {Number} [speed=false] - The time in milliseconds for the transition.
   */
  Navigation.prototype.prev = function(speed) {
    $.proxy(this._overrides.to, this._core)(this.getPosition(false), speed);
  }

  /**
   * Slides to the specified item or page.
   * @public
   * @param {Number} position - The position of the item or page.
   * @param {Number} [speed] - The time in milliseconds for the transition.
   * @param {Boolean} [standard=false] - Whether to use the standard behaviour or not.
   */
  Navigation.prototype.to = function(position, speed, standard) {
    var length;

    if (!standard) {
      length = this._pages.length;
      $.proxy(this._overrides.to, this._core)(this._pages[((position % length) + length) % length].start, speed);
    } else {
      $.proxy(this._overrides.to, this._core)(position, speed);
    }
  }

  $.fn.owlCarousel.Constructor.Plugins.Navigation = Navigation;

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

/**
 * Hash Plugin
 * @version 2.0.0
 * @author Artus Kolanowski
 * @license The MIT License (MIT)
 */
;
(function($, window, document, undefined) {
  'use strict';

  /**
   * Creates the hash plugin.
   * @class The Hash Plugin
   * @param {Owl} carousel - The Owl Carousel
   */
  var Hash = function(carousel) {
    /**
     * Reference to the core.
     * @protected
     * @type {Owl}
     */
    this._core = carousel;

    /**
     * Hash table for the hashes.
     * @protected
     * @type {Object}
     */
    this._hashes = {};

    /**
     * The carousel element.
     * @type {jQuery}
     */
    this.$element = this._core.$element;

    /**
     * All event handlers.
     * @protected
     * @type {Object}
     */
    this._handlers = {
      'initialized.owl.carousel': $.proxy(function() {
        if (this._core.settings.startPosition == 'URLHash') {
          $(window).trigger('hashchange.owl.navigation');
        }
      }, this),
      'prepared.owl.carousel': $.proxy(function(e) {
        var hash = $(e.content).find('[data-hash]').andSelf('[data-hash]').attr('data-hash');
        this._hashes[hash] = e.content;
      }, this)
    };

    // set default options
    this._core.options = $.extend({}, Hash.Defaults, this._core.options);

    // register the event handlers
    this.$element.on(this._handlers);

    // register event listener for hash navigation
    $(window).on('hashchange.owl.navigation', $.proxy(function() {
      var hash = window.location.hash.substring(1),
        items = this._core.$stage.children(),
        position = this._hashes[hash] && items.index(this._hashes[hash]) || 0;

      if (!hash) {
        return false;
      }

      this._core.to(position, false, true);
    }, this));
  }

  /**
   * Default options.
   * @public
   */
  Hash.Defaults = {
    URLhashListener: false
  }

  /**
   * Destroys the plugin.
   * @public
   */
  Hash.prototype.destroy = function() {
    var handler, property;

    $(window).off('hashchange.owl.navigation');

    for (handler in this._handlers) {
      this._core.$element.off(handler, this._handlers[handler]);
    }
    for (property in Object.getOwnPropertyNames(this)) {
      typeof this[property] != 'function' && (this[property] = null);
    }
  }

  $.fn.owlCarousel.Constructor.Plugins.Hash = Hash;

})(window.Zepto || window.jQuery, window, document);
;/*})'"*/;/*})'"*/
(function ($) {

  Drupal.behaviors.owlCarousel = {
    attach: function (context, settings) {



      var owl = $("#widget_pager_bottom_property_gallery-block_m", context).owlCarousel({
        items: 7,
        loop: false,
        //nav: true,
        navText: ['<span class="fa fa-chevron-left"></span>', '<span class="fa fa-chevron-right"></span>' ],
        pagination: false,
        margin:10,
        //autoWidth:true,
        responsive : {
          // breakpoint from 0 up
          0 : {
              items: 3,
              center: true
          },
          // breakpoint from 480 up
          480 : {
              items: 3
          },
          // breakpoint from 768 up
          768 : {
              items: 7
          },
          970 : {
              items: 7
          }
        }
      });
    }
  }

}(jQuery));
;/*})'"*/;/*})'"*/
(function($, Drupal, undefined) {



  Drupal.behaviors.MainPropertyOwl = {
    attach: function(context, settings) {



      var mainOwlBig = $('.property-main-owl:first .view-content:first'),
        mainOwlThumb = $('.property-gallery--small .view-content'),
        flag = false,
        duration = 300,
        relaLazyDict = {};

      var owlFullBg = $(mainOwlBig, context)
        .on('initialized.owl.carousel changed.owl.carousel', function(e) {
          if (!e.namespace) return
          var carousel = e.relatedTarget
          $('#owl-page').text(carousel.relative(carousel.current()) + 1 + ' of ' + carousel.items().length)
        })
        .owlCarousel({
          items: 1,
          margin: 0,
          nav: true,
          navText: [
            '<div class="pe-7s-angle-left"></div>',
            '<div class="pe-7s-angle-right"></div>'
          ],
          responsive: {
            0: {
              smartSpeed: 250
            },
            768: {
              smartSpeed: 750
            }
          }

        })
        .on('changed.owl.carousel', function(e) {
          relaLazyUnload(e);
          relaLazyLoad(e);
          if (!flag) {
            flag = true;
            mainOwlThumb.trigger('to.owl.carousel', [e.item.index, duration, true]);
            flag = false;
          }
        })




      var owlThumbs = $(mainOwlThumb, context).owlCarousel({
          items: 7,
          margin: 10,
          smartSpeed: 750,
        })
        .on('click', '.owl-item', function() {
          mainOwlBig.trigger('to.owl.carousel', [$(this).index(), duration, true]);

        })
        .on('changed.owl.carousel', function(e) {
          if (!flag) {
            flag = true;
            mainOwlBig.trigger('to.owl.carousel', [e.item.index, duration, true]);
            flag = false;
          }
        });

      $('div[data="block-views-property-gallery-block-main-owl"]', context).click(function() {
        var stageWidth = $('#block-views-property-gallery-block-main-owl').width();

        var carouselMain = $(mainOwlBig).data('owlCarousel');
        carouselMain._width = stageWidth;
        carouselMain.invalidate('width');
        carouselMain.refresh();

        var carouselThumbs = $(mainOwlThumb).data('owlCarousel');
        carouselThumbs._width = stageWidth;
        carouselThumbs.invalidate('width');
        carouselThumbs.refresh();

        relaLazyInit(carouselMain);
      });

      $('a[data="block-views-property-gallery-block-main-owl"]', context).click(function() {
        var stageWidth = $('#block-views-property-gallery-block-main-owl').width();

        var carouselMain = $(mainOwlBig).data('owlCarousel');
        carouselMain._width = stageWidth;
        carouselMain.invalidate('width');
        carouselMain.refresh();

        var carouselThumbs = $(mainOwlThumb).data('owlCarousel');
        carouselThumbs._width = stageWidth;
        carouselThumbs.invalidate('width');
        carouselThumbs.refresh();

        relaLazyInit(carouselMain);
      });

      /**
       * Loads the first two images in the carousel on init
       */
      function relaLazyInit(e) {
        for (i = 0; i < 2; i++) {
          var owlItem = e._items[i];
          var owlImage = $(owlItem).find('img.owl-lazy');
          $(owlImage).attr('src', $(owlImage).attr('data-src'));
          $(owlImage).css('opacity', '1');
          relaLazyArrayPush(owlImage, i);
        }
      };

      /**
       * Unloads an image to save on physical memory
       */
      function relaLazyUnload(e) {
        if (e.item.index >= 2) {
          var nums = [-2, 2];
          for (i in nums) {
            var preIndex = e.item.index + nums[i];
            var owlItem = e.relatedTarget._items[preIndex];
            var owlImage = $(owlItem).find('img.owl-lazy');
            if ($(owlImage).attr('src')) {
              $(owlImage).removeAttr('src');
              relaLazyIncinerator(preIndex, e.item.index);
            }
          }
        }
      };

      /**
       * loads the image when it is one away
       */
      function relaLazyLoad(e) {
        if (e.item.index >= 1) {
          for (i = -1; i < 2; i++) {
            var owlItem = e.relatedTarget._items[e.item.index + i];
            var owlImage = $(owlItem).find('img.owl-lazy');
            if (!$(owlImage).attr('src')) {
              $(owlImage).attr('src', $(owlImage).attr('data-src'));
              $(owlImage).css('opacity', '1');
              relaLazyArrayPush(owlImage, e.item.index + i);
            }
          }
        }
      };

      /**
       * Moves the image element into an dictionary with its index being the key for
       * incineration later
       */
      function relaLazyArrayPush(el, indexKey) {
        relaLazyDict[indexKey] = el;
      };

      /**
       * incinerates any loaded photos out of range of carousel
       */
      function relaLazyIncinerator(indexKey, currentIndex) {
        delete relaLazyDict[indexKey];
        //the +1 is because it kept returning one less than there actually was
        var dictLength = Object.keys(relaLazyDict).length + 1;
        if (dictLength > 3) {
          for (i in relaLazyDict) {
            if (i > currentIndex + 1 || i < currentIndex - 1) {
              delete relaLazyDict[i];
            }
          }
        }
      };


    }
  }



  Drupal.behaviors.OwlinPage = {
    attach: function(context, settings) {
      if ($(".view-display-id-embed_owl_main").length > 0) {
        var owl = $(".view-display-id-embed_owl_main .view-content", context).owlCarousel({
          loop: false,
          items: 3,
          nav: true,
          margin: 20,
          navText: ['<span class="icon icon-arrow-67"></span>', '<span class="icon icon-arrow-68"></span>'],
          pagination: false,
          video: true,
          responsive: {
            // breakpoint from 0 up
            0: {
              items: 1,
              margin: 20,

              center: true,

            },
            // breakpoint from 480 up
            480: {
              items: 2,
            },

            // breakpoint from 768 up
            768: {
              items: 3,
            }
          }
        });
      }
    }
  }




  Drupal.behaviors.OwlThemesSlider = {
    attach: function(context, settings) {
      var owlFullBg = $(".owl-themes-slider .view-content", context).owlCarousel({
        loop: true,
        items: 1,
        margin: 0,
        pagination: false,
        autoplay: true,
        autoplayTimeout: 5000,
        smartSpeed: 750,
        autoplayHoverPause: true,
      });
    }
  }


  Drupal.behaviors.RelazTestimonial = {
    attach: function(context, settings) {
      if ($("#aa-testimonials .view-content").length > 0) {
        var showNav = false;
        var target = '#aa-testimonials .view-content';
        if ($(target + ' .views-row').length > 1) {
          showNav = true;
        }
        var owlOpenHouse = $(target, context)
          .owlCarousel({
            items: 1,
            autoplay: true,
            smartSpeed: 1100,
            nav: showNav,
            loop: showNav,
            navText: ['<span class="icon icon-arrow-67"></span>', '<span class="icon icon-arrow-68"></span>'],
            responsive: {
              // breakpoint from 0 up
              0: {
                nav: false,
              },
              // breakpoint from 480 up
              768: {
                nav: true,


              }
            }
          });
      }
    }
  }

  Drupal.behaviors.RelazOpenHouz = {
    attach: function(context, settings) {
      if ($(".open-house-slider .view-content").length > 0) {
        var showNav = false;
        var target = '.open-house-slider .view-content';
        if ($(target + ' .views-row').length > 1) {
          showNav = true;
        }
        var owlOpenHouse = $(target, context)
          .owlCarousel({
            items: 1,
            autoplay: true,
            smartSpeed: 750,
            nav: showNav,
            loop: showNav,
            navText: ['<span class="icon icon-arrow-67"></span>', '<span class="icon icon-arrow-68"></span>'],
          });
      }
    }
  }

  Drupal.behaviors.RelazVOpenHouz = {
    attach: function(context, settings) {
      if ($(".voh-slider .view-content").length > 0) {
        var showNav = false;
        var target = '.voh-slider .view-content';
        if ($(target + ' .views-row').length > 1) {
          showNav = true;
        }
        var owlOpenHouse = $(target, context)
          .owlCarousel({
            items: 1,
            autoplay: true,
            smartSpeed: 750,
            nav: showNav,
            loop: showNav,
            navText: ['<span class="icon icon-arrow-67"></span>', '<span class="icon icon-arrow-68"></span>'],
          });
      }
    }
  }
  Drupal.behaviors.RelazSwiperFullBG = {
    attach: function(context, settings) {

      var owlFullBg = $(".owl-fullbg .view-content", context).owlCarousel({
        loop: false,
        items: 1,
        // nav:true,
        margin: 0,
        //navText: ['<span class="icon icon-arrow-67"></span>', '<span class="icon icon-arrow-68"></span>' ],
        pagination: false,

      });

      var owlThumbs = $(".owl-thumbs .view-content", context).owlCarousel({
        loop: false,
        //items: 8,
        nav: true,
        margin: 10,
        stagePadding: 20,
        navText: ['<span class="icon icon-arrow-67"></span>', '<span class="icon icon-arrow-68"></span>'],
        pagination: false,
        //autoWidth:true,
        responsiveClass: true,
        responsive: {
          // breakpoint from 0 up
          0: {
            items: 1,
            //stagePadding: 0,
            //autoWidth:true,
            loop: true,
            nav: false,
            center: true,
            touchDrag: true,
            mouseDrag: true
          },
          // breakpoint from 480 up
          480: {
            items: 1,

            nav: true,
            //center:true,
            //stagePadding: 0,
            touchDrag: true,
            mouseDrag: true

          },
          // breakpoint from 768 up
          768: {
            items: 6,
            //stagePadding:0,
            //touchDrag: false,
            // mouseDrag: false
          },
          // breakpoint from 768 up
          1200: {
            items: 8,
            // stagePadding:0,
            //touchDrag: false,
            //mouseDrag: false
          }
        }


      });



      $(".owl-thumbs").on('click', '.owl-item', function() {

        owlFullBg.trigger('to.owl.carousel', [$(this).index(), 500]);
        owlThumbs.trigger('next.owl.carousel', [500]);


      });

      var playerID = '.view-display-id-owl_embed_fullbg .views-field-field-property-video-url .field-content';

      function vimeoRescale() {
        var w = $(window).width() + 0,
          h = $(window).height() + 0;

        if (w / h > 16 / 9) {
          $(playerID).width(w).height(w / 16 * 9);
          $(playerID).css({
            'left': '0px'
          });
        } else {
          $(playerID).width(h / 9 * 16).height(h);
          $(playerID).css({
            'left': -($(playerID).outerWidth() - w) / 2
          });
        }
      } // End viemo rescale
      $(window).on('load resize', function() {
        vimeoRescale();
      });
    }
  }


  Drupal.behaviors.EmbeddableSingleOwlCarousel = {
    attach: function(context, settings) {
      if ($(".property-plain-owl").length > 0) {
        $('.property-plain-owl .view-content').owlCarousel({
          items: 1,
          nav: true,
          navText: ['<div class="pe-7s-angle-left"></div>', '<div class="pe-7s-angle-right"></div>'],
          lazyLoad: true,
          autoplay: true,
          autoplayHoverPause: true,
        });
      }
    }
  }

  Drupal.behaviors.EmbeddableCarousel = {
    attach: function(context, settings) {
      if ($(".embed-owl-carousel").length > 0) {
        $('.embed-owl-carousel .view-content').owlCarousel({
          items: 1,
          nav: true,
          navText: ['<div class="pe-7s-angle-left"></div>', '<div class="pe-7s-angle-right"></div>'],
        });
      }
    }
  }

  Drupal.behaviors.logoCarousel = {
    attach: function(context, settings) {
      if ($(".view-display-id-pane_customer_logos").length > 0) {
        $('.view-display-id-pane_customer_logos .view-content ul').owlCarousel({
          items: 3,
          nav: false,
          autoplay: true,
          loop: true,

        });
      }
    }
  }

  Drupal.behaviors.floorplanGallery = {
    attach: function(context, settings) {
      if ($(".aview-display-id-embed_floorplan_gallery").length > 0) {
        $('.view-display-id-embed_floorplan_gallery .view-content').owlCarousel({
          items: 2,

          nav: false,
          autoplay: false,
          autoWidth:true,
          loop: false,
          center: true,
          responsive: {
          // breakpoint from 0 up
          0: {
            items: 1,
            //stagePadding: 0,
            //autoWidth:true,
            loop: true,
            nav: false,
            center: true,
            touchDrag: true,
            mouseDrag: true
          },

          // breakpoint from 768 up
          768: {
            items: 2
          }
        }
        });
      }
    }
  }

  Drupal.behaviors.PropertyPSPWthumbs = {
    attach: function(context, settings) {
      if ($('#pspw-gallery-thumbs').length > 0) {
        $('#pspw-gallery-thumbs .inner').owlCarousel({
          items:8,
          nav: true,
          navText: ['<div class="icon-arrow-left"></div>', '<div class="icon-arrow-right"></div>'],
          autoplay: false,
          loop: false,
          margin:10,

          responsive: {

            0: {
              items:4
            },

            768: {
              items:6
            },
            1199:{
              items:8
            },
          },
        });
      }
    }
  }

})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
(function ($) {

  Drupal.leaflet._create_layer_orig = Drupal.leaflet.create_layer;

  Drupal.leaflet.create_layer = function(layer, key) {
    if (layer.type === 'quad') {
      var mapLayer = L.tileLayerQuad(layer.urlTemplate, layer.options);
      mapLayer._leaflet_id = key;
      mapLayer._type = 'quad';
      return mapLayer;
    }
    if (layer.type === 'google' && layer.options.detectRetina && L.Browser.retina) {
      layer.urlTemplate += '&style=high_dpi&w=512';
      layer.options.tileSize = 512;
      var mapLayer = L.tileLayer(layer.urlTemplate, layer.options);
      mapLayer._leaflet_id = key;
      mapLayer._type = 'google';
      return mapLayer;
    }
    // Default to the original code;
    return Drupal.leaflet._create_layer_orig(layer, key);
  };

})(jQuery);

L.TileLayerQuad = L.TileLayer.extend({

  getTileUrl: function(tilePoint) {
    this._adjustTilePoint(tilePoint);

    return L.Util.template(this._url, L.extend({
      s: this._getSubdomain(tilePoint),
      q: this._xyzToQuad(tilePoint.x, tilePoint.y, this._getZoomForUrl())
    }, this.options));
  },

  /** Convert xyz tile coordinates to a single quadtree key string.
   *
   * The length of the quadkey equals the zoom level. Note: zoom > 0.
   *
   * Adapted from http://msdn.microsoft.com/en-us/library/bb259689.aspx
   */
  _xyzToQuad: function(x, y, zoom) {
    var quadKey = '', digit, mask;
    for (var z = zoom; z > 0; z--) {
      digit = 0;
      mask = 1 << (z - 1);
      if ((x & mask) !== 0) {
        digit = 1;
      }
      if ((y & mask) !== 0) {
        digit += 2;
      }
      // At this point digit equals 0, 1, 2 or 3. Append digit to quad key and
      // advance to the next zoom level to calculate the next digit.
      quadKey += digit;
    }
    return quadKey;
  }
});

L.tileLayerQuad = function(urlTemplate, options) {
  return new L.TileLayerQuad(urlTemplate, options);
};
;/*})'"*/;/*})'"*/
/*!
 * Bootstrap v3.3.4 (http://getbootstrap.com)
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.4",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.4",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active"));a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.4",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.4",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=c(d),f={relatedTarget:this};e.hasClass("open")&&(e.trigger(b=a.Event("hide.bs.dropdown",f)),b.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f)))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.4",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27|32)/.test(b.which)&&!/input|textarea/i.test(b.target.tagName)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g&&27!=b.which||g&&27==b.which)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(b.target);38==b.which&&j>0&&j--,40==b.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="menu"]',g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.4",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in").attr("aria-hidden",!1),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a('<div class="modal-backdrop '+e+'" />').appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.3.4",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport),this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c&&c.$tip&&c.$tip.is(":visible")?void(c.hoverState="in"):(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.options.container?a(this.options.container):this.$element.parent(),p=this.getPosition(o);h="bottom"==h&&k.bottom+m>p.bottom?"top":"top"==h&&k.top-m<p.top?"bottom":"right"==h&&k.right+l>p.width?"left":"left"==h&&k.left-l<p.left?"right":h,f.removeClass(n).addClass(h)}var q=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(q,h);var r=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",r).emulateTransitionEnd(c.TRANSITION_DURATION):r()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type)})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.4",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.4",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.4",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});
if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.4",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=a(document.body).height();"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
;/*})'"*/;/*})'"*/
/*!
 * hoverIntent v1.8.0 // 2014.06.29 // jQuery v1.9.1+
 * http://cherne.net/brian/resources/jquery.hoverIntent.html
 *
 * You may use hoverIntent under the terms of the MIT license. Basically that
 * means you are free to use hoverIntent as long as this header is left intact.
 * Copyright 2007, 2014 Brian Cherne
 */
(function($){$.fn.hoverIntent=function(handlerIn,handlerOut,selector){var cfg={interval:100,sensitivity:6,timeout:0};if(typeof handlerIn==="object"){cfg=$.extend(cfg,handlerIn)}else{if($.isFunction(handlerOut)){cfg=$.extend(cfg,{over:handlerIn,out:handlerOut,selector:selector})}else{cfg=$.extend(cfg,{over:handlerIn,out:handlerIn,selector:handlerOut})}}var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if(Math.sqrt((pX-cX)*(pX-cX)+(pY-cY)*(pY-cY))<cfg.sensitivity){$(ob).off("mousemove.hoverIntent",track);ob.hoverIntent_s=true;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=false;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=$.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type==="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).on("mousemove.hoverIntent",track);if(!ob.hoverIntent_s){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).off("mousemove.hoverIntent",track);if(ob.hoverIntent_s){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.on({"mouseenter.hoverIntent":handleHover,"mouseleave.hoverIntent":handleHover},cfg.selector)}})(jQuery);
;/*})'"*/;/*})'"*/
/*! modernizr 3.6.0 (Custom Build) | MIT *
 * https://modernizr.com/download/?-webp-setclasses !*/
!function(e,n,A){function o(e,n){return typeof e===n}function t(){var e,n,A,t,a,i,l;for(var f in r)if(r.hasOwnProperty(f)){if(e=[],n=r[f],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(A=0;A<n.options.aliases.length;A++)e.push(n.options.aliases[A].toLowerCase());for(t=o(n.fn,"function")?n.fn():n.fn,a=0;a<e.length;a++)i=e[a],l=i.split("."),1===l.length?Modernizr[l[0]]=t:(!Modernizr[l[0]]||Modernizr[l[0]]instanceof Boolean||(Modernizr[l[0]]=new Boolean(Modernizr[l[0]])),Modernizr[l[0]][l[1]]=t),s.push((t?"":"no-")+l.join("-"))}}function a(e){var n=u.className,A=Modernizr._config.classPrefix||"";if(c&&(n=n.baseVal),Modernizr._config.enableJSClass){var o=new RegExp("(^|\\s)"+A+"no-js(\\s|$)");n=n.replace(o,"$1"+A+"js$2")}Modernizr._config.enableClasses&&(n+=" "+A+e.join(" "+A),c?u.className.baseVal=n:u.className=n)}function i(e,n){if("object"==typeof e)for(var A in e)f(e,A)&&i(A,e[A]);else{e=e.toLowerCase();var o=e.split("."),t=Modernizr[o[0]];if(2==o.length&&(t=t[o[1]]),"undefined"!=typeof t)return Modernizr;n="function"==typeof n?n():n,1==o.length?Modernizr[o[0]]=n:(!Modernizr[o[0]]||Modernizr[o[0]]instanceof Boolean||(Modernizr[o[0]]=new Boolean(Modernizr[o[0]])),Modernizr[o[0]][o[1]]=n),a([(n&&0!=n?"":"no-")+o.join("-")]),Modernizr._trigger(e,n)}return Modernizr}var s=[],r=[],l={_version:"3.6.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var A=this;setTimeout(function(){n(A[e])},0)},addTest:function(e,n,A){r.push({name:e,fn:n,options:A})},addAsyncTest:function(e){r.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=l,Modernizr=new Modernizr;var f,u=n.documentElement,c="svg"===u.nodeName.toLowerCase();!function(){var e={}.hasOwnProperty;f=o(e,"undefined")||o(e.call,"undefined")?function(e,n){return n in e&&o(e.constructor.prototype[n],"undefined")}:function(n,A){return e.call(n,A)}}(),l._l={},l.on=function(e,n){this._l[e]||(this._l[e]=[]),this._l[e].push(n),Modernizr.hasOwnProperty(e)&&setTimeout(function(){Modernizr._trigger(e,Modernizr[e])},0)},l._trigger=function(e,n){if(this._l[e]){var A=this._l[e];setTimeout(function(){var e,o;for(e=0;e<A.length;e++)(o=A[e])(n)},0),delete this._l[e]}},Modernizr._q.push(function(){l.addTest=i}),Modernizr.addAsyncTest(function(){function e(e,n,A){function o(n){var o=n&&"load"===n.type?1==t.width:!1,a="webp"===e;i(e,a&&o?new Boolean(o):o),A&&A(n)}var t=new Image;t.onerror=o,t.onload=o,t.src=n}var n=[{uri:"data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA=",name:"webp"},{uri:"data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAABBxAR/Q9ERP8DAABWUDggGAAAADABAJ0BKgEAAQADADQlpAADcAD++/1QAA==",name:"webp.alpha"},{uri:"data:image/webp;base64,UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA",name:"webp.animation"},{uri:"data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=",name:"webp.lossless"}],A=n.shift();e(A.name,A.uri,function(A){if(A&&"load"===A.type)for(var o=0;o<n.length;o++)e(n[o].name,n[o].uri)})}),t(),a(s),delete l.addTest,delete l.addAsyncTest;for(var p=0;p<Modernizr._q.length;p++)Modernizr._q[p]();e.Modernizr=Modernizr}(window,document);

jQuery(window).bind("load resize scroll", function(e) {
  var $ = jQuery;
  var y = jQuery(window).scrollTop();


  jQuery(".parallax-move-up").filter(function() {

    return jQuery(this).offset().top < (y + jQuery(window).height()) &&
      jQuery(this).offset().top + jQuery(this).height() > y;
  }).css('background-position', '50% ' + parseInt(-y / 20) + 'px');
  //console.log($(window).height());
  var windowHeight = $(window).height();
  var footerHeight = $('footer').height()
  $('#property-list-scroll').height(windowHeight - footerHeight);
});

  jQuery.fn.isInViewport = function(y) {
    var y = y || 1;
    var elementTop = jQuery(this).offset().top;
    var elementBottom = elementTop + jQuery(this).outerHeight();
    var elementHeight = jQuery(this).height();
    var viewportTop = jQuery(window).scrollTop();
    var viewportBottom = viewportTop + jQuery(window).height();
    var deltaTop = Math.min(1, (elementBottom - viewportTop) / elementHeight);
    var deltaBottom = Math.min(1, (viewportBottom - elementTop) / elementHeight);
    return deltaTop * deltaBottom >= y;
  };
// https://github.com/daneden/animate.css
jQuery.fn.extend({
  animateCss: function(animationName, callback) {
    var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
    jQuery(this).removeClass('animated-processed').addClass('animated ' + animationName).one(animationEnd, function() {
      jQuery(this).removeClass('animated ' + animationName);
      if (typeof callback === 'function') callback();

    });
  }
});
// Open social share popup.
jQuery.fn.extend({
  openSocialShare: function(url, name, options) {
    var newWin = window.open(url, name, options);
    if (!newWin || newWin.closed || typeof newWin.closed == 'undefined') {
      jQuery('#social-block-alert').slideDown().delay(2000).slideUp();
    }
  }
});

jQuery.fn.extend({
  makeCloseLink: function(nid) {
    var selector = '.lead-summary-' + nid + ' a';
    var newLink = '<a href="#" class="summary-link opened">Close</a>';
    jQuery(selector).replaceWith(newLink);
  }
});

jQuery.fn.extend({
  openModal: function() {
    if (jQuery('.overlay-open').length == 0) {
      jQuery('#ajax-content-overlay').fadeIn();
      jQuery('.overlay-content').html('<div class="loader"></div>');
      jQuery('body').addClass('overlay-open');
    }
  }
});

jQuery.fn.extend({
  closeModal: function() {
    if (jQuery('.overlay-open').length > 0) {
      jQuery('#ajax-content-overlay').fadeOut();
      jQuery('.right-overlay-close').click();
      jQuery('.overlay-content').html('<div class="loader"></div>');
      jQuery('body').removeClass('overlay-open');
    }
  }
});

jQuery.fn.extend({
  openRightOverlay: function() {
    if (jQuery('.right-overlay-open').length == 0) {

      jQuery('#right-edit-overlay').addClass('right-overlay-open');
      jQuery('#right-edit-overlay').after('<div class="right-underlay"></div>');
      jQuery('#right-edit-overlay .overlay-inner').html('<i class="loader loader-grey"></i>');
      jQuery('#right-edit-overlay').animate({
        right: 0
      }, 500, "easeOutCubic");
      jQuery('body').addClass('right-overlay-open');
      var scroll = false;
      if (jQuery('#right-edit-overlay').hasClass('scroll-top')) {
        scroll = true;
      }
      if (scroll) {
        jQuery("html, body").animate({
          scrollTop: 0
        }, "normal");
      }

    }
  }
});

jQuery.fn.extend({
  closeRightOverlay: function() {
    if (jQuery('.right-overlay-open').length > 0) {
      jQuery('#right-edit-overlay').removeClass('right-overlay-open');
      jQuery('.right-underlay').remove();
      jQuery('#right-edit-overlay').animate({
        right: '-100%'
      }, 500, "easeOutCubic", function() {
        jQuery('#right-edit-overlay .overlay-title').text('Loading...');
        jQuery('#right-edit-overlay .overlay-inner').html('<i class="loader loader-grey"></i>');
      });
      jQuery('body').removeClass('right-overlay-open');
    }
  }
});

(function($, Drupal, undefined) {

  // custom global functions that can be called in other js files.
  // Call them like this Drupal.relaGlobalFunctions.isMobile()
  Drupal.relaGlobalFunctions = {
    isMobile: function () {

      return function() {
        // Check for mobile and iPad inside the function
        // //https://stackoverflow.com/a/3540295
        var mobile = /Android|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent || navigator.vendor || window.opera);
        //https://stackoverflow.com/a/58017456 checks for ipad
        var isIpad = navigator.userAgent.match(/Mac/) && navigator.maxTouchPoints && navigator.maxTouchPoints > 2;

        return mobile || isIpad;
      };

      }(),
      // other functions defined here
  };

  window.getUrlParameter = function(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
      sURLVariables = sPageURL.split('&'),
      sParameterName,
      i;

    for (i = 0; i < sURLVariables.length; i++) {
      sParameterName = sURLVariables[i].split('=');

      if (sParameterName[0] === sParam) {
        return sParameterName[1] === undefined ? true : sParameterName[1];
      }
    }
  };

  window.relaAjaxPost = function(url, params) {
    // Only allow this for relajax/ urls.
    if (url.indexOf('/relajax/nojs/global/') === 0) {
      var id = 'relaAjaxLink-wrapper';
      $wrapper = $('<div></div>', {id: id});

      var element_settings = {
        url: url,
        event: 'click',
        submit: params
      };

      Drupal.ajax[id] = new Drupal.ajax(id, $wrapper[0], element_settings);
      $wrapper.click();
    }
  }

  // Add Drupal ajax link.
  window.relaAjaxLink = function(url) {
    // Only allow this for relajax/ urls.
    if (url.indexOf('/relajax/') == 0) {
      var id = 'relaAjaxLink-wrapper';
      $wrapper = $('<div></div>', {id: id});

      var element_settings = {
        url: url,
        event: 'click'
      };

      Drupal.ajax[id] = new Drupal.ajax(id, $wrapper[0], element_settings);
      $wrapper.click();
    }
  }

  window.getTextColor = function($element) {
    var bgColor = $element.css('background-color');
    var count = 0;

    while (!bgColor || bgColor == 'rgba(0, 0, 0, 0)') {
      count += 1;
      $element = $element.parent();
      if ($element.is('body') || count >= 100) {
        bgColor = 'rgba(255, 255, 255)';
      }
      else {
        bgColor = $element.css('background-color');
      }
    }

    var bkg = bgColor.replace(/[^0-9,\.]/g, '').split(',');
    var a = 1 - (0.299 * bkg[0] + 0.587 * bkg[1] + 0.114 * bkg[2]) / 255;
    if (a < 0.25) {
      return '#000';
    }
    else {
      return '#FFF';
    }
  }

  window.isDefined = function(something) {
    return typeof something !== "undefined";
  }

  $(document).ready(function() {

    // AJAX reload the sort images for bulk upload background process.
    if (Drupal.settings.relaPhotos) {
      $('.view-id-property_images .empty-text').css({
        'opacity': '0'
      });
      var bid = Drupal.settings.relaPhotos.imageProcessing.bid;
      var nid = Drupal.settings.relaPhotos.imageProcessing.nid;
      var query = "?timestamp=" + $.now() + "&bid=" + bid;

      var photosPercentageInterval = setInterval(function() {
        photosGetPercentage();
      }, 2000);

      var photosViewInterval = setInterval(function() {
        //photosReloadView();

        relaAjaxLink('/relajax/photos/nojs/reload-sort-view-placeholder/' + nid);
      }, 5000);

      var photosGetPercentage = function() {
        $.ajax({
          url: '/batch_percentage.php' + query,
          complete: function(data) {

            // Update the percentage.
            $('#image-processing-' + nid + ' .image-processing-status').text(data.responseText);
            $.cookie(bid, data.responseText, {
              path: '/'
            });

            if (data.responseText == 'Done') {
              $.cookie(bid, null, {
                path: '/'
              });
              clearInterval(photosPercentageInterval);
              $.ajax({
                url: '/relajax/photos/nojs/processing-complete/' + nid,
                complete: function(data) {
                  clearInterval(photosViewInterval);
                  // photosReloadView();

                  relaAjaxLink('/relajax/photos/nojs/reload-sort-view/' + nid);
                  setTimeout(function() {
                    $('.image-processing-wrapper').remove();
                  }, 4000);

                }
              });
            }
          }
        });
      };

      var photosReloadView = function() {
        if ($('.reload-image-sort-view').length) {
          $('.reload-image-sort-view').trigger('click');
        }
      };
    }

    // Something else.
    $('.promo-activation .pane-title').click(function() {
      var parent = $(this).parent();
      if (parent.hasClass('expanded')) {
        $(this).parent().removeClass('expanded');
        $(this).next().slideUp('slow');
      } else {
        $(this).parent().addClass('expanded');
        $(this).next().slideDown('slow');
      }
    });
  });

  // Custom AJAX callback to send GA event.
  Drupal.ajax.prototype.commands.sendGAEventAJAX = function(ajax, response, status) {
    var category = response.data.category || 'Category';
    var action = response.data.action || 'Action';
    var label = response.data.label || 0;
    var value = response.data.value || 0;

    sendGAEvent(category, action, label, value);
  }

  // This is literally copied from ajax.js line 501 to define
  // Drupal.ajax.prototype.commands. We're doing this so we don't wrap replaced
  // content in a stupid div.
  Drupal.ajax.prototype.commands.relaInsert = function (ajax, response, status) {
    var wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
    var method = response.method || ajax.method;
    var effect = ajax.getEffect(response);

    var new_content_wrapped = $('<div></div>').html(response.data);
    var new_content = new_content_wrapped.contents();

    switch (method) {
      case 'html':
      case 'replaceWith':
      case 'replaceAll':
      case 'empty':
      case 'remove':
        var settings = response.settings || ajax.settings || Drupal.settings;
        Drupal.detachBehaviors(wrapper, settings);
    }

    wrapper[method](new_content);

    if (effect.showEffect != 'show') {
      new_content.hide();
    }

    if ($('.ajax-new-content', new_content).length > 0) {
      $('.ajax-new-content', new_content).hide();
      new_content.show();
      $('.ajax-new-content', new_content)[effect.showEffect](effect.showSpeed);
    }
    else if (effect.showEffect != 'show') {
      new_content[effect.showEffect](effect.showSpeed);
    }

    if (new_content.parents('html').length > 0) {
      var settings = response.settings || ajax.settings || Drupal.settings;
      Drupal.attachBehaviors(new_content, settings);
    }
  };


  Drupal.behaviors.propertyGalleryProtect = {
    attach: function(context, settings) {

      $('.pswp__item').on('contextmenu', 'img', function(e) {
        return false;
      });
    }
  }

  // Send GA on checkout
  Drupal.behaviors.relaAnalytics = {
    attach: function(context, settings) {


      // Check for UTMs.
      var utmSource = getUrlParameter('utm_source') || '';
      if (utmSource.length) {
        var utms = {
          utm_source: utmSource,
          utm_medium: getUrlParameter('utm_medium') || '',
          utm_campaign: getUrlParameter('utm_campaign') || '',
          utm_term: getUrlParameter('utm_term') || '',
          utm_content: getUrlParameter('utm_content') || '',
        }

        $.cookie('rela_utms', JSON.stringify(utms), {
          expires: 30,
          path: '/'
        });
      }

      function sendGAEvent(category, action, label, value) {
        if (typeof ga !== 'undefined') {
          if (label === undefined) {
            label = 0;
          }

          if (value === undefined) {
            value = 0;
          }
      // console.log(category, 'sendtoGA');
          ga('send', {
            'hitType': 'event',
            'eventCategory': category,
            'eventAction': action,
            'eventLabel': label,
            'eventValue': value
          });
        }
      }

      if (!$.isEmptyObject(Drupal.settings.relaAnalytics)) {
        $.each(Drupal.settings.relaAnalytics, function(k, analytics) {
          //console.log(analytics, 'analyt');
          delete Drupal.settings.relaAnalytics[k];
          sendGAEvent(analytics.category, analytics.action, analytics.label, analytics.value);
        });
      }

    }
  }

  Drupal.behaviors.bef_bootstrap_fix = {
    attach: function (context, settings) {
      var views_exposed_form = jQuery('.views-exposed-form', context);

      views_exposed_form.hide();
      views_exposed_form.find('.form-control').not('.form-text, .form-select').removeClass('form-control');
      views_exposed_form.show();
    }
  };

  Drupal.behaviors.RelazGeneral = {
    attach: function(context, settings) {

      $('.forgot-pass-login-link').click(function() {
        $('.login-form-wrapper').removeClass('hidden');
        $('.pass-reset-form-wrapper').addClass('hidden');
      });

      $('.forgot-pass-link').click(function() {
        $('.login-form-wrapper').addClass('hidden');
        $('.pass-reset-form-wrapper').removeClass('hidden');
      });

      // Checks if user loads page via backbutton history and reloads it.
      if (performance.navigation.type == 2) {
        location.reload(true);
      }
      // Automatically change text color.
      if ($('.auto-text-color', context).length) {
        $('.auto-text-color').each(function() {
          $(this).removeClass('auto-text-color');
          $(this).css('color', getTextColor($(this)));
        });
      }

      if ($('.auto-border-color', context).length) {
        $('.auto-border-color').each(function() {
          $(this).removeClass('auto-border-color');
          var bkg = $(this).css('background-color').replace(/[^0-9,\.]/g, '').split(',');
          var a = 1 - (0.299 * bkg[0] + 0.587 * bkg[1] + 0.114 * bkg[2]) / 255;
          if (a < 0.5) {
            $(this).css('border-color', '#000');
          }
          else {
            $(this).css('border-color', '#FFF');
          }
        });
      }

        // Show/hide currency in property details form.
        if ($('.change-currency').length) {
          $('.change-currency').unbind('click');
          $('.change-currency').click(function() {
            var parent = $(this).closest('.group-pricing');
            $(parent).toggleClass('us-based');
          })
        }

        // Disable submit on click.
        $('.submit-disable').on('click', function() {
          $(this).addClass('disabled');
        });

        if ($('.submit-disable').is(":disabled")) {
          $(this).addClass('disabled');
        }

        // Doing this to re-enable the button after the user changes any details
        // for their card in the form so they re-submit.
        $('.commerce_payment input, .commerce_payment select').change(function(){
          $('.submit-disable').removeClass('disabled');
          $('.payment-errors').html('');
        });

        $('.commerce_payment input').keyup(function(){
          $('.submit-disable').removeClass('disabled');
          $('.payment-errors').html('');
        });

        // Disable submit on mousedown.
        $('.submit-disable-md').on('mousedown', function() {
          $(this).addClass('disabled');
        });

        if ($('.submit-disable-md').is(":disabled")) {
          $(this).addClass('disabled');
        }

        // Auto click links.
        if ($('.auto-download').length) {
          $('.auto-download', context).each(function() {
            $this = $(this);
            var url = $this.attr('data-url') || '';
            if (url.length) {
              var delay = $this.attr('data-delay') || 0;
              setTimeout(function() {
                $this.removeClass('auto-download').hide();
                window.location.href = '/relajax/nojs/general/auto-download?url=' + url;
              }, delay);
            }
          });
        }

        // if ($('a.auto-click').length) {
          $('a.auto-click').once(function() {
            var $this = $(this);
            var delay = $this.attr('data-delay') || 0;
            if (delay == 'in-viewport') {
              if ($this.isInViewport(0.5) && !$($this).hasClass('click-processed')){
                $this.click().removeClass('auto-click').hide()
                $this.click().addClass('click-processed');
              }

              $(window).scroll(function() {
                if ($this.isInViewport(0.5) && !$($this).hasClass('click-processed')) {
                  $this.click().removeClass('auto-click').hide()
                  $this.click().addClass('click-processed');
                }
              });
            }
            else {
              setTimeout(function() {
                $this.click().removeClass('auto-click').hide();
              }, delay);
            }

          });
        // }

        $('a.auto-redirect', context).each(function() {
          var $this = $(this);
          var delay = $this.attr('data-delay') || 0;
          var countdown = $this.attr('data-countdown') || 0;

          if (countdown && delay > 0) {
            var countdownTime = delay / 1000;
            $this.before('<div class="ar-countdown">You will be redirected in <span class="ar-countdown-time">' + countdownTime + '</span> seconds.</div>');
            var countdownInt = setInterval(function() {
              var currentCountdown = parseInt($('.ar-countdown .ar-countdown-time').text());
              if (currentCountdown == 1) {
                clearInterval(countdownInt);
              }
              $('.ar-countdown .ar-countdown-time').text(currentCountdown - 1);
            }, 1000);
          }

          setTimeout(function() {
            window.location.replace($this.attr('href'));
          }, delay);

        });

        $('.right-overlay-trigger', context).click(function() {
          if (!$('#right-edit-overlay').hasClass('right-overlay-open')) {
            $('#right-edit-overlay').addClass('right-overlay-open');
            $('#right-edit-overlay').after('<div class="right-underlay"></div>');
            $('#right-edit-overlay .overlay-inner').html('<i class="loader loader-grey"></i>');
            $('#right-edit-overlay').animate({
              right: 0
            }, 500, "easeOutCubic");

            var scroll = false;
            if (jQuery('#right-edit-overlay').hasClass('scroll-top')) {
              scroll = true;
            }
            if (scroll) {
              jQuery("html, body").animate({
                scrollTop: 0
              }, "normal");
            }
          }


          return false;
        });

      $('.right-overlay-close', context).click(function() {
        $('#right-edit-overlay').removeAttr('class');
        $('.right-underlay').remove();
        $('#right-edit-overlay').animate({
          right: '-100%'
        }, 500, "easeOutCubic", function() {
          $('#right-edit-overlay .overlay-title').text('Loading...');
          $('#right-edit-overlay .overlay-inner').html('<i class="loader loader-grey"></i>');
        });
        $('body').removeClass('right-overlay-open');
        //$('.right-overlay-close').trigger('closeRightOverlay');
      });
        // Close modal on escape key.
        if ($('body.overlay-open').length) {
          $(document).keyup(function(e) {
            if ($('.rela-modal.locked').length == 0) {
              if (e.keyCode == 27) {
                $.fn.closeModal();
              }
            }
          });
        }

        // Also hide overlay close if locked.
        $('.overlay-close').show();
        if ($('.rela-modal.locked').length) {
          $('.overlay-header .overlay-close').hide();
        }

        // Add slideDown animation to Bootstrap dropdown when expanding.
        $('.dropdown').on('show.bs.dropdown', function() {
          $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
        });

        // Add slideUp animation to Bootstrap dropdown when collapsing.
        $('.dropdown').on('hide.bs.dropdown', function() {
          $(this).find('.dropdown-menu').first().stop(true, true).slideUp();
        });

        // Villa real estate phone format.
        $('.auth-20886 .field-name-field-user-phone').text(function(_, text) {
          return text.replace(/\(|\)/g, '').replace(/-/g, ' ');
        })

        // Reattach behaviors.
        $.fn.reattachBehaviors = function(selector) {
          Drupal.attachBehaviors(selector);
        };

        // Hide CC on share email for WL.
        $('#rela-property-email-share .form-type-checkbox input').change(function() {
          var checkedAgents = $('#rela-property-email-share .form-type-checkbox input:checked');
          var mail = $(this).val();
          if (this.checked) {
            $('#rela-property-email-share .cc-wrapper').slideDown();
            $('#rela-property-email-share div[data-mail="' + mail + '"]').slideDown();
          } else {
            $('#rela-property-email-share div[data-mail="' + mail + '"]').slideUp();
            if (checkedAgents.length == 0) {
              $('#rela-property-email-share .cc-wrapper').slideUp();
            } else {
              $('#rela-property-email-share .cc-wrapper').slideDown();
            }
          }
        })

        // Check DNS.
        if ($('.dns-check', context).length) {
          // Setup domain.
          if ($('td[data-domain-order]', context).length) {
            $('.dns-check', context).html('<div class="dns-check-result"><span class="fa fa-refresh fa-spin"></span> ' + Drupal.t('Processing') + '</div>');
          }
          // Check DNS Settings.
          else {
            $('.dns-check', context).each(function(k, v) {
              $this = $(this);
              if ($this.next('.dns-instructions-table').length > 0) {
                return;
              }

              $this.addClass('dns-check-' + k);

              var aRecord = $this.attr('data-arecord') || '';
              var cname = $this.attr('data-cname') || '';
              var srv = $this.attr('data-srv') || '';
              $this.html('<div class="dns-check-result"><span class="fa fa-refresh fa-spin"></span></div>');
              $.ajax({
                  method: 'POST',
                  url: '/relajax/nojs/domains/dns-check',
                  data: {
                    aRecord: aRecord,
                    cname: cname,
                    srv: srv
                  },
                })
                .done(function(data) {
                  var status = data.status;
                  var error = data.error;

                  $this = $('.dns-check-' + k);

                  var cls = status.replace(/\s+/g, '').toLowerCase();
                  $this.html('<div class="dns-check-result"><span class="fa fa-circle domain-status-' + cls + '"></span> ' + status + '</div>');

                  if (status.indexOf('Action Required') >= 0) {
                    $('body').addClass('show-dns-instructions');
                    $this.addClass('dns-invalid');

                    var showInstructions = $this.attr('data-show-errors') || false;
                    if (showInstructions && error.length > 0) {
                      $this.after(error);
                    }
                  }
                  else {
                    $('body').removeClass('show-dns-instructions');
                    if (status == 'OK') {
                      $this.removeClass('dns-invalid');
                      $this.html('<div class="dns-check-result"><span class="fa fa-check ico-green"></span> OK</div>');
                      if ($('.dns-check.wl-domain').length) {
                        $.post('/relajax/white-label/nojs/set-valid-wl-domain', {
                          cname: cname
                        });
                      }

                    }
                  }
                });
            });
          }
        }

        // Disable buttons on PLUpload submit.
        $('#rela-property-bulk-media-upload-upload-form', context).once('plupload-form', function() {
          if (0 < $(this).find('.plupload-element').length) {
            $(this).submit(function(e) {
              $('button').prop("disabled", true);
            })
          }
        });


        // Video upload stuff.
        $(window).on('beforeunload', function() {
          var ytInProgress = $.cookie['ytInProgress'];
          if (ytInProgress) {
            return Drupal.t('Warning: Your video is still uploading. Leaving this page will cancel the upload.');
          }
        });

        // Height for property header
        $('.property-header').height($('.group-property-details-right').height());

        var topOffset = $('.group-property-details-right').outerHeight() + $('.property-details-title').outerHeight();
        $('.details-group-wrap').css('margin-top', -topOffset);

        $('.no-brochure', context).click(function() {
          $('.no-brochure-message').slideDown('normal');
          return false;
        });

        if ($('.phone-format').length && !$('body').hasClass('user-21906')) {
          $('.phone-format input').mask("(999) 999-9999");
        }

        if ($('#property-edit-messages').hasClass('showing')) {
          setTimeout(
            function() {
              // $('#property-edit-messages').fadeOut(500, function(){
              //   $(this).removeClass('showing');
              // });
              $("#property-edit-messages").animate({
                top: -10 + "px"
              }, 200, function() {
                //Animation complete
                $(this).hide();
                $(this).css("top", "90px");
              });
            }, 2000);
        }

        $('.overlay-trigger', context).click(function() {
          var style = $(this).data('style');

          if (style !== undefined) {
            $('.overlay-content').attr('class', 'overlay-content');
            $('.overlay-content').addClass(style);
          } else {
            $('.overlay-content').attr('class', 'overlay-content');
          }
          $('#ajax-content-overlay').fadeIn();

          $('.overlay-content').show();
          $('#overlay-content-static').hide();
          $('.overlay-content').html('<div class="loader"></div>');
          $('body').addClass('overlay-open');

          if ($(this).attr('data-youtube-id')) {
            var videoID = $(this).attr('data-youtube-id');
            var embedURL = 'https://www.youtube.com/embed/' + videoID + '?autoplay=1&modestbranding=1&rel=0&showInfo=0&vq=hd720';
            var videoIframe = '<div id="property-video-modal" class="aspect-ratio-content">';
            videoIframe += '<iframe width="100%" height="100%" src="' + embedURL + '" frameborder="0" allowfullscreen></iframe></div>';
            $('.overlay-content').addClass('overlay-sixteen-nine').html(videoIframe);
          }

        });

        $('.overlay-close', context).click(function() {
          $('#ajax-content-overlay').fadeOut();
          $('.overlay-content').html('');
          $('.overlay-content').attr('class', 'overlay-content');
          $('body').removeClass('overlay-open');
          $('#overlay-content-static').hide();
          setTimeout(function() {
            $('#ajax-content-overlay').removeClass();
          }, 500);
          return false;
        });


        // Doing all leadop cookie checks in the front end and not in backend.
        $('#lead-pop-check', context).click(function() {
          if ($('body').hasClass('ppss-required')) {
            return false;
          }
          var pid = $(this).data('pid');
          var type = $(this).data('type');
          var lpid = getUrlParameter('lpid')
          var setLPcookie = false;
          var mls = getUrlParameter('mls');
          var utmMedium = getUrlParameter('utm_medium');

          var path = $(location).attr('href');
          path = path.split("/");
          if (mls === true || path[3] === 'mls' || path[3] === 'pv' || utmMedium === 'property_fb_ad') {
            setLPcookie = true;
            if (type == 'click for price') {
              var price = $('.click-for-price').data('price');
              if (price !== null) {
                $('.price-field').html(price);
              }

              return;
            }
          }

          // Check url param and hash in settinsg and set cookie if match.
          if (settings.relaPIDhash !== undefined) {
            if (lpid !== undefined) {
              if (lpid == settings.relaPIDhash) {
                setLPcookie = true;
              }
            }
          }
          // If cookie doesnt exists and set flag is true, then set.
          if ($.cookie('rela_leadpop') === null) {
            if (setLPcookie == true) {

              var dis = [];
              dis.push(pid);
              $.cookie('rela_leadpop', JSON.stringify(dis), {
                expires: 14,
                path: '/'
              });
              // click this check link again and it should run through.
              $('#lead-pop-check').click();

            }
            else {
              // if no cookie, and not ready to set, then click the link.
              $('.lead-pop-link-auto').click();
              setExitPop();
            }
          }
          // If we have the cookie, check if correct one, if not, then click
          else {
            //have cookie
            var cooky = $.parseJSON($.cookie('rela_leadpop'));
            if (typeof pid !== 'string') {
              // if the shit is set from php it's not a string so check and covert
              // so we can check the inarray correctly.
              pid = pid.toString();
            }
            if ($.inArray(pid, cooky) !== -1) {
             // Cookie validates against property, so show price.
             if (type == 'click for price') {
              var price = $('.click-for-price').data('price');
              $('.price-field').html(price);
             }
            }
            else if (setLPcookie == true) {
              cooky.push(pid);
              $.cookie('rela_leadpop', JSON.stringify(cooky), {
                expires: 14,
                path: '/'
              });
            }
            else {
              // click the leadpop link, but not price or the exit intent
              $('.lead-pop-link-auto').click();
              setExitPop();

            }
          }
        });

        $('.lead-pop-link', context).click(function() {
          var mls = getUrlParameter('mls');
          var $this = $(this);
          var delay = $(this).attr('data-delay') || 0;
          var style = $(this).data('style');

          if ($('body').hasClass('ppss-required')) {
            return false;
          }

          if (mls !== true) {
            setTimeout(function() {
              if (style !== undefined) {
                $('.overlay-content').attr('class', 'overlay-content');
                $('#ajax-content-overlay').addClass(style);
              }
              else {
                $('.overlay-content').attr('class', 'overlay-content');
              }
              $('#ajax-content-overlay').show();

              $('#overlay-content-static').show();
              $('body').addClass('overlay-open');
              if ($this.attr('data-static-content')) {
                 var target = $this.attr('data-static-content');
                 $('#' + target).show().detach().appendTo('#overlay-content-static');
              }

            }, delay);
            return false;
          }
        });

        function setExitPop(){
          $('.lead-pop-exit', context).each(function(){
            $(function() {
              ddexitpop.init({
                contentsource: ['id', 'ph'],
                fxclass: 'random',
                displayfreq: 'always',
                onddexitpop: function($popup) {
                  $('.lead-pop-exit').click();
                }
              })
            });
          })
        }
        // $('.overlay-trigger-static', context).click(function() {
        //   $('#overlay-content-static').show();
        //   $('#ajax-content-overlay').fadeIn('fast');
        //   $('.overlay-content').hide();

        //   var target = $(this).attr('data');
        //   var style = $(this).data('style');
        //   $('.static-content').hide();
        //   $(target + '.static-content').show();
        //   if (style !== undefined) {
        //     $('#overlay-content-static').removeClass();
        //     $('#overlay-content-static').addClass(style);
        //   } else {
        //     $('#overlay-content-static').removeClass();
        //   }
        //   $('#' + target).addClass('static-content');
        //   $('#' + target).detach().appendTo('#ajax-content-overlay #overlay-content-static');
        //   $('#' + target).show();
        //   return false;
        // });



        // Property image delete confirm open/close
        $('.prop-image-delete', context).unbind().click(function() {
          var wrapper = $(this).parent().find('.prop-image-delete-confirm-wrapper');
          $('.prop-image-delete-confirm-wrapper').not(wrapper).slideUp();
          $('.prop-image-download-select-wrapper').slideUp();
          wrapper.slideToggle();
        });

        $('.prop-image-delete-cancel', context).click(function() {
          $(this).parent().slideUp();
        });

        // Property image download.
        $('.prop-image-download', context).unbind().click(function() {
          var wrapper = $(this).parent().find('.prop-image-download-select-wrapper');
          $('.prop-image-download-select-wrapper').not(wrapper).slideUp();
          $('.prop-image-delete-confirm-wrapper').slideUp();
          wrapper.slideToggle();
        });

        // Send An Invite form.

        // Modal email link
        // $('.overlay-content .send-invite-email', context).click(function() {
        //   $('.overlay-content #send-invite-links').addClass('hidden');
        //   $('.overlay-content #rela-referrals-send-email-invite').removeClass('hidden');
        // });

        $('.overlay-content .send-invite-back, .overlay-close', context).click(function() {
          $('.overlay-content #send-invite-links').removeClass('hidden');
          $('.overlay-content #rela-referrals-send-email-invite').addClass('hidden');
          $('.alert-block').remove();
        });

        $('.status-switch', context).click(function() {
          if ($(this).hasClass('open')) {
            $('.switch-link').slideUp();
            $(this).removeClass('open');
            $('.switch-icon').removeClass('fa-rotate-180');
          } else {
            $('.switch-link').slideDown();
            $(this).addClass('open');
            $('.switch-icon').addClass('fa-rotate-180');
          }
        });


        $("#dashboard-left-nav", context).hoverIntent({
          over: expandMenu,
          out: collapseMenu,
          // selector: 'div'
        });

        function expandMenu() {
          $("#dashboard-left-nav").addClass('expanded');

        }

        function collapseMenu() {
          $("#dashboard-left-nav").removeClass('expanded');
          $('#dashboard-left-nav .dropup').removeClass('open');

        }

        $.fn.fakeSaveTriggered = function() {
          $('.fake-save').clearQueue();
          var btnText = 'Save';
          //console.log(btnText);
          $('.fake-save').html(btnText + ' <span class="fa fa-refresh fa-spin"></span>');
          setTimeout(function() {
            $('.fake-save').html('Saved <span class="fa fa-check"></span>');
          }, 1000);
          setTimeout(function() {
            if ($('.fake-save').hasClass('no-text')) {
              btnText = '';
            }
            $('.fake-save').text(btnText);
          }, 3000);

          $('#property-edit-messages .pane-content').html('Property Saved!');
          $('#property-edit-messages')
            .delay(500).addClass('animated').removeClass('slideOutUp').addClass('slideInDown').show()
          setTimeout(function() {
            $('#property-edit-messages').removeClass('slideInDown').addClass('slideOutUp');
          }, 2000);

          var pid = $(this).attr('data-pid') || 0;
          if (pid > 0) {
            $.post('/relajax/nojs/property/' + pid + '/clearcache');
          }
        };

        $('.fake-save-disabled', context).click(function() {
          $(this).html('Save <span class="fa fa-refresh fa-spin"></span>').fakeSaveTriggered();
        });

        $('.fake-save-enabled', context).click(function() {
          $(this).html('Save <span class="fa fa-refresh fa-spin"></span>')

          var $formBtn = $('.form-actions .form-submit');

          if ($formBtn.length) {
            $('.form-actions .form-submit').click();
            $('.form-actions .form-submit').mousedown();
          }
          else {
            $(this).fakeSaveTriggered();
          }

          return false;
        });

        if ($.isFunction($.fn.perfectScrollbar)) {
          $("#property-list-scroll").perfectScrollbar();
          $('.property-template-focal .field-name-field-property-description .field-item').perfectScrollbar({
            //wheelPropagation: true
          });
        }

        $('.flag-admin-message-mark-as-read a').each(function() {
          if ($(this).hasClass('unflag-action')) {
            $(this).parent().parent().parent().addClass('message-read');
            $(this).parent().parent().parent().removeClass('message-unread');
          } else {
            $(this).parent().parent().parent().addClass('message-unread');
            $(this).parent().parent().parent().removeClass('message-read');
          }
        });

        $('.animate-bg-x').animate({
          'background-position-x': '100%',
        }, 10000, 'linear', function() {
          $(this).animate({
            'background-position-x': '0%',
          }, 100000, 'linear');
        });

        $('.exit-cta').on('click', function() {
          $('#exit_intent_lead_node_form_wrapper').animateCss('fadeInUp', function() {
            $('#exit_intent_lead_node_form_wrapper').addClass('active');
        })
      });

      } // End Attach Behaves
  }; //End Function

  Drupal.behaviors.relaFlyerDownload = {
    attach: function(context, settings) {
      if ($('.prompt-claim').length) {
        $('body').once('prompt-claim', function() {
          setTimeout(function() {
            $('.prompt-claim').trigger('click');
          }, 5000);
        });
      }
    }
  }

  Drupal.behaviors.liveImageStyleRefresh = {
    attach: function(context, settings) {

      if (settings.relaDemo !== undefined) {

        $('.live-image-refresh img').once('image-refresh', function() {
          var imagePath = $(this).attr('src');
          $(this).attr('src', imagePath + '?' + settings.relaDemo.refreshStyle);

        })

      }
    }
  }

  /**
   * Default text for textfields.
   * @type {Object}
   */
  Drupal.behaviors.defaultFormText = {
    attach: function(context, settings) {

        var inputs = $('.clear-text:not(.processed)');

        // Store the orginal values
        inputs.each(function() {
          $this = $(this);
          $this.data('default', $this.val());
        }).addClass('processed grey-text');

        inputs
          .focus(function() {
            $this = $(this);
            if ($this.val() == $this.data('default')) {
              $this.val('');
              $this.removeClass('grey-text');
            }
          })
          .blur(function() {
            $this = $(this);
            if ($this.val() == '') {
              $this.val($this.data('default'));
              $this.addClass('grey-text');
            }
          });

        // Add a pseudo checkbox.
        var checkIcon = '<img width="13" height="13" src="/sites/all/themes/relaz/images/svg/checkmark_white.svg">';
        $('.pseudo-checkbox').each(function() {
          $realCheckbox = $(this);
          if ($realCheckbox.next('.pseudo-checkbox-input').length == 0) {

            $pseudoCheckbox = $('<div class="pseudo-checkbox-input"><span class="pseudo-checkbox-check">' + checkIcon + '</span></div>');
            $pseudoCheckbox.attr('style', $realCheckbox.attr('style'));
            $pseudoCheckbox.css('color', getTextColor($realCheckbox));

            if ($realCheckbox.attr('checked') == 'checked') {
              $pseudoCheckbox.addClass('checked');
            }
            else {
              $pseudoCheckbox.removeClass('checked');
            }
            $realCheckbox.after($pseudoCheckbox);
          }
        });

        $('.pseudo-checkbox-input').once().click(function() {
          $(this).prev('.pseudo-checkbox').click();
        });

        $('.pseudo-checkbox').once().click(function() {
          $(this).next('.pseudo-checkbox-input').toggleClass('checked');
        });

      } // End Attach Behaves
  }; //End Function

  /**
   * Waypoints
   */
  Drupal.behaviors.Waypoints = {
    attach: function(context, settings) {

        // Add this class to a div in the template to trigger the waypoint.
        var waypointTrigger = $('.waypoint-trigger');
        var waypointOffset = 0;
        if ($(waypointTrigger).attr('waypoint-offset')) {

          waypointOffset = $(waypointTrigger).attr('waypoint-offset');
        }
        var waypoints = $(waypointTrigger, context).waypoint(function(direction) {
          if (direction == 'down') {
            $('#sticky-menu').addClass('stuck');
            $('body').addClass('scrolled');
          }
        }, {
          offset: waypointOffset
        })

        var waypointOffsetUp = 100;
        if ($(waypointTrigger).attr('waypoint-offset-up')) {
          waypointOffsetUp = $(waypointTrigger).attr('waypoint-offset-up');
        }
        $(waypointTrigger, context).waypoint(function(direction) {
          if (direction == 'up') {
            $('#sticky-menu').removeClass('stuck');
            $('body').removeClass('scrolled');
          }
        }, {
          offset: waypointOffsetUp
        });

        var waySpy = $('.spy-nav', context).waypoint(function(direction) {
          if (direction == 'down') {

            var spyID = this.element.id;
            $('.region-content .active-spy').removeClass('active-spy');
            $('a[href="#' + spyID + '"]').addClass('active-spy');
          }
        }, {
          offset: '25%'
        })

        var waySpy = $('.spy-nav', context).waypoint(function(direction) {
          if (direction == 'up') {

            var spyID = this.element.id;
            $('.region-content .active-spy').removeClass('active-spy');
            $('a[href="#' + spyID + '"]').addClass('active-spy');
          }
        }, {
          offset: '-25%'
        })


        var navHeight = $('#navbar').outerHeight(true)
        var wizardWaypoints = $('#wizard-steps-pane', context).waypoint(function(direction) {

          if (direction == 'down') {
            var offset1 = $('#wizard-steps-pane').outerHeight(true)
            $('#wizard-steps-pane').addClass('affix');
            var marginTop = $('#wizard-steps-pane').outerHeight(true) + $('#wizard-top-submit-pane').outerHeight(true);
            $('#wizard-top-submit-pane').addClass('affix').css('top', offset1 - 15);
            $('body').css('margin-top', marginTop);
            $('body').addClass('wizard-scrolled')
          }
        }, {
          offset: 0
        });

        $('#wizard-steps-pane', context).waypoint(function(direction) {
          if (direction == 'up') {
            $('#wizard-steps-pane').removeClass('affix');
            $('#wizard-top-submit-pane').removeClass('affix');
            $('body').css('margin-top', 0);
            $('body').removeClass('wizard-scrolled')
          }
        }, {
          offset: 0
        });

        $('#navbar.navbar-fixed-top', context).affix({
          offset: {
            top: 80
              //bottom: -80
          }

        });


        // $('#wizard-steps-pane', context).affix({
        //   offset: {
        //     top: function() {

        //       return (this.top = $('#navbar').outerHeight(true))
        //     }
        //   }
        // });

        // $('#wizard-top-submit-pane', context).affix({
        //   offset: {
        //     top: function() {
        //       var topPos = $('#wizard-steps-pane').outerHeight(true);
        //       $('#wizard-top-submit-pane').css("top", topPos);
        //       $('body').addClass("wizard-scrolled");
        //       console.log(topPos);
        //       return (this.top = $('#navbar').outerHeight(true))
        //     }
        //   }
        // });


        //}// End check waypoint function
      } // End Attach Behaves
  }; //End Function

  Drupal.behaviors.LinkScroll = {
    attach: function(context, settings) {

      $('.sticky-link a', context).click(function() {
        var sectionId = $(this).attr('href');
        var menuHeight = $('#navbar').height()
        var scrollOffset = 0;

        if ($(this).attr('data-scroll-to')) {
          sectionId = $(this).attr('data-scroll-to')
        }

        if ($(this).attr('data-scroll-offset')) {
          scrollOffset = $(this).attr('data-scroll-offset');
        }
        if ($(sectionId).attr('data-scroll-offset')) {
          scrollOffset = $(sectionId).attr('data-scroll-offset');
        }
        if ($(sectionId).length) {
          $('.sticky-link a.active').removeClass('active');
          $(this).addClass('active');
          $('html, body').animate({
            scrollTop: $(sectionId).offset().top - menuHeight - scrollOffset
          }, 1000);
        }
        if ($('.navbar-collapse').hasClass('in')) {
          $('.navbar-collapse').removeClass('in');
        }
        return false;
      });
    }
  }; // End Function

  /**
   * Custom tabs for the dashboard. This can be used globally as well.
   */
  Drupal.behaviors.TabContent = {
    attach: function(context, settings) {

        if ($('.tabs-wrapper', context).not('.static').length > 0) {
          $('.tabs-wrapper').not('.static').each(function() {
            var tabsWrapper = $(this);
            var tabsContentWrapper = $(tabsWrapper).next('.tab-content-wrapper');

            $(tabsWrapper).find('.tab a').click(function() {
              $(tabsWrapper).find('.active-tab').removeClass('active-tab');
              $(tabsWrapper).find('.active-tab-parent').removeClass('active-tab-parent');
              $(this).addClass('active-tab');
              $(this).parent().addClass('active-tab-parent');
              $(tabsContentWrapper).children('.tab-content-active').removeClass('tab-content-active').hide();
              var tabContentHref = $(this).attr('href').split('#');
              var tabContentID = '#' + tabContentHref[1];
              //#tab-x-content
              $(tabContentID).fadeIn().addClass('tab-content-active');
              var resizeEvent = new Event('resize');

              window.dispatchEvent(resizeEvent);
              return false;
            });

            var firstTab = $(tabsWrapper).find('.tab:first a');
            var firstTabID = firstTab.attr('href');

            // This fixes ajax reloads from grabbing the first tab again.
            $(tabsWrapper).find('.tab a').each(function() {
              if ($(this).hasClass('active-tab')) {
                firstTab = $(this);
              }
            });

            // You can set the active tab via php if you send in drupal settings.
            // Helpful for form submits and shit.
            if (Drupal.settings.relaTabs !== undefined) {
              firstTabID = Drupal.settings.relaTabs.activeTab;
              firstTab = $(tabsWrapper).find('.tab a[href="' + firstTabID + '"]');
              firstTab.click();
              Drupal.settings.relaTabs = undefined;
            }

            // if ?active_tab=xxxx is a query in the url.
            var active_tab_query = getUrlParameter('active_tab') || '';
            if (active_tab_query) {

              $('body').once('active_tab_in_url', function() {
                // get rid of the param so a reload doesnt fire it again.
                // This will also remove it from history so they can go back to the
                // original tab @see https://stackoverflow.com/a/22753103

                var newURL = location.href.split("?")[0];
                window.history.replaceState('object', document.title, newURL);
                firstTabID = '#' + active_tab_query;
                firstTab = $(tabsWrapper).find('.tab a[href="' + firstTabID + '"]');
              });
            }

            $(firstTab, context).parent().addClass('active-tab-parent');
            $(firstTab, context).addClass('active-tab');
            $(tabsContentWrapper).children('.tab-content').hide();
            // Make sure this isn't a link
            if (firstTabID[0] != '/') {
              $(firstTabID, context).addClass('tab-content-active');
            }
          });
        }

        // WL Onboard Sidebar.
        if (Drupal.settings.wlOnboardStatus !== undefined) {
          if ($('#wl-show-onboard-link').length) {
            setTimeout(function() {
              $('#wl-show-onboard-link', context).click();
            }, 1000);

          }
        }

      } // End Attach Behaves
  }; //End Function

  Drupal.behaviors.TogglePricing = {
    attach: function(context, settings) {
      $('.toggle-yearly', context).click(function() {
        $('.price-toggle-wrapper').removeClass('prices-show-monthly');
        $('.price-toggle-wrapper').addClass('prices-show-yearly');
        return false;
      });

      $('.toggle-monthly', context).click(function() {
        $('.price-toggle-wrapper').removeClass('prices-show-yearly');
        $('.price-toggle-wrapper').addClass('prices-show-monthly');
        return false;
      });

      $('.price-toggle a', context).click(function() {
        $('.price-toggle-wrapper .active-toggle').removeClass('active-toggle');
        $('.price-toggle-wrapper .active-toggle-parent').removeClass('active-toggle-parent');
        $(this).addClass('active-toggle');
        $(this).parent().addClass('active-toggle-parent');
        return false;
      });

      $('.product-frequency-switch a').click(function() {
        $('.product-frequency-switch a.active').removeClass('active');
        $(this).addClass('active');
        var activeFreq = $(this).attr('data-toggle-group')
        $('.show').removeClass('show');
        $('.' + activeFreq).addClass('show');
        return false;

      });

      // Pricing quick pick.
      $('.product-frequency-switch a.active').each(function() {
        var activeFreq = $(this).attr('data-toggle-group')
        $('.' + activeFreq).addClass('show');
      });

    }
  }

  Drupal.behaviors.ToggleGroups = {
    attach: function(context, settings) {
      $('.toggle-trigger').unbind('click');
      $('.toggle-trigger').click(function() {
        if ($(this).hasClass('toggle-on')) {
          // Remove everything with toggle-on class.
          $('.toggle-on').removeClass('toggle-on');
        } else {
          // Remove everything with toggle-on class.
          $('.toggle-on').removeClass('toggle-on');

          // Toggle class toggle-on for this trigger.
          $(this).toggleClass('toggle-on');

          // Add toggle-on class to extra element.
          if ($(this).attr('data-target').length) {
            var target = $(this).attr('data-target');
            $(target).addClass('toggle-on');
          }
        }

      });

      $('.toggle-first', context).find('.toggler:first').addClass('active');

      $('.toggler', context).click(function() {
        var showToggle = $(this).attr('id') + '-toggled';
        if ($(this).hasClass('toggler-single')) {
          $(this).removeClass('active');
        }
        else {
          $('.toggler.active').removeClass('active');
        }

        $('.toggled.toggled-active').removeClass('toggled-active');
        $(this).addClass('active');

        $('#' + showToggle + '.toggled').addClass('toggled-active');
      });
    }
  }

  Drupal.behaviors.DropdownToggle = {
    attach: function(context, settings) {
      $('.dropdown-link-wrapper .dropdown-link-title-wrapper', context).on('click', function() {
        if ($(this).parent().hasClass('collapsed')) {
          $('body').find('.dropdown-link-wrapper.open .dropdown-link-title-wrapper').each(function() {
            dropdown_close($(this))
          });
          dropdown_open($(this));
        } else {
          dropdown_close($(this));
        }
      });

      function dropdown_open(drop_item) {
        // $(drop_item).parent().find('.dropdown-link-content-wrapper').slideDown();
        $(drop_item).parent().removeClass('collapsed');
        $(drop_item).parent().addClass('open');
        $(drop_item).find('.fa-chevron-down').addClass('fa-rotate-180');
      }

      function dropdown_close(drop_item) {
        // $(drop_item).parent().find('.dropdown-link-content-wrapper').slideUp('fast');
        $(drop_item).parent().removeClass('open');
        $(drop_item).parent().addClass('collapsed');
        $(drop_item).find('.fa-chevron-down').removeClass('fa-rotate-180');
      }

      // Show-hide toggler.
      $('.show-hide-toggle-trigger').click(function(e) {
        e.stopImmediatePropagation();
        if ($(this).hasClass('showing')) {
          $(this).next('.show-hide-toggle-content').slideUp();
        } else {
          $(this).next('.show-hide-toggle-content').slideDown();
        }

        $(this).toggleClass('showing');
        $(this).parent().toggleClass('showing');
      });
    }
  }

  Drupal.behaviors.LiveSearch = {
    attach: function(context, settings) {
      $('#property-search', context).keyup(function() {
        var filter = $(this).val();
        $('.search-icon-default').hide();
        $(".property-list-row").each(function() {
          if ($(this).text().search(new RegExp(filter, "i")) < 0) {
            $(this).fadeOut();
          } else {
            $(this).show();
          }
        })
      });

      $('.search-icon-clear', context).click(function() {
        $('#property-search').val('');
        $('.search-icon-default').show();
        $(".property-list-row").each(function() {
          $(this).show();
        });
      });

      $('.prefill-btn', context).click(function() {

        var prefillText = $(this).data('prefill-text');

        // If the button option is already clicked then clear the filter.
        if ($('#property-search').val() == prefillText) {
          $('#property-search').val("");
          $('.search-icon-default').show();
          $(".property-list-row").each(function() {
            $(this).show();
          });
        } else {
          $('#property-search').val(prefillText);
          $('.search-icon-default').hide();
          $(".property-list-row").each(function() {
            if ($(this).text().search(new RegExp(prefillText, "i")) < 0) {
              $(this).fadeOut();
            } else {
              $(this).show();
            }
          })
        }
      });
    }
  }

  Drupal.behaviors.Leadfilter = {
    attach: function(context, settings) {
      var noResults = function() {
        if ($('.view-display-id-block_property_leads .view-content', context).children(':visible').length == 0) {

          $('.view-display-id-block_property_leads .view-footer').show();
        } else {
          $('.view-display-id-block_property_leads .view-footer').hide();
        }
      }

      $("[id^='edit-ratings-']", context).change(function() {

        var countChecked = $("[id^='edit-ratings-']").filter(":checked").length;

        if (countChecked == 0) {
          $('.views-row-lead').show();
          noResults();
        } else {

          $('.views-row-lead').hide();
          $("[id^='edit-ratings-']:checked", context).each(function() {
            var filterVal = $(this).attr('value');
            console.log(filterVal);
            $('.rating-' + filterVal).show();
          });
          noResults();
        }
      });

    }
  }

  Drupal.behaviors.LeadToggle = {
    attach: function(context, settings) {
      $('.lead-toggle', context).click(function() {
        var leadID = $(this).attr('id') + '-content';
        var rowID = $(this).attr('id') + '-row';

        if ($('.' + leadID).hasClass('lead-toggle-content-open')) {
          $('.' + leadID).slideUp(function() {
            $('.' + leadID).removeClass('lead-toggle-content-open');
            $('.' + leadID).addClass('lead-toggle-content-closed');
            $('.' + rowID).removeClass('views-row-lead-open');
          });
        }

        if ($('.' + leadID).hasClass('lead-toggle-content-closed')) {
          $('.' + rowID).addClass('views-row-lead-open');
          $('.' + leadID).slideDown(function() {
            $('.' + leadID).removeClass('lead-toggle-content-closed');
            $('.' + leadID).addClass('lead-toggle-content-open');
          });
        }

      });
    }
  }

  Drupal.behaviors.RelazProviders = {
    attach: function(context, settings) {

      $('.field-name-field-agency-whitelabel-domain input').keyup(function() {
        $('.edit-wl-domain').text($(this).val());
      });

      $('.whitelabel-modal-trigger', context).click(function() {
        $('#whitelabel-modal').fadeIn('slow');
        $('body').addClass('overlay-open');
      })

      $('.whitelabel-modal-close', context).click(function() {
        $('#whitelabel-modal').fadeOut('slow');
        $('#whitelabel-modal').html('');
        $('body').removeClass('overlay-open');
      })
    }
  }

    Drupal.behaviors.RelazPhotoProcessing = {
    attach: function(context, settings) {

      $('.status-check-link', context).each(function() {
        var $this = $(this);
        var delay = $this.data('delay');
        var count = $this.data('count');

        // Click this once to get it going, then the delay will
        // click on the interval up to the count limit.
        $this.click();
        $progressBar = $('.progress-bar');
        if (!$progressBar.length) {
          var noBarInterval = setInterval(function () {
            if (count > 0) {
             $this.click();
             //console.log(count);
            }
            else {
              clearInterval(noBarInterval);
              //console.log('done');
            }


             count--;
          }, delay);
        }
        else {

          //return
          var progress = parseInt($progressBar.prop('style')['width']);
          var increase = 100 / (count) + 3;
          var interval = setInterval(function () {
            if (!$progressBar.length) {
              clearInterval(interval);
            }

            if (count > 0) {
              $this.click();
              //console.log(count);
            }
            else {
              clearInterval(interval);
              //console.log('done');
            }
            count--;

            }, delay);
          }

      });
   }
  }

  Drupal.behaviors.EditableAutoSave = {
    attach: function(context, settings) {

      // $('.property-photo-manage-grid .editablefield-item').blur(function(){
      //   var id = $(this + 'textarea').attr('id');
      //   var idParts = id.split("-");
      //   //edit-field-property-image-description-1-field-property-image-description-und-0-value
      //   $('#edit-field-property-image-description-' + idParts[5] + '-actions-submit').click();
      //   console.log(idParts[5]);
      // });
    }
  }


  // Drupal.behaviors.RelaYoutubeModal = {
  //   attach: function(context, settings) {
  //     var uploadingCookie = $.cookie('ytInProgress', true);
  //     if (uploadingCookie == true) {
  //       console.log('hhhhaie')
  //     }
  //   }
  // }

  Drupal.behaviors.AutoFileUpload = {
    attach: function(context, settings) {
      $('form').delegate('input.form-file', 'change', function() {
        var target = $(this).next('button[type="submit"]');
        target.mousedown();
      });

    }
  }

  Drupal.behaviors.radioActive = {
    attach: function(context, settings) {

      $('.form-type-radio input', context).each(function() {
        if ($(this).is(':checked')) {
          $(this).parent().addClass('radio-active');
        }
      });

      $('.form-type-radio input', context).click(function() {
        $(this).closest('.form-radios').find('.form-type-radio.radio-active').removeClass('radio-active');
        $(this).parent().addClass('radio-active');
      });

    }
  }

  Drupal.behaviors.scheduleBooking = {
    attach: function(context, settings) {

      $.each($('#rela_property_book_showing_form-wrapper .alert-messages-wrapper'), function() {
        $('.initial-wrapper').removeClass('active');
        $('.finish-wrapper').addClass('active');
      });

      $('#rela_property_book_showing_form-wrapper .btn-showing-next').unbind('click');
      $('#rela_property_book_showing_form-wrapper .btn-showing-next').click(function() {
        $initWrapper = $(this).closest('.initial-wrapper');
        $finishWrapper = $initWrapper.next('.finish-wrapper');

        $inputs = $initWrapper.find('.radio-active');
        if ($inputs.length == 3) {
          var displayDate = $.datepicker.formatDate('DD, MM d, yy', new Date($('.form-item-appointment-date .radio-active input').val()));
          $(this).datepicker('destroy');

          $('#rela_property_book_showing_form-wrapper .date-info').remove();
          var dateInfo = '<div class="date-info text-center">' +
          '<div class="date-type text-capitalize">' + $('.form-item-appointment-type .radio-active label').text() + '</div>' +
          '<div class="date-date h4">' + displayDate + '</div>' +
          '<div class="date-time h5">' + $('.form-item-preferred-time .radio-active label').text() + '</div>' +
          '</div>';
          $finishWrapper.remove('.date-info');
          $finishWrapper.prepend(dateInfo);

          $initWrapper.removeClass('active');
          $finishWrapper.addClass('active');
          $('.book-showing-back').show();
        }
        else {
          $('#booking-request-error').text('Please choose an Appointment Type, Date, and Preferred Time');
        }
      });

      $('.book-showing-back').unbind('click');
      $('.book-showing-back').click(function() {
        $('#booking-request-error').text('');
        $(this).hide();
        $('.finish-wrapper').removeClass('active');
        $('.initial-wrapper').addClass('active');
        $('#rela_property_book_showing_form-wrapper .btn-showing-next').show();
      });

    }
  }

  Drupal.behaviors.Owlz = {
    attach: function(context, settings) {
      $('.form-item-appointment-date .form-radios').owlCarousel({
        items: 3,
        nav: true,
        navText: ['<div class="fa fa-angle-left"></div>','<div class="fa fa-angle-right"></div>']
        // nestedItemSelector: 'form-type-radio',
      });

      if ($(".view-owl-pricing-table").length > 0) {
        var owl = $(".view-owl-pricing-table .view-content", context).owlCarousel({
          loop: false,

          navText: ['<span class="fa fa-chevron-left"></span>', '<span class="fa fa-chevron-right"></span>'],
          pagination: false,

          responsive: {
            // breakpoint from 0 up
            0: {
              items: 1,
              stagePadding: 0,
              loop: true,
              nav: true,
              center: true,
              touchDrag: true,
              mouseDrag: true
            },
            // breakpoint from 480 up
            480: {
              items: 1,
              loop: true,
              nav: true,
              center: true,
              stagePadding: 0,
              touchDrag: true,
              mouseDrag: true

            },
            // breakpoint from 768 up
            768: {
              items: 3,
              stagePadding: 0,
              //touchDrag: false,
              mouseDrag: false
            }
          }
        });
      }
    }
  }

  Drupal.behaviors.OwlzPropertyGallery = {
    attach: function(context, settings) {
      if ($(".property-gallery--owl-full").length > 0) {
        var owl = $(".property-gallery--owl-full .view-content", context).owlCarousel({
          loop: false,
          items: 1,
          nav: true,
          margin: 0,
          navText: ['<span class="icon icon-arrow-67"></span>', '<span class="icon icon-arrow-68"></span>'],
          pagination: false,
          video: true

        });
      }
    }
  }

  Drupal.behaviors.OwlzVideoGallery = {
    attach: function(context, settings) {
      if ($(".video-gallery-tabbed").length > 0) {
        var owl = $('.video-gallery-tabbed .view-content', context).owlCarousel({
          // loop: true,
          items: 1,
          thumbs: true,
          // thumbsPrerendered: true,
          thumbContainerClass: 'owl-thumbs',
          thumbItemClass: 'owl-thumb-item'
        });
      }
    }
  }

  Drupal.behaviors.DashmenuToggle = {
    attach: function(context, settings) {

      // $('.dashmenu-toggle').sidr({
      //   name: 'sidr-left',
      //   source: '#dashboard-left-nav'
      // });

      $('.dashmenu-toggle', context).click(function() {
        if ($('body').hasClass('sidemenu-open')) {
          $('body').removeClass('sidemenu-open');
        } else {
          $('body').addClass('sidemenu-open');
        }
      });

      if (typeof breaky !== 'undefined') {
        breaky.at("md", function() {
          $('body').removeClass('sidemenu-open');

        })

        breaky.above("md", function() {

          $('body').addClass('sidemenu-open');
        })

        breaky.at("xs", function() {

          $('body').removeClass('sidemenu-open');
        })
      }

      // var open = false;
      // var duration = 400;

      // // if(settings.DashmenuToggle === undefined){
      // //   // Do nothing.
      // //   console.log('pong');
      // // }
      // // else {
      // //   // this is reset when a user taps a property link from the sidebar menu.
      // //   // rela_property_manage_load_property();
      // //   open = settings.DashmenuToggle.sideBarOpen;

      // // }

      //   $('.pane-dashboard-main-content', context).click(function(){
      //     if ($('body').hasClass('fuck')) {
      //       if(open == true){
      //        closeMenu();
      //       }
      //     }

      //   });

      //   $('.dashmenu-toggle', context).click(function(){
      //     if ($('body').hasClass('fuck')) {
      //      if (open == false ) {
      //         openMenu();
      //       }
      //     }

      //   });

      // breaky.below("xs", function(){
      //   closeMenu();
      //   $('body').addClass('fuck');
      // });
      // breaky.at("sm", function(e){
      //   $('body').removeClass('fuck');
      //   openMenu();

      // });

      // function openMenu() {
      //   $('#dashboard-left-nav').animate({"left": "0px"}, 100, function(){open = true });
      //   $('#dashboard-left-submenu').animate({"left": "0px"}, duration, function(){/*Animation complete */  });
      // }

      // function closeMenu() {
      //   $('#dashboard-left-nav').animate({"left": "-255px"}, 100, function(){open = false  });
      //   $('#dashboard-left-submenu').animate({"left": "-300px"}, duration, function(){ /*Animation complete */ });
      // }
    }

  }

  Drupal.behaviors.LogoResizer = {
    attach: function(context, settings) {
      //var logo = $('.field-name-field-property-logo-reference img');
      // $(logo).resizable({
      //   maxHeight: 195,
      //   maxWidth: 350,
      //   minHeight:50,
      //   minWidth: 50,
      //   aspectRatio: true,
      //   stop: function(event, ui) {
      //     console.log(ui.size.height);
      //     console.log(ui.size.width);
      //   }
      // });
      // $(logo).draggable({
      //   containment: ".field-name-field-property-logo-reference",
      //   stop: function( event, ui ) {
      //      console.log(ui.position.left);
      //      console.log(ui.position.top);
      //   }
      // });

    }
  }

  Drupal.behaviors.FlyerLogoResizer = {
    attach: function(context, settings) {

      $('.flyer-scale-wrapper', context).each(function() {
        setTimeout(function() {
          $('body').addClass('flyer-scale-wrapper-loaded');
        }, 700);

      });



      var nid = "";
      var pid = "";
      var coordsHWTL = [];
      var logoImg = $('.demo-logo img');
      var container = $('.logo-wrapper');

      var maxImgW = 395;
      var maxImgH = 130;
      var zoomScale = 1;
      var containerArray = [];




      function getLogoBounds() {
        maxImgH = $('.logo-wrapper').css("height");
        maxImgW = $('.logo-wrapper').css("width");
      };

      function getZoomScale() {
        var obj = $('.flyer-scale-wrapper-loaded .flyer-scale-wrapper');
        var transformMatrix = obj.css("-webkit-transform") ||
          obj.css("-moz-transform") ||
          obj.css("-ms-transform") ||
          obj.css("-o-transform") ||
          obj.css("transform");
        var matrix = transformMatrix.replace(/[^0-9\-.,]/g, '').split(',');
        if (matrix[0] == matrix[3] && matrix[0] != 0) {
          zoomScale = matrix[0];
        };
      };



      // Ajax call after resize or drag has stopped to save coords into database
      // order of xy === hw, xy === tl
      function saveCoords(x, y, type) {
        x = x || 0;
        y = y || 0;
        if (type === "hw") {
          coordsHWTL[0] = Math.floor(x);
          coordsHWTL[1] = Math.floor(y);
        };
        if (type === "tl") {
          coordsHWTL[2] = Math.floor(x);
          coordsHWTL[3] = Math.floor(y);
        };
        var url = '/relajax/nojs/marketing/logo-pos/' + pid + '/' + nid;
        $.ajax({
          url: url,
          type: "POST",
          data: {
            coords: coordsHWTL
          }
        });
      };


      // Options for the resizable initialization includes autosave
      var resizeOpt = {
        containment: ".logo-wrapper",
        grid: [2, 1],
        maxHeight: maxImgH,
        maxWidth: maxImgW,
        minHeight: 25,
        minWidth: 25,
        aspectRatio: true,
        stop: function(event, ui) {
          $h = ui.size.height;
          $w = ui.size.width;
          if (zoomScale != 1) {
            $h *= zoomScale;
            $w *= zoomScale;
          }
          if (typeof saveTime !== "undefined") {
            clearTimeout(saveTime);
          };
          saveTime = setTimeout(saveCoords($h, $w, "hw"), 2000);

        },
        resize: function(event, ui) {
          if (zoomScale != 1) {
            var changeWidth = ui.size.width - ui.originalSize.width;
            var newWidth = (ui.originalSize.width + changeWidth) / zoomScale;

            var changeHeight = ui.size.height - ui.originalSize.height;
            var newHeight = (ui.originalSize.height + changeHeight) / zoomScale;

            ui.size.width = newWidth;
            ui.size.height = newHeight;
          }
        },
      };

      // Options for the draggable initialization
      var dragOpt = {
        containment: ".logo-wrapper",
        stop: function(event, ui) {
          $t = ui.position.top / zoomScale;
          $l = ui.position.left / zoomScale;
          if ($t < 0) {
            $t = 0;
          }
          if ($l < 0) {
            $l = 0;
          }
          if (zoomScale != 1) {
            $t *= zoomScale;
            $l *= zoomScale;
          }
          if (typeof saveTime !== "undefined") {
            clearTimeout(saveTime);
          };
          saveTime = setTimeout(saveCoords($t, $l, "tl"), 2000);
        },
        drag: function(event, ui) {
          if (zoomScale != 1) {
            var contWidth = container.width(),
              contHeight = container.height();
            ui.position.left = Math.max(0, Math.min(ui.position.left / zoomScale, contWidth - ui.helper.width()));
            ui.position.top = Math.max(0, Math.min(ui.position.top / zoomScale, contHeight - ui.helper.height()));
          }
        },
      };


      $('#image-adjust', context).click(function() {

        if (!$('body').hasClass("image-editor")) {
          $('body').toggleClass('image-editor');
        };

        getLogoBounds();
        getZoomScale();


        nid = $(this).attr("data-nid");
        pid = $(this).attr("data-pid");

        // Initializes Resizable and Draggable in one go
        $(logoImg).resizable(resizeOpt)
          .parent('.ui-wrapper')
          .draggable(dragOpt);

        // Saves coords to array after converting them into integers
        var coordsDict = $('.demo-logo .ui-wrapper').css(["height", "width", "top", "left"]);
        coordsHWTL = Object.keys(coordsDict).map(function(key) {
          return parseInt(coordsDict[key]);
        });
      });


      $('#image-save', context).click(function() {
        $(logoImg).resizable("destroy").parent('.ui-wrapper').draggable("destroy");
        $('body').toggleClass('image-editor');
      });

      $.fn.resetForAjax = function() {
        if ($('body').hasClass("image-editor")) {
          $(logoImg).resizable("destroy").parent('.ui-wrapper').draggable("destroy");
          $('body').toggleClass('image-editor');
        };
      };

    }
  }

  Drupal.behaviors.contactCardForm = {
    attach: function(context, settings) {
      $('.field-name-field-user-headshot .droppable-browse-button').text('Add Photo');
    }
  }


  Drupal.behaviors.screenWidth = {
    attach: function(context, settings) {

      if (typeof breaky !== 'undefined') {
        breaky.at("xs", function() {
          removeWidthClasses()
          $('body').addClass('screen-width-xs').trigger('screenXs');
        })

        breaky.at("sm", function() {
          removeWidthClasses()
          $('body').addClass('screen-width-sm').trigger('screenSm');

        })

        breaky.at("md", function() {
          removeWidthClasses()
          $('body').addClass('screen-width-md').trigger('screenMd');
        })
        breaky.at("lg", function() {
          removeWidthClasses()
          $('body').addClass('screen-width-lg').trigger('screenLG');
        })
      }

      function removeWidthClasses() {
        $('body').removeClass(function(index, css) {
          return (css.match(/(^|\s)screen-width-\S+/g) || []).join(' ');
        });
      }
    }
  }

  Drupal.behaviors.relaPhotosGrid = {
    attach: function(context, settings) {

      // Re-number images.
      $('.draggableviews-grid-property_images-sort_block').unbind('sortstop');
      $('.draggableviews-grid-property_images-sort_block').on('sortstop', function(e, ui) {
        $this = $(this);
        if ($this.find('.views-row .views-field-counter')) {
          var count = 0;
          $this.find('.views-row').each(function() {
            count += 1;
            $(this).find('.views-field-counter .field-content').text(count);
          });
        }
      });

      // Favoriting images.
      $('.views-field-field-image-favorite a').unbind('click');
      $('.views-field-field-image-favorite a').on('click', function(e) {
        e.preventDefault();

        var enabled = $(this).hasClass('favorite-1');
        if (enabled) {
          $(this).removeClass('favorite-1').addClass('favorite-0');
        }
        else {
          $(this).removeClass('favorite-0').addClass('favorite-1');
        }

        $.post($(this).attr('href'));
      });
    }
  }

  Drupal.behaviors.relaClipboard = {
    attach: function(context, settings) {

      $('.clip-btn', context).each(function() {
        $(this).tooltip({
          trigger: 'click',
          placement: 'right'
        });

        var clipboard = new Clipboard(this);

        clipboard.on('success', function(e) {
          $(e.trigger).attr('data-original-title', 'Copied!').tooltip('show').attr("disabled", "disabled");

          setTimeout(function() {
            $(e.trigger).tooltip('hide').removeAttr('disabled')
          }, 3000);
        });

        clipboard.on('error', function(e) {
          $(e.trigger).attr('data-original-title', 'Error!').tooltip('show');
          setTimeout(function() {
            $(e.trigger).tooltip('hide').removeAttr('disabled')
          }, 5000);
        });
      })
    }
  }

  // Drupal.behaviors.resizeVideo = {
  //   attach: function(context, settings) {
  //     $('body.property-template-focal', context).once('video-embed', function(){
  //     var playerID = '.player iframe';
  //     var wrapper = '#photos';
  //     function vRescale(){
  //       var w = $(wrapper).width()+200,
  //           h = $(wrapper).height()+200;

  //       if (w/h > 16/9){
  //         $(playerID).width(w).height(w/16*9);
  //         $(playerID).css({'left': '0px'});
  //       }
  //       else {
  //         $(playerID).width(h/9*16).height(h);
  //         $(playerID).css({'left': -($(playerID).outerWidth()-w)/2});
  //       }
  //     } // End viemo rescale
  //     $(window).on('load resize', function(){

  //       vRescale();
  //     });
  //   }); // End once
  //   }
  // }

  Drupal.behaviors.MTOptionToolbarDraggable = {
    attach: function(context, settings) {
      if ($(".mt-option-select-wrapper").length > 0) {
        $('.mt-option-select-wrapper').owlCarousel({
          autoWidth: true,
          items: 1,
          nav: true,
          navText: ['<div class="pe-7s-angle-left"></div>', '<div class="pe-7s-angle-right"></div>'],
        });

      }
    }
  }


  Drupal.behaviors.relaVtourShow = {
    attach: function(context, settings) {

      if ($('.vtour-overlay-trigger').length > 0) {
        $(".vtour-overlay-trigger").click(function() {
          $(this).addClass('vtour-open');
          $vtour = $(this).find('iframe');
          var src = $vtour.attr('src');
          if (~src.indexOf('matterport.com')) {
            $vtour.attr('src', src + '&play=1');
          }
        });
      }

    }
  }

  Drupal.behaviors.propertyContentOverlay = {
    attach: function(context, settings) {
      var content = false;

      $('.property-overlay-link a', context).not('.property-overlay-link-photos a').click(function() {
        $('body').removeClass('show-photos-full-bg');
        if (content && content == $(this).attr('href')) {
          return false;
        }
        content = $(this).attr('href');
        if ($('#property-overlay').hasClass('overlay-in')) {
          $('#property-overlay').animate({
            "top": "100%"
          }, 300, function() {
            $('#property-overlay').css({
              "top": "0"
            });
            animateIn(content, false);
          });
          setTimeout(function() {
            //animateIn(content, false);
          }, 1000);
          return false;
        } else {

          animateIn(content, true);
          return false;
        }


      })

      $('.property-overlay-close', context).click(function() {
        $('#property-overlay').animateCss('fadeOutDown');
        $("#property-details").animate({
          left: 0 + "px"
        }, 500, function() {
          //Animation complete
          $('#property-overlay').removeClass('overlay-in');
        });

        $("#property-price-mobile").animate({
          left: 0 + "px"
        }, 800)
        content = false;
        return false;
      })

      function animateIn(content, init) {

        $('.property-overlay-content').removeClass('active');
        $(content).addClass('active');
        $('#property-overlay').animateCss('fadeInUp');
        if (init) {
          $("#property-details").animate({
            left: -480 + "px"
          }, 200, function() {
            //Animation complete
          });
          $("#property-price-mobile").animate({
            left: -480 + "px"
          }, 500)
        }


        $('#property-overlay').addClass('overlay-in');

      }

      $('.show-photos-full-bg a', context).click(function() {
        $('body').toggleClass('show-photos-full-bg');
        $("#property-details").animate({
          left: -480 + "px"
        }, 300);
        $("#property-price-mobile").animate({
          left: -480 + "px"
        }, 500);
        $('#property-overlay').animateCss('fadeOutDown');
        $('#property-overlay').removeClass('overlay-in');
        content = false;
        return false;
      });
    }
  }

  Drupal.behaviors.additionalSeats = {
    attach: function(context, settings) {

      function showSelectedProduct() {
        $('#purchase-seats-form .additional-seats-product', context).addClass('hidden');

        var currentId = $('#purchase-seats-form .form-select', context).val();
        $('#purchase-seats-form .product-' + currentId).removeClass('hidden');
      }

      if ($('#purchase-seats-form', context).length) {
        showSelectedProduct();
        $('#purchase-seats-form .form-select', context).change(function() {
          showSelectedProduct();
        });
      }
    }
  }

  Drupal.behaviors.relaCalculateDays = {
    attach: function(context, settings) {

      // Calculate the days between 2 date fields.
      if ($('.calculate-date-trigger', context).length) {
        relaCalculateDaysBetweenDates();
        $('.calculate-date-trigger input', context).change(function() {
          relaCalculateDaysBetweenDates();
        });
      }

      function relaCalculateDaysBetweenDates() {
        var wrappers = $('.calculate-date-trigger .form-type-date-popup', context);
        var startDate = new Date(wrappers.first().find('input:first').val());
        var endDate = new Date(wrappers.last().find('input:first').val());

        var diff = new Date(endDate - startDate);
        var days = Math.floor(diff / 1000 / 60 / 60 / 24);
        days += 1;

        if ($('.calculate-date-value', context).length) {
          var multiplier = $('.calculate-date-multiplier', context).text() || 1;
          days = days * multiplier;
          if (days < 0) {
            days = 0;
          }
          $('.calculate-date-value', context).text(days);
        }

        return days;
      }
    }
  }

  Drupal.behaviors.relaAutocomplete = {
    attach: function(context, settings) {

      if ($('.rela-autocomplete').length) {
        var path = '/' + $('.rela-autocomplete').attr('rela_autocomplete_path');
        $('.rela-autocomplete input').keyup(function() {
          var string = $(this).val();
          $.get(path + '/' + string, function(data) {
            if (data.length) {

            }
          });
        });
      }
    }
  }

  Drupal.behaviors.lazyVideo = {
    attach: function(context, settings) {

      $("video.lazy source", context).each(function() {
        var sourceFile = $(this).attr("data-src");
        $(this).attr("src", sourceFile);
        var video = this.parentElement;
        video.load();
        video.play();
      });

      $("video.hover-lazy", context).once().click(function() {

        var $playing = $('video.hover-lazy.active');
        if ($playing.length > 0) {
          $playing.get(0).pause();
          $playing.removeClass('active');
        }

        var sourceFile = $(this).find('source').attr("data-src");

        $(this).find('source').attr("src", sourceFile);
          if (!$(this).hasClass('active')) {
            $(this).addClass('active');
            console.log('fua');
            var exampleVideo = $(this);
            exampleVideo.load();
            exampleVideo.get(0).play();
          }

      });

      $("iframe.lazy", context).each(function() {
        var sourceUrl = $(this).attr("data-src");


        $(this).attr("src", sourceUrl);
        setTimeout(function() {
          $('.loader-wrap').remove();
        }, 3000);

      });
    }
  }

  Drupal.behaviors.relaLazyImage = {
      attach: function(context, settings) {

        $("img.rela-lazy", context).each(function() {
          if (!$(this).hasClass('img-processed')) {
            var target = $(this);
            $('<img/>').attr('src', $(this).data('src')).on('load', function() {
              $(this).remove(); // prevent memory leaks as @benweet suggested
              target.attr('src', target.data('src')).addClass('img-processed').removeClass('rela-lazy');
            });

          }
        });

        $(".lazy-bg", context).each(function() {
          if (!$(this).hasClass('img-processed')) {
            var target = $(this);
            target.css('background-image', "url(" + target.data('src') + ")").addClass('img-processed');

          }
        });
      }
    }

  Drupal.behaviors.videoTabs = {
    attach: function(context, settings) {
      $(".video-tabs .tab", context).click(function() {
        var sourceFile = $(this).attr("data-src");
        $('video').attr("src", sourceFile);
        var video = ('#video-tab_video');
        $('.video-tabs .tab.active').removeClass('active');
        $(this).addClass('active');
       // video.load();
        // video.play();
      });
    }
  }

  Drupal.behaviors.relaAgentDiscounts = {
    attach: function(context, settings) {

      // var discounts = Drupal.settings.relaAgentDiscounts || '';
      // if (discounts.data !== undefined) {
      //   var arr = $(discounts.data)[0];
      //   $('.form-item-quantity input').change(function() {
      //     var quantity = parseInt($(this).val());
      //     $.each(arr, function(percent, value) {
      //       if (quantity >= value.min && quantity <= value.max) {
      //         console.log(percent);
      //         return false;
      //       }
      //     })
      //   })
      // }

    }
  }

  Drupal.behaviors.relaSliders = {
    attach: function(context, settings) {

      if ($('#thumb-size-slider').length) {
        var current = parseInt($('.view-property-images .views-row').css('width')) - 100;

        $('#thumb-size-slider').slider({
          min: 0,
          max: 200,
          step: 50,
          values: [current],
          slide: function(e, ui) {
            var rows = $('.view-property-images .views-row');
            $(rows).css('width', 100 + ui.value + 'px');
            $(rows).css('height', 'auto');

            if (ui.value < 50) {
              $(rows).addClass('row-sm');
            } else {
              $(rows).removeClass('row-sm');
            }
          },
          change: function(e, ui) {
            var rows = $('.view-property-images .views-row');
            $(rows).css('height', $('.view-property-images .views-row-first').css('height'));
          }
        });
      }

      // Remove the stupid Click to Edit text on property image editable fields.
      if ($('.views-field-field-property-image-description').length) {
        $('.views-field-field-property-image-description').find('.editablefield-edit').html('');

        // Blur textareas.
        $('.page-property-edit-photos', context).on('mousedown', function(e) {
          if (!$(e.target).hasClass('form-textarea')) {
            $('textarea:focus').blur();
          }
        });
      }

      $('.views-field-field-property-image-description textarea', context).on('focus', function() {
        var nid = $(this).closest('.views-row').attr('data-nid');
        localStorage.setItem(nid, $(this).val());
      });

      $('.views-field-field-property-image-description textarea', context).once().on('blur', function() {
        $viewsRow = $(this).closest('.views-row');
        var nid = $viewsRow.attr('data-nid');
        var orig = localStorage.getItem(nid);
        if ($(this).val() != orig) {
          $viewsRow.find('.form-submit').click();
        }
      });

    }
  }

  Drupal.behaviors.closeDiv = {
    attach: function(context, settings) {

      $('.close-div').click(function() {
        var divID = $(this).attr('data-close-div');
        $(divID).animateCss('slideOutUp', function() {
          $(divID).addClass('hidden');
        });
        return false;
      });


    }
  }

  Drupal.behaviors.getParamAjaxCallbacks = {
    attach: function(context, settings) {

      // Show order confirmation modal. Doing this because the users are bouncing
      // from order.wldomain.com to sites.wldomain.com, and our normal overlay
      // messages (session based) don't crossover.
      //
      var WLOrderConfirm = getUrlParameter('wl_order_confirm') || '';
      if (WLOrderConfirm) {
        $('body').once('openOrderConfirmation', function() {
          // get rid of the param so a reload doesnt fire it again.
          // This will also remove it from history so they can go back to the
          // original tab @see https://stackoverflow.com/a/22753103

          var newURL = location.href.split("?")[0];
          window.history.replaceState('object', document.title, newURL);
          relaAjaxLink('/relajax/wl-commerce/nojs/order-success-modal/' + WLOrderConfirm);
        });
      }

    }
  }

  Drupal.behaviors.relaHotspots = {
    attach: function(context, settings) {


      $(document).mousedown(function(e) {
        if ($('body').hasClass('page-property-edit-floorplans')) {
          var container = $("#mini-panel-property_edit_docs_floorplans .view-header.current-active");

          if ($(e.target).hasClass('hotspot')) {
            return;
          }
          if ($(e.target).parent().hasClass('hotspot')) {
            return;
          }

          // If the target of the click isn't the container nor a descendant of
          // the container.
          if (!container.is(e.target) && container.has(e.target).length === 0) {
            container.removeClass('current-active');
            $('.view-display-id-hotspots .view-content').removeClass('disabled');
            $('.hotspot.active').removeClass('active');
          }
        }
      });
      // This is for dragging existing hotspots on floorplan
      var spotDraggableOptions = function() {

        return {
          containment: '.hotspot-map',
          start: function(e, ui) {

            var id = $(this).attr('data-nid');
            $('.hotspot-map-wrapper .active, .view-display-id-hotspots .active').removeClass('active');
            $(this).addClass('active');
            setActive(this);
          },

          stop: function(e, ui) {
            var id = ui.helper.attr('data-nid');

            var left = parseInt($(this).css('left'));
            var top = parseInt($(this).css('top'));

            var mapWidth = parseInt($('.hotspot-map').width());
            var mapHeight = parseInt($('.hotspot-map').height());

            var newLeft = left / mapWidth * 100;
            var newTop = top / mapHeight * 100;

            $(this).css('left', newLeft + '%');
            $(this).css('top', newTop + '%');

            var floorplanId = $(this).closest('.floorplan-hotspot').attr('data-nid');
            $.post('/relajax/nojs/docs/' + floorplanId + '/save-hotspot', {
              image: id,
              left: newLeft,
              top: newTop
            });
          }
        }
      }

     /// Set active class on hotspot click.
      $(window).scroll(function(){
        $('.hotspot-photos-wrapper').fadeOut();
        $('.hotspot-viewer .hotspot.active').removeClass('active');
      });
      $('.hotspot-viewer', context).on('click', function(event){
        // don't close if clicking a spot
        if ($(event.target).hasClass('hotspot') || $(event.target).parent().hasClass('hotspot')) {
          return false;
        }
        $('.hotspot-photos-wrapper').fadeOut();
        $('.hotspot-viewer .hotspot.active').removeClass('active');


      });
      $('.hotspot-viewer .hotspot', context).hover(function() {
        var hotspot = $(this);

        if ($(this).hasClass('active')) {

          return;
        }
        $('.hotspot-photos-wrapper').fadeIn();
        setActive(hotspot)
        var uri = $(hotspot).attr('data-uri');
        //$('.current-image').attr('src', uri);
        $('.current-image').attr('src', uri);

        var layout = $(hotspot).attr('data-layout');
        $('.current-image').removeClass('portrait').removeClass('landscape').addClass(layout);
        $('.hotspot-photos-wrapper').removeClass('portrait').removeClass('landscape').addClass(layout);

        setHotspotDescription(hotspot);

       // return false;
      });



      $('.hotspot-editor .hotspot', context).hover(function(){
        var hotspot = $(this);
        if ($(this).hasClass('active')) {
          return;
        }
        setActive(hotspot)
      });
      // Remove active class on any click.
      $('.hotspot-map-wrapper, #dashboard-left-nav').click(function(e) {
        if (!$(e.target).hasClass('hotspot')) {
          // $('.hotspot-map-wrapper .active, .view-display-id-hotspots .active').removeClass('active');
        }
      });

      // Remove active class on close click.
      $('.hotspot-close').click(function() {
        $('.hotspot-map-wrapper .active, .view-display-id-hotspots .active').removeClass('active');
      })

      // Set draggable.
      if ($('.hotspot.draggable').length) {
        $('.hotspot.draggable').draggable(spotDraggableOptions());

        // Colorpicker.
        $('.field-name-field-doc-hotspot-color .color_picker').on('change', function() {
          var spotColor = $(this).css('background-color');
          var lastComma = spotColor.lastIndexOf(')');
          var opacityColor = spotColor.slice(0, lastComma) + ", 0.4)";
          $('.floorplan-hotspot .hotspot-map-wrapper .hotspot-container .hotspot-map .circle').css('background-color', opacityColor);
          $('.floorplan-hotspot .hotspot-map-wrapper .hotspot-container .hotspot-map .circle').css('border-color', spotColor);
          $('.floorplan-hotspot .hotspot-map-wrapper .hotspot-container .hotspot-map .ringer').css('border-color', spotColor);
        });
      }

      // This is for dragging images on to the floorplan
      if (Drupal.settings.relaHotspots !== undefined) {
        if (Drupal.settings.relaHotspots.floorplanDrag) {
          $('.view-display-id-property_image_select img').draggable({
          helper: 'clone',
          appendTo: ".hotspot-map",
          stop: function(e, ui) {
            var id = ui.helper.attr('data-nid');

            var left = parseInt(ui.helper.css('left'));
            var top = parseInt(ui.helper.css('top'));

            var mapWidth = parseInt($('.hotspot-map').width());
            var mapHeight = parseInt($('.hotspot-map').height());

            var newLeft = left / mapWidth * 100;
            var newTop = top / mapHeight * 100;

            // If outside of bounds then put ti back.
            if (newLeft < 0) {
              newLeft = 5;
            }
            if (newLeft > 100) {
              newLeft = 95;
            }
            if (newTop < 0) {
              newTop = 5;
            }
            if (newTop > 100) {
              newTop = 95;
            }

            var spot = $('<div></div>').addClass('hotspot draggable').css({
              left: newLeft + '%',
              top: newTop + '%',
              position:'absolute',
            });

            $(spot).attr('data-image-description', ui.helper.attr('data-image-description'));
            $(spot).attr('data-layout', ui.helper.attr('data-layout'));
            $(spot).attr('data-nid', ui.helper.attr('data-nid'));
            $(spot).attr('data-uri', ui.helper.attr('data-uri'));
            $(spot).addClass('new');


            var inner = $('<span></span>').addClass('circle').css({
              border: '2px solid rgb(230, 0, 255)',
              backgroundColor: 'rgba(230, 0, 255)',
            });
            $(spot).append(inner);

            // initialize da drag.
            //$(spot).draggable(spotDraggableOptions());

            $('.hotspot-map').append(spot);

            var floorplanId = $('.floorplan-hotspot').attr('data-nid');
            $.post('/relajax/nojs/docs/' + floorplanId + '/save-hotspot', {
              image: id,
              left: newLeft,
              top: newTop,
              add: true
            })
            .done(function(data) {
              $('#floorplan-reload').click();
              $('.view-display-id-property_image_select img.image-nid-' + id).parent().addClass('used');
            });
            }
          });
        }
      }

      function setActive(hotspot) {
        $('.view-display-id-hotspots .view-content').addClass('disabled');
        $('.view-display-id-hotspots .view-header').addClass('current-active');
        var id = $(hotspot).attr('data-nid');
        $('.hotspot-map-wrapper .active, .view-display-id-hotspots .active').removeClass('active');
        $(hotspot).addClass('active');
        //$('.views-row-' + id).addClass('active');
        var activeClone = $('.views-row-' + id + ':not(.cloned)').clone('true').addClass('cloned')
        $('.cloned').removeClass('.views-row-' + id);
        $('#hotspot-current').html(activeClone);
      }

      function setHotspotDescription(hotspot) {
        var description = $(hotspot).attr('data-image-description');
        if (description.length > 0) {
          $('.hotspot-photos-wrapper .img-description').removeClass('hidden');
          $('.hotspot-photos-wrapper .img-description').html(description);
        } else {
          $('.hotspot-photos-wrapper .img-description').addClass('hidden');
        }
      }
    }
  }
  Drupal.behaviors.btnToggleTarget = {
    attach: function(context, settings){
      $('.btn-toggle-target', context).click(function() {
        var targetText = $(this).attr('data-target-text');
        var target = $(this).attr('data-target');
        var targetClass = $(this).attr('data-target-class');

        if ($(this).text() == targetText) {
          if ($(this).attr('data-target-original-text')) {
            $(this).html($(this).attr('data-target-original-text'));
          }
          else {
            $(this).html('<i class="icon icon-arrow-left m-r-1 valign-sub"></i>Back');
          }
        }
        else {
          if ($(this).attr('data-target-original-text')) {
            $(this).attr('data-target-original-text', $(this).text());
          }
          $(this).html(targetText);
        }

        $(target).toggleClass(targetClass);
      });
    }
  }

  Drupal.behaviors.socialSharePop = {
    attach: function(context, settings){
      $('.social-share-link').click(function(){
        var url = $(this).attr('href');
        window.open(url, 'Share','width=640,height=320');
        return false;
      });
    }
  }


  Drupal.behaviors.matterportDemo  = {
    attach: function(context, settings){

      $('#rela-matterport-add-demo-property-form input.matterport-id-input').blur(function(){
        var city = $(this).data('city');
        var state = $(this).data('state');
        var zip = $(this).data('zip');
        var street = $(this).data('street');

        $('input.thoroughfare').val(street);
        $('input.locality').val(city);
        $('select.state').val(state);
        $('input.postal-code').val(zip);
      });
    }
  }

  Drupal.behaviors.wlOrderForm = {
    attach: function(context, settings) {
      if ($('.page-booking-edit').length) {
        if ($('.wl-client-order-steps').length) {
          $('.wl-client-order-form-wrapper').affix({
            offset: {
              top: $('.wl-client-order-steps').offset().top + $('.wl-client-order-steps').outerHeight(true)
            }
          });
        }

      }

      $('.address-autocomplete input.address-autocomplete-field').focus(function(){
        $(this).attr('autocomplete', 'nogo');
      });

      $('#calendar-select-wrapper .cal-select-day', context).on('mousedown', function(){
        var $el = $('.selected-day-display');
        if ($el.is(':visible')) {
          var goto = $el.offset().top - 145;
          $('html, body').animate({
           scrollTop: goto
          }, 1000);
        }
      });

      // $('.address-autocomplete input.address-autocomplete-field', context).each(function() {
      //   if (!$(this).hasClass('pac-target-input')) {
      //     console.log('hit');
      //     window.initAddressAutocomplete();
      //   }
      // });
    }
  } // End wlOrderForm.

  Drupal.behaviors.googlePlaces = {
    attach: function(context, settings) {

      if (Drupal.settings.relaGooglePlaces !== undefined) {
        setTimeout(function() {
          $('.address-autocomplete input.address-autocomplete-field').once(function() {
            initAddressAutocomplete();
          });
        }, 100);
      }

    }
  }

  Drupal.behaviors.primaryNav = {
    attach: function(context, settings) {
      //https://stackoverflow.com/a/7385673
      $(document).mouseup(function(e) {
        var container = $("#primary-front-nav");
        if ($('.primary-link.active').length > 0) {
          // if the target of the click isn't the container nor a descendant of the container
          if (!container.is(e.target) && container.has(e.target).length === 0) {
            $('.primary-link.active').removeClass('active');
          }
        }

      });


      $('.primary-link .drop-link').click(function(e){
        if ($(this).parent().hasClass('active')) {
          $(this).parent().removeClass('active');
          $('#primary-front-nav').removeClass('affix');
        }
        else {
          $('.primary-link.active').removeClass('active');
          $(this).parent().addClass('active');
          $('#primary-front-nav').addClass('affix');
        }
        e.preventDefault();
      });




    }
  }

  window.initAddressAutocomplete = function() {
    $('.pac-container').remove();

    var $field = $('.address-autocomplete input.address-autocomplete-field');
    // var id = $field.attr('id');
    var element = $field[0];

    var currentCountry = $('.address-autocomplete .commerce-stripe-country :selected').val() || false;
    var options = {
      types: ['geocode'],
    };

    if (currentCountry) {
     options.componentRestrictions = {country: currentCountry.toLowerCase()};
    }
    // Create the autocomplete object, restricting the search predictions to
    // geographical location types.
    autocomplete = new google.maps.places.Autocomplete(
        element, options);

    // Avoid paying for data that you don't need by restricting the set of
    // place fields that are returned to just the address components.
    autocomplete.setFields(['address_component']);

    // When the user selects an address from the drop-down, populate the
    // address fields in the form.
    autocomplete.addListener('place_changed', fillInAddressAutocomplete);

    // setTimeout(function() {
    //   $field.attr('autocomplete', 'nogo');
    // }, 2000);
  }

  window.fillInAddressAutocomplete = function() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    $('.address-autocomplete input').val('');

    var componentForm = {
      street_number: {
        type: 'short_name',
        drupalField: 'thoroughfare'
      },
      route: {
        type: 'long_name',
        drupalField: 'thoroughfare'
      },
      locality: {
        type: 'long_name',
        drupalField: 'locality'
      },
      administrative_area_level_1: {
        type: 'short_name',
        drupalField: 'state'
      },
      country: {
        type: 'short_name',
        drupalField: 'country'
      },
      postal_code: {
        type: 'short_name',
        drupalField: 'postal-code'
      }
    };

    // Get each component of the address from the place details,
    // and then fill-in the corresponding field on the form.
    var addy = {};
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (typeof componentForm[addressType] !== "undefined") {
        var formType = componentForm[addressType];

        if ($('.address-autocomplete .' + formType.drupalField).length) {
          var val = place.address_components[i][formType.type];
          if (addressType == 'route') {
            val = $('.address-autocomplete .' + formType.drupalField).val() + ' ' + val;
          }
          $('.address-autocomplete .' + formType.drupalField).val(val);
          addy[formType.drupalField] = val;
        }
      }
    }

    var storeID = 0;
    if (Drupal.settings.relaWLCommerce !== undefined) {
      if (Drupal.settings.relaWLCommerce.wlStoreID) {
        storeID = Drupal.settings.relaWLCommerce.wlStoreID;
      }
    }
    $.post("/relajax/nojs/global/g-address", {place: addy, storeID: storeID})
    .done(function(data) {
      if (data !== 0) {
        console.log(data);
        $('.field-name-field-wl-order-price-based-range select').val(data.range);
        $('.field-name-field-property-square-feet input').val(data.sqft);
      }
    });
  }

  // Bias the autocomplete object to the user's geographical location,
  // as supplied by the browser's 'navigator.geolocation' object.
  window.geolocateAddressAutocomplete = function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var circle = new google.maps.Circle(
            {center: geolocation, radius: position.coords.accuracy});
        autocomplete.setBounds(circle.getBounds());
      });
    }
  }

  Drupal.behaviors.frontNav = {
    attach: function(context, settings) {
      $('#primary-front-nav .outside-menu-toggle').click(function(){
        $('#nav-menu-toggle').toggleClass('open');
        $('#nav-links').toggleClass('open');
      })
    }
  };

  Drupal.behaviors.relaWLOFakeSubmit = {
    attach: function(context, settings) {
      $('.sudo-submit').on('click', function(event){
        var formID = $(this).attr('data-form-id');
        var submitName = $(this).attr('data-submit-name');
        // console.log(formID);
        // console.log(submitName);
        // console.log(formID + ' .form-submit[name="' + submitName + '"]');
        $(formID + ' .form-submit[name="' + submitName + '"').mousedown();
      });
    }
  }

  Drupal.behaviors.colorPickerFancy = {
    attach: function(context, settings) {
      //form-colorpicker
      $('.color-picker-fancy input.form-colorpicker', context).change(function(){
        var colorVal = $(this).val();
        var target = $(this).attr('name');
        // replace targets that have group-name[fieldname] with -- cuz [ ] dont work
        target = target.replace(/\[|\]/g, '--');
        console.log(target);
        $('#target-' + target + '.color-preview svg').attr('fill', '#' + colorVal);
        $('#target-' + target + '.color-preview .color-value').text('#' + colorVal);
      });
    }
  }

  Drupal.behaviors.formDropdown = {
    attach: function(context, settings) {
      $(document).on('click', '.dropdown-form .dropdown-menu', function (e) {
        e.stopPropagation();
        //$('.date-filters .btn-group').stopPropagation();
      });
      $(document).on('click', '.ui-datepicker-header', function (e) {
         e.stopPropagation();
      });

      // Doc on so it works with ajax loaded content
      $(document).on('click', '.rela-exposed-sort-drop .views-widget-sort-sort_bef_combine .form-type-radios', function(){
        if ($(this).hasClass('open')) {
          $(this).removeClass('open');
        }
        else {
          $(this).addClass('open');
        }
      });
    }
  }

})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
(function($, Drupal, undefined) {

  Drupal.behaviors.RelazPropertySideMenu = {
    attach: function(context, settings) {
      $('.sidemenu-toggle', context).click(function() {
        var identifier = '#' + $(this).attr('data-menu-id');
        $(identifier).toggleClass('side-menu-open');
      });

      $('.side-menu-over a', context).click(function() {
        $('.side-menu-open').removeClass('side-menu-open');
      });

      $('.side-menu-under', context).click(function() {
        $('.side-menu-open').removeClass('side-menu-open');
      });

      $('body', context).on('screenMd', function() {
        $('.side-menu-open').removeClass('side-menu-open');
      });


    }
  }

  Drupal.behaviors.RelazPropertyOutsideMenu = {
    attach: function(context, settings) {
      $('.outside-menu-toggle', context).click(function() {

        if ($('body').hasClass('outside-menu-open')) {
          $('body').removeClass('outside-menu-open');
          var menuData = $(this).attr('menu-data');
          setTimeout(
            function() {
              $('#outside-menu').removeClass('outside-menu-' + menuData);
            }, 1500);

        }
        else {
          $('#outside-menu .menu-content-item').hide();
          $('body').addClass('outside-menu-open');
          var menuData = $(this).attr('menu-data');
          $('#outside-menu').addClass('outside-menu-' + menuData);
          $('.menu-content-item' + '.menu-content-' + menuData).show();
        }
      });

      $('#property-nav-links li a', context).click(function() {
        $('body.outside-menu-open').removeClass('outside-menu-open');
      });
      // $('#outside-menu a:not(.auto-click)', context).click(function() {
      //   $('body').toggleClass('outside-menu-open');
      // })

    }
  }

  Drupal.behaviors.RelazMainMobileMenu = {
    attach: function(context, settings) {
      $('.close-nav', context).click(function() {

        $('#nav-mobile').removeClass('mobile-nav-open');

      });

      $('#nav-mobile .menu a', context).click(function() {

        $('#nav-mobile').removeClass('mobile-nav-open');

      });

      $('.open-nav', context).click(function() {

        $('#nav-mobile').addClass('mobile-nav-open');

      });

    }
  }

})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
(function ($) {

/**
 * Override Views prototype function so it can recognize Bootstrap AJAX pagers.
 * Attach the ajax behavior to each link.
 */
Drupal.views.ajaxView.prototype.attachPagerAjax = function() {
  this.$view.find('ul.pager > li > a, th.views-field a, .attachment .views-summary a, ul.pagination li a')
  .each(jQuery.proxy(this.attachPagerLinkAjax, this));
};

})(jQuery);
;/*})'"*/;/*})'"*/
/**
 * @file
 *
 * Overrides for ctools modal.
 *
 */

(function ($) {
  /**
   * Override CTools modal show function so it can recognize the Bootstrap modal classes correctly
   */
  Drupal.CTools.Modal.show = function(choice) {
    var opts = {};

    if (choice && typeof choice == 'string' && Drupal.settings[choice]) {
      // This notation guarantees we are actually copying it.
      $.extend(true, opts, Drupal.settings[choice]);
    }
    else if (choice) {
      $.extend(true, opts, choice);
    }

    var defaults = {
      modalTheme: 'CToolsModalDialog',
      throbberTheme: 'CToolsModalThrobber',
      animation: 'show',
      animationSpeed: 'fast',
      modalSize: {
        type: 'scale',
        width: .8,
        height: .8,
        addWidth: 0,
        addHeight: 0,
        // How much to remove from the inner content to make space for the
        // theming.
        contentRight: 25,
        contentBottom: 45
      },
      modalOptions: {
        opacity: .55,
        background: '#fff'
      }
    };

    var settings = {};
    $.extend(true, settings, defaults, Drupal.settings.CToolsModal, opts);

    if (Drupal.CTools.Modal.currentSettings && Drupal.CTools.Modal.currentSettings != settings) {
      Drupal.CTools.Modal.modal.remove();
      Drupal.CTools.Modal.modal = null;
    }

    Drupal.CTools.Modal.currentSettings = settings;

    var resize = function(e) {
      // When creating the modal, it actually exists only in a theoretical
      // place that is not in the DOM. But once the modal exists, it is in the
      // DOM so the context must be set appropriately.
      var context = e ? document : Drupal.CTools.Modal.modal;

      if (Drupal.CTools.Modal.currentSettings.modalSize.type == 'scale') {
        var width = $(window).width() * Drupal.CTools.Modal.currentSettings.modalSize.width;
        var height = $(window).height() * Drupal.CTools.Modal.currentSettings.modalSize.height;
      }
      else {
        var width = Drupal.CTools.Modal.currentSettings.modalSize.width;
        var height = Drupal.CTools.Modal.currentSettings.modalSize.height;
      }

      // Use the additionol pixels for creating the width and height.
      $('div.ctools-modal-dialog', context).css({
        'width': width + Drupal.CTools.Modal.currentSettings.modalSize.addWidth + 'px',
        'height': height + Drupal.CTools.Modal.currentSettings.modalSize.addHeight + 'px'
      });
      $('div.ctools-modal-dialog .modal-body', context).css({
        'width': (width - Drupal.CTools.Modal.currentSettings.modalSize.contentRight) + 'px',
        'height': (height - Drupal.CTools.Modal.currentSettings.modalSize.contentBottom) + 'px'
      });
    }

    if (!Drupal.CTools.Modal.modal) {
      Drupal.CTools.Modal.modal = $(Drupal.theme(settings.modalTheme));
      if (settings.modalSize.type == 'scale') {
        $(window).bind('resize', resize);
      }
    }

    resize();

    $('.modal-title', Drupal.CTools.Modal.modal).html(Drupal.CTools.Modal.currentSettings.loadingText);
    Drupal.CTools.Modal.modalContent(Drupal.CTools.Modal.modal, settings.modalOptions, settings.animation, settings.animationSpeed);
    $('#modalContent .modal-body').html(Drupal.theme(settings.throbberTheme));
  };

  /**
   * Provide the HTML to create the modal dialog in the Bootstrap style.
   */
  Drupal.theme.prototype.CToolsModalDialog = function () {
    var html = ''
    html += '  <div id="ctools-modal">'
    html += '    <div class="ctools-modal-dialog">'
    html += '      <div class="modal-content">'
    html += '        <div class="modal-header">';
    html += '          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
    html += '          <h4 id="modal-title" class="modal-title">&nbsp;</h4>';
    html += '        </div>';
    html += '        <div id="modal-content" class="modal-body">';
    html += '        </div>';
    html += '      </div>';
    html += '    </div>';
    html += '  </div>';

    return html;
  }

  /**
   * Provide the HTML to create a nice looking loading progress bar.
   */
  Drupal.theme.prototype.CToolsModalThrobber = function () {
    var html = '';
    html += '  <div class="loading-spinner" style="width: 200px; margin: -20px 0 0 -100px; position: absolute; top: 45%; left: 50%">';
    html += '    <div class="progress progress-striped active">';
    html += '      <div class="progress-bar" style="width: 100%;"></div>';
    html += '    </div>';
    html += '  </div>';

    return html;
  };


})(jQuery);
;/*})'"*/;/*})'"*/
(function ($) {

/**
 * Override Drupal's AJAX prototype beforeSend function so it can append the
 * throbber inside the pager links.
 */
Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {
  // For forms without file inputs, the jQuery Form plugin serializes the form
  // values, and then calls jQuery's $.ajax() function, which invokes this
  // handler. In this circumstance, options.extraData is never used. For forms
  // with file inputs, the jQuery Form plugin uses the browser's normal form
  // submission mechanism, but captures the response in a hidden IFRAME. In this
  // circumstance, it calls this handler first, and then appends hidden fields
  // to the form to submit the values in options.extraData. There is no simple
  // way to know which submission mechanism will be used, so we add to extraData
  // regardless, and allow it to be ignored in the former case.
  if (this.form) {
    options.extraData = options.extraData || {};

    // Let the server know when the IFRAME submission mechanism is used. The
    // server can use this information to wrap the JSON response in a TEXTAREA,
    // as per http://jquery.malsup.com/form/#file-upload.
    options.extraData.ajax_iframe_upload = '1';

    // The triggering element is about to be disabled (see below), but if it
    // contains a value (e.g., a checkbox, textfield, select, etc.), ensure that
    // value is included in the submission. As per above, submissions that use
    // $.ajax() are already serialized prior to the element being disabled, so
    // this is only needed for IFRAME submissions.
    var v = $.fieldValue(this.element);
    if (v !== null) {
      options.extraData[this.element.name] = v;
    }
  }

  // Disable the element that received the change to prevent user interface
  // interaction while the Ajax request is in progress. ajax.ajaxing prevents
  // the element from triggering a new request, but does not prevent the user
  // from changing its value.
  $(this.element).addClass('progress-disabled').attr('disabled', true);

  // Insert progressbar or throbber.
  if (this.progress.type == 'bar') {
    var progressBar = new Drupal.progressBar('ajax-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback));
    if (this.progress.message) {
      progressBar.setProgress(-1, this.progress.message);
    }
    if (this.progress.url) {
      progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
    }
    this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar');
    this.progress.object = progressBar;
    $(this.element).after(this.progress.element);
  }
  else if (this.progress.type == 'throbber') {
    this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><i class="glyphicon glyphicon-refresh glyphicon-spin"></i></div>');
    // If element is an input type, append after.
    if ($(this.element).is('input')) {
      if (this.progress.message) {
        $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>');
      }
      $(this.element).after(this.progress.element);
    }
    // Otherwise inject it inside the element.
    else {
      if (this.progress.message) {
        $('.throbber', this.progress.element).append('<div class="message">' + this.progress.message + '</div>');
      }
      $(this.element).append(this.progress.element);
    }
  }
};

})(jQuery);
;/*})'"*/;/*})'"*/
