(function ($) {

Drupal.behaviors.incubator = {
  attach: function (context, settings) {
    if (Drupal.settings.incubatorTaxonomyNoLinkTid) {
      $(".incubator-taxonomy-nolink-" + Drupal.settings.incubatorTaxonomyNoLinkTid + " a", context).each(function() {
        var $t = jQuery(this);
        $t.after($t.text());
        $t.remove();
      });
    }
    if (Drupal.settings.incubatorMobileMenu) {
      
      // Menu button, for all visitors
      var sidrsources = ['#block-search-form div.content', '.html nav.navigation', '#block-system-user-menu div.content'];
      var sidrsource = '';
      $.each(sidrsources, function(index, value) {
        if ($(value).length) {
          sidrsource += value + ', ';
        }
      });
      if (sidrsource.length) {
        sidrsource = sidrsource.substr(0,sidrsource.length - 2);
        $('#incubator-mobile-menu', context).once('sidr-menu').append('<a id="mobile-menu-button" class="sidr-button" href="#">Menu</a>');
        $('#mobile-menu-button').sidr({
          name: 'incubator-mobile-sidr-main',
          source: sidrsource,
          side: 'right'
        });
      }
      
      // Admin button, for administrators
      if ($('#admin-menu-wrapper').length) {
        $('#incubator-mobile-menu', context).once('sidr-config').prepend('<a id="mobile-config-button" class="sidr-button" href="#">Config</a>');
        $('#mobile-config-button').sidr({
          name: 'incubator-mobile-sidr-config',
          source: '#admin-menu-wrapper',
          side: 'left',
        });
      }
      
      $('.sidr-class-expandable, .sidr-class-has-subitems').once('sidr-exp').prepend('<div class="sidr-expand-toggle">+</div>');
      $('.sidr-expand-toggle').click(function() {
        if ($(this).hasClass('active')) {
          $(this).removeClass('active');
          $(this).html('+');
          $(this).siblings('ul:first').slideUp();
        }
        else {
          $(this).addClass('active');
          $(this).html('-');
          $(this).siblings('ul:first').slideDown();
        }
      });
      
    }
  }
};

Drupal.behaviors.incubatorResizeEmbeds = {
  attach: function (context, settings) {
    var allVideos = $("iframe, object, embed");
    allVideos.each(function() {
      $(this)
              .attr('data-aspectRatio', this.height / this.width)
              .attr('data-height', this.height)
              .attr('data-width', this.width)
              .removeAttr('height')
              .removeAttr('width');
    });
    $(window).resize(function() {
      allVideos.each(function() {
        var newWidth = $(this).closest('article, .block, .block-inner, .content, .views-row, td').width();
        var el = $(this);
        if (newWidth < $(this).attr('data-width')) {
          el.width(newWidth).height(newWidth * el.attr('data-aspectRatio'));
        }
        else {
          el.width(el.attr('data-width')).height(el.attr('data-height'));
        }
      });
    }).resize();
  }
};

}(jQuery));