(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);
;/*})'"*/;/*})'"*/
/**
 * 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);
;/*})'"*/;/*})'"*/
