/**
 * NjitTabbedContent behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Formstone.NoConflict();

  Drupal = Drupal || {};

  Drupal.settings = Drupal.settings || {};

  //tabbed nav
  var userNavTimer = setInterval(function(){ 
     
    if(jQuery.trim(jQuery('.user-navigation').text()) != "") {
      var userNavTimer;
      jQuery('.user-navigation  a').focus(function() {
        clearTimeout(userNavTimer);
        var parent = jQuery(this).parent();
        
        parent.addClass('user-nav-show');

        parent.trigger('hover');
        parent.trigger('mouseenter');

      });

      jQuery('.user-navigation a').blur(function() {
        var parent = jQuery(this).parent();
        userNavTimer = setTimeout(function() {
          jQuery('.user-nav-show').removeClass('user-nav-show');
          //parent.removeClass('user-nav-show');
        },200);
      }); 

      clearInterval(userNavTimer); 
    }
  }, 500);
  
  if(!ownheader){
    var navtimerForTabbed = null;
    jQuery('.navigation a, .student-navigation a').focus(function(event) {
      clearTimeout(navtimerForTabbed);
      var $this = this;
      console.log('2');
      navtimerForTabbed = setTimeout(function() { 
        if(!jQuery(jQuery($this).parent()).hasClass('opened')) {
          console.log('1');
          jQuery($this).trigger('click');
          jQuery($this).parent().trigger('mouseenter');
          event.stopPropagation()
        }
      }, 100);
      
    });
    console.log('default');
  } else {
      jQuery('.main-header .mega-nav-container nav .menu.active-with-children > li a').focus(function(event) {
      jQuery('.tabbed').removeClass('tabbed');
      var $this = jQuery(this);
      $this.parent().addClass('tabbed');
        $this.parent().trigger('focus');
        $this.parent().trigger('hover');
        $this.parent().trigger('mouseenter');
      
     // event.stopPropagation();
      
    });

    jQuery('.main-header .mega-nav-container nav .menu--submenu > li a').focus(function(event) {
    
      var $this = jQuery(this);
      $this.closest('.expanded').addClass('tabbed');

      
     // event.stopPropagation();
      
    });



  }






  /*jQuery('.main-header .mega-nav-container a').blur(function(event) {
    jQuery(this).parent().removeClass('tabbed');
    jQuery(this).parent().trigger('mouseleave');
    event.stopPropagation();
    
  });*/

  /**
   * hasScrollBar utility.
   *
   */

  (function($) {
    $.fn.hasHorizontalScrollBar = function() {
      return this.get(0).scrollWidth > this.width();
    }
  })(jQuery);
  (function($) {
    $.fn.hasVerticalScrollBar = function() {
      return this.get(0).scrollHeight > this.height();
    }
  })(jQuery);

  /**
   * TabbedContent behaviour.
   *
   */
  Drupal.NjitTabbedContent = function (container) {

    var thisContainer = container;

    /**
     * Prepare content to be converted to tabs.
     */
    this.prepareTabs = function () {
      reCalculateTab();
    };

    /**
     * Build tabs.
     */
    this.makeTabs = function () {
      var $container = $(thisContainer);

      $('.tab-control', $container).fsTabs({"mobileMaxWidth": '0'});
      $('.tab-control', $container).on("update.tabs", function(event) {
        var $tablink = $(event.currentTarget);
        window.location = $tablink.attr('data-tab-url');
        reCalculateTab(container);
      });
      // $('nav', this.$container).fsScrollbar({
      //   horizontal: true
      // });
    };

    this.setDefaultTab = function () {
      setDefaultTab();
    };

    var reCalculateTab = function (container) {
	    
      var $container = $(thisContainer);

      var container_id = Math.random().toString(16).slice(2);

      $container.attr({id: container_id + '-container'});
      var outer_width = 0;

      // Get the value for the attr 'data-tab-url'.
      var location = window.location;
      var tablink = location.hash.substring(location.hash.lastIndexOf('#')+1);
      var tabBaseUrl = location.href;
      if ($('[data-target="'+tablink+'"]').length >0) {
        var tabBaseUrl = tabBaseUrl.replace('#' + tablink, '');
      }

      $('.tab-control', $container).each(function () {
        var rel = $(this).data('target');
        $(this).attr('data-tab-url', tabBaseUrl + '#' + rel);
        var id = container_id + '-' + rel;
        $(this).attr({href: '#' + id,  "data-tabs-group":  container_id});
        var $item =  $('.tab-content[rel=' + rel + ']', $container);
        $item.attr('id', id);
        outer_width += ($(this).outerWidth() + 32); // Each item has left margin 32px and right margin 32px.
        outer_width += 1; // Added one more pixels to each tab item some tabs have decimal number width but JS can't get that decimal number.
      });
      outer_width -= 32; // First and last item don't have left and right margin.

      //$('.wide-load', $container).width(outer_width);
      if (outer_width > $container.outerWidth()) {
        $('.wide-load', $container).width(outer_width);
      }
      else {
        $('.wide-load', $container).css({width: 'auto'});
      }
      $('.bottom-line', $container).width(outer_width + 32 + 10);
    };

    var setDefaultTab = function () {
      // pick up has from url and see if it matches a tab
      var tablink = window.location.hash.substring(window.location.hash.lastIndexOf('#')+1);
      if ($('[data-target="'+tablink+'"]').length > 0) {
        $('[data-target="'+tablink+'"]').click();
        //$('div.fs-tabs-active').removeClass('fs-tabs-active');
        //$('a.fs-tabs-active').removeClass('fs-tabs-active');
        //
        //$('div[rel="'+tablink+'"]').addClass('fs-tabs-active');
        //$('a[data-target="'+tablink+'"]').addClass('fs-tabs-active');
      }
    }

    var that = this;
    this.init = function () {
      that.prepareTabs();
      that.makeTabs();
      that.setDefaultTab();
    }
  };

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.njitPhotoGallery.attach}}
   */
  Drupal.behaviors.NjitTabbedContent = {
    attach: function (context, settings) {

      // The tabbed content must be ready to be uses as tabbed content.
      // The default container selector is [data-tabbed-content="1"].
      $('[data-tabbed-content="1"]').each(function () {
        var NjitTabbedContent = new Drupal.NjitTabbedContent(this);
        fontSpy('Poppins', {
          success: function() {
            NjitTabbedContent.init();
          },
          failure: function() {
            NjitTabbedContent.init();
          }
        });
      });
      // add UI indicator if Tabs are scrolling
      var scrollShadeDebounced = _.debounce(scrollShade, 700);
      $(window).on('resize', scrollShadeDebounced);
      scrollShadeDebounced();
      function scrollShade() {
        if ($('.tabbed-nav .nav-scroll').length >= 1) {
          if ($('.tabbed-nav .nav-scroll').hasHorizontalScrollBar()) {
            $('.tabbed-nav').addClass('scrolling');
            $('.tabbed-nav.scrolling .scroll-shade').css("bottom",$('.tabbed-nav .nav-scroll').height());
          } else {
            $('.tabbed-nav').removeClass('scrolling');
          }
        }
      }

      $(".nav-scroll" ).scroll(function() {
        var maxScrollLeft = $('.nav-scroll').get(0).scrollWidth - $('.nav-scroll').get(0).clientWidth;
        if ($('.nav-scroll').scrollLeft() >= maxScrollLeft) {
          $('.tabbed-nav').removeClass('scrolling');
        } else {
          $('.tabbed-nav').addClass('scrolling');
        }
      });
    }
  }

})(Drupal, jQuery);

/**
 * NjitDropdown behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Formstone.NoConflict();

  Drupal = Drupal || {};

  Drupal.settings = Drupal.settings || {};

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

      var $target = $("select:not(.fs-select-disabled)");
      var errorClassName = 'error';
      var $fsDropdowns = $target.fsDropdown();

      $fsDropdowns.once('dropdown').each(function () {
          var hasError = $(this).hasClass(errorClassName);
          if (hasError) {
            $(this).parent().parent().find('label:not(.error)').addClass(errorClassName);
            $(this).parent().addClass(errorClassName);
          }
        })
    }
  }

})(Drupal, jQuery);

/**
 * NjitTextfield behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Formstone.NoConflict();

  Drupal = Drupal || {};

  Drupal.settings = Drupal.settings || {};

  Drupal.behaviors.NjitTextfield = {
    attach: function (context, settings) {
      $("input[type='text'].error").parent().find('label:not(.error)').addClass('error');
    }
  }

})(Drupal, jQuery);

/**
 * NjitNavigator behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Formstone.NoConflict();

  Drupal = Drupal || {};

  Drupal.settings = Drupal.settings || {};
  Drupal.settings.NjitNavigatorMenus = {};  
  Drupal.settings.NjitNavigatorMenus['navigator-student'] = [
    {
      title: 'Incoming Students',
      list: [
        {
          title: 'For Freshmen',
          list: [{
          title: 'For Transfer Students',
          list: []
        },
        {
          title: 'Placement Testing',
          list: []
        }]
        },
        {
          title: 'Placement Testing',
          list: []
        },
        {
          title: 'Summer Orientation',
          list: []
        },
        {
          title: 'NJIT Experience Day',
          list: []
        },
        {
          title: 'Getting to Campus',
          list: []
        },
        {
          title: 'Academic Support Programs',
          list: []
        }
      ]
    }, {
      title: 'Student Finances',
      list: [
        {
          title: 'Bills, Payments and Refunds',
          list: []
        },
        {
          title: 'Financial Aid',
          list: [
            {
              title: 'Dates & Deadlines',
              href: 'http://www.google.com'
            },
            {
              title: 'Tuition & Costs',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Paying Your Bill',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Getting a Refund or Credit',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Student Health Insurance',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Online Self-Service How-Tos',
              href: 'http://www.google.com'                  
            },
            {
              title: '1098-T Forms',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Title IV Authorization',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Contact Us',
              href: 'http://www.google.com'                  
            }
          ]
        },
        {
          title: 'Student Employment',
          list: []
        },
        {
          title: 'Military & Veteran Benefits',
          list: []
        }
      ]
    },
    {
      title: 'Academics',
      list: [
	      {
		      title:"Class Registration",
		      href:""
	      },
	      {
		      title:"Exam Schedules",
		      href:""
	      },
	      {
		      title:"Study Abroad",
		      href:""
	      },
	      {
		      title:"Academic Advising",
		      href:""
	      },
	      {
		      title:"Tutoring & Support",
		      href:""
	      },
	      {
		      title:"Assistance for Disabled Students",
		      href:""
	      },
	      {
		      title:"Graduation",
		      href:""
	      },
	      {
		      title:"Commencement",
		      href:""
	      },
	      {
		      title:"Pre-College Programs",
		      href:""
	      }
      ]
    },
    {
      title: 'Campus Life',
      list: [
	      {
		      title:"Campus Center",
		      href:""
	      },
	      {
		      title:"Housing & Residence Life",
		      href:""
	      },
	      {
		      title:"Dining Services",
		      href:""
	      },
	      {
		      title:"Activities & Organizations",
		      href:""
	      },
	      {
		      title:"Leadership Programs",
		      href:""
	      },
	      {
		      title:"Diversity Programs",
		      href:""
	      },
	      {
		      title:"Community Service Programs",
		      href:""
	      }
	      
      ]
    },
    {
      title: 'Health & Safety',
      list: [
	      {
		      title:"Student Health Services",
		      href:""
	      },
	      {
		      title:"Couseling & Psychological Services",
		      href:""
	      },
	      {
		      title:"Public Safety",
		      href:""
	      },
	      {
		      title:"Environmental Health & Safety",
		      href:""
	      },
	      {
		      title:"Title IX",
		      href:""
	      }
      ]
    },
    {
      title: 'Career Services',
      list: [
	      {
		      title:"Career Advising",
		      href:""
	      },
	      {
		      title:"Job Search Help",
		      href:""
	      },
	      {
		      title:"Co-ops & Internships",
		      href:""
	      },
	      {
		      title:"Job Listings",
		      href:""
	      },
	      {
		      title:"Career Fairs",
		      href:""
	      },
	      {
		      title:"Education & Workshops",
		      href:""
	      },
	      {
		      title:"On-Campus Interviews",
		      href:""
	      },
	      {
		      title:"Sponsorships & Partnerships",
		      href:""
	      }
      ]
    },
    {
      title: 'Research',
      list: [
	      {
		      title:"Funding Opportunities",
		      href:""
	      },
	      {
		      title:"Grant Management",
		      href:""
	      },
	      {
		      title:"Research Compliance",
		      href:""
	      },
	      {
		      title:"Intellectual Property & Patents",
		      href:""
	      }
      ]
    },
    {
      title: 'Information Technology',
      list: [
	      {
		      title:"Accounts & Passwords",
		      href:""
	      },
	      {
		      title:"E-mail",
		      href:""
	      },
	      {
		      title:"Connecting to the Internet",
		      href:""
	      },
	      {
		      title:"Phone & Voicemail",
		      href:""
	      },
	      {
		      title:"Software",
		      href:""
	      },
	      {
		      title:"Campus Computer Labs",
		      href:""
	      },
	      {
		      title:"Storage Services",
		      href:""
	      },
	      {
		      title:"Faculty & Staff Services",
		      href:""
	      },
	      {
		      title:"Training",
		      href:""
	      },
	      {
		      title:"Help & Support",
		      href:""
	      }
	      
      ]
    },
    {
      title: 'Facilities & Operations',
      list: [
	      {
		      title:"Bookstore",
		      href:""
	      },
	      {
		      title:"Parking",
		      href:""
	      },
	      {
		      title:"Conference Services",
		      href:""
	      },
	      {
		      title:"Maintenance",
		      href:""
	      },
	      {
		      title:"Mail Center",
		      href:""
	      },
	      {
		      title:"Photo IDs & Security Systems",
		      href:""
	      }
      ]
    },
    {
      title: 'Human Resources',
      list: [
	      {
		      title:"For Prospective Employees",
		      href:""
	      },
	      {
		      title:"For Employees",
		      href:""
	      },
	      {
		      title:"For Supervisors",
		      href:""
	      }
	      
      ]
    },
     {
      title: 'University Finances',
      list: [
	      {
		      title:"Accounts Payable",
		      href:""
	      },
	      {
		      title:"Budgeting & Financial Planning",
		      href:""
	      },
	      {
		      title:"General Accounting",
		      href:""
	      },
	      {
		      title:"Payroll",
		      href:""
	      },
	      {
		      title:"Purchasing",
		      href:""
	      },
	      {
		      title:"Risk Management",
		      href:""
	      }
	      
      ]
    },
    {
      title: 'Strategic Communications',
      list: [
	      {
		      title:"Advertising",
		      href:""
	      },
	      {
		      title:"University Publications",
		      href:""
	      },
	      {
		      title:"Public Relations",
		      href:""
	      },
	      {
		      title:"Social & Digital Media",
		      href:""
	      },
	      {
		      title:"Web Services",
		      href:""
	      }
      ]
    },
    {
      title: 'Legal Affairs',
      list: [
	      {
		      title:"General Counsel",
		      href:""
	      },
	      {
		      title:"Intellectual Property & Patents",
		      href:""
	      },
	      {
		      title:"Public Records Requests",
		      href:""
	      },
	      {
		      title:"Ethics",
		      href:""
	      }
	    ]
    },
    {
      title: 'Alumni',
      list: [
	      {
		      title:"Events for Alumni",
		      href:""
	      },
	      {
		      title:"Benefits & Discounts",
		      href:""
	      },
	      {
		      title:"Alumni Association",
		      href:""
	      },
	      {
		      title:"Career Services for Alumni",
		      href:""
	      },
	      {
		      title:"Transcript Requests",
		      href:""
	      },
	      {
		      title:"Giving to NJIT",
		      href:""
	      }
	    ]
    }
  ];
 Drupal.settings.NjitNavigatorMenus['navigator-facstaff'] = [
    {
      title: 'Incoming Students',
      list: [
        {
          title: 'For Freshmen',
          list: [{
          title: 'For Transfer Students',
          list: []
        },
        {
          title: 'Placement Testing',
          list: []
        }]
        },
        {
          title: 'Placement Testing',
          list: []
        },
        {
          title: 'Summer Orientation',
          list: []
        },
        {
          title: 'NJIT Experience Day',
          list: []
        },
        {
          title: 'Getting to Campus',
          list: []
        },
        {
          title: 'Academic Support Programs',
          list: []
        }
      ]
    }, {
      title: 'Student Finances',
      list: [
        {
          title: 'Bills, Payments and Refunds',
          list: []
        },
        {
          title: 'Financial Aid',
          list: [
            {
              title: 'Dates & Deadlines',
              href: 'http://www.google.com'
            },
            {
              title: 'Tuition & Costs',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Paying Your Bill',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Getting a Refund or Credit',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Student Health Insurance',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Online Self-Service How-Tos',
              href: 'http://www.google.com'                  
            },
            {
              title: '1098-T Forms',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Title IV Authorization',
              href: 'http://www.google.com'                  
            },
            {
              title: 'Contact Us',
              href: 'http://www.google.com'                  
            }
          ]
        },
        {
          title: 'Student Employment',
          list: []
        },
        {
          title: 'Military & Veteran Benefits',
          list: []
        }
      ]
    },
    {
      title: 'Academics',
      list: [
	      {
		      title:"Class Registration",
		      href:""
	      },
	      {
		      title:"Exam Schedules",
		      href:""
	      },
	      {
		      title:"Study Abroad",
		      href:""
	      },
	      {
		      title:"Academic Advising",
		      href:""
	      },
	      {
		      title:"Tutoring & Support",
		      href:""
	      },
	      {
		      title:"Assistance for Disabled Students",
		      href:""
	      },
	      {
		      title:"Graduation",
		      href:""
	      },
	      {
		      title:"Commencement",
		      href:""
	      },
	      {
		      title:"Pre-College Programs",
		      href:""
	      }
      ]
    },
    {
      title: 'Campus Life',
      list: [
	      {
		      title:"Campus Center",
		      href:""
	      },
	      {
		      title:"Housing & Residence Life",
		      href:""
	      },
	      {
		      title:"Dining Services",
		      href:""
	      },
	      {
		      title:"Activities & Organizations",
		      href:""
	      },
	      {
		      title:"Leadership Programs",
		      href:""
	      },
	      {
		      title:"Diversity Programs",
		      href:""
	      },
	      {
		      title:"Community Service Programs",
		      href:""
	      }
	      
      ]
    },
    {
      title: 'Health & Safety',
      list: [
	      {
		      title:"Student Health Services",
		      href:""
	      },
	      {
		      title:"Couseling & Psychological Services",
		      href:""
	      },
	      {
		      title:"Public Safety",
		      href:""
	      },
	      {
		      title:"Environmental Health & Safety",
		      href:""
	      },
	      {
		      title:"Title IX",
		      href:""
	      }
      ]
    },
    {
      title: 'Career Services',
      list: [
	      {
		      title:"Career Advising",
		      href:""
	      },
	      {
		      title:"Job Search Help",
		      href:""
	      },
	      {
		      title:"Co-ops & Internships",
		      href:""
	      },
	      {
		      title:"Job Listings",
		      href:""
	      },
	      {
		      title:"Career Fairs",
		      href:""
	      },
	      {
		      title:"Education & Workshops",
		      href:""
	      },
	      {
		      title:"On-Campus Interviews",
		      href:""
	      },
	      {
		      title:"Sponsorships & Partnerships",
		      href:""
	      }
      ]
    },
    {
      title: 'Research',
      list: [
	      {
		      title:"Funding Opportunities",
		      href:""
	      },
	      {
		      title:"Grant Management",
		      href:""
	      },
	      {
		      title:"Research Compliance",
		      href:""
	      },
	      {
		      title:"Intellectual Property & Patents",
		      href:""
	      }
      ]
    },
    {
      title: 'Information Technology',
      list: [
	      {
		      title:"Accounts & Passwords",
		      href:""
	      },
	      {
		      title:"E-mail",
		      href:""
	      },
	      {
		      title:"Connecting to the Internet",
		      href:""
	      },
	      {
		      title:"Phone & Voicemail",
		      href:""
	      },
	      {
		      title:"Software",
		      href:""
	      },
	      {
		      title:"Campus Computer Labs",
		      href:""
	      },
	      {
		      title:"Storage Services",
		      href:""
	      },
	      {
		      title:"Faculty & Staff Services",
		      href:""
	      },
	      {
		      title:"Training",
		      href:""
	      },
	      {
		      title:"Help & Support",
		      href:""
	      }
	      
      ]
    },
    {
      title: 'Facilities & Operations',
      list: [
	      {
		      title:"Bookstore",
		      href:""
	      },
	      {
		      title:"Parking",
		      href:""
	      },
	      {
		      title:"Conference Services",
		      href:""
	      },
	      {
		      title:"Maintenance",
		      href:""
	      },
	      {
		      title:"Mail Center",
		      href:""
	      },
	      {
		      title:"Photo IDs & Security Systems",
		      href:""
	      }
      ]
    },
    {
      title: 'Human Resources',
      list: [
	      {
		      title:"For Prospective Employees",
		      href:""
	      },
	      {
		      title:"For Employees",
		      href:""
	      },
	      {
		      title:"For Supervisors",
		      href:""
	      }
	      
      ]
    },
     {
      title: 'University Finances',
      list: [
	      {
		      title:"Accounts Payable",
		      href:""
	      },
	      {
		      title:"Budgeting & Financial Planning",
		      href:""
	      },
	      {
		      title:"General Accounting",
		      href:""
	      },
	      {
		      title:"Payroll",
		      href:""
	      },
	      {
		      title:"Purchasing",
		      href:""
	      },
	      {
		      title:"Risk Management",
		      href:""
	      }
	      
      ]
    },
    {
      title: 'Strategic Communications',
      list: [
	      {
		      title:"Advertising",
		      href:""
	      },
	      {
		      title:"University Publications",
		      href:""
	      },
	      {
		      title:"Public Relations",
		      href:""
	      },
	      {
		      title:"Social & Digital Media",
		      href:""
	      },
	      {
		      title:"Web Services",
		      href:""
	      }
      ]
    },
    {
      title: 'Legal Affairs',
      list: [
	      {
		      title:"General Counsel",
		      href:""
	      },
	      {
		      title:"Intellectual Property & Patents",
		      href:""
	      },
	      {
		      title:"Public Records Requests",
		      href:""
	      },
	      {
		      title:"Ethics",
		      href:""
	      }
	    ]
    },
    {
      title: 'Alumni',
      list: [
	      {
		      title:"Events for Alumni",
		      href:""
	      },
	      {
		      title:"Benefits & Discounts",
		      href:""
	      },
	      {
		      title:"Alumni Association",
		      href:""
	      },
	      {
		      title:"Career Services for Alumni",
		      href:""
	      },
	      {
		      title:"Transcript Requests",
		      href:""
	      },
	      {
		      title:"Giving to NJIT",
		      href:""
	      }
	    ]
    }
  ];

  Drupal.NjitNavigator = function(data) {

    /**
     * Helper function to generate a li  w/ title, url and associate data related to the item and the level.
    */
    function li(item, level) {
      return $('<li role="listitem"><a target="_blank" href="' + item.href +'" class="title" data-item-level="'+ level +'">' + item.title + '</div></li>')
        .data('item', item);
    }
    
    /**
     * Helper function to generate a ul w/ content and a class name.
     */
    function ul(el, className) {
      return $('<ul></ul>').append(el).addClass(className);
    }

    /**
     * Generate a list item element a recursive render and append the list.
     */
    function renderItem(item, recursive, level) {
       var itemElement = li(item, level);
    
       if(item.list && recursive) {
         var listElement = renderList(item.list, recursive, level + 1);
         itemElement.append(listElement).addClass('has-children');
       }
      
       return itemElement;
    }
     /**
     * Generate a list and each element.
     */
    function renderList(list, _recursive, _level) {
        var recursive = _recursive || false;
        var level = _level || 0;
    
        var items = list.map(function(item) {
            return renderItem(item, recursive, level);
        });
      
        return ul(items, 'level-' + level);
    }

     /**
     * Render the list, handle clicks to links, and insert in the DOM for desktop version.
     */
    this.desktop = function ($el) { 
        
      var $list = renderList(data);
      $el.find('[data-level=0]').html($list);
        
      $el.on('click', 'a', function(e) {
        
        var $link =  $(this);
        var level =  Number($link.attr('data-item-level'));
        var nextLevel = level + 1;
        var item = $link.parent().data('item');
        
        if(item.list) {
  
          var $lastContainer =  $el.find('> [data-level=2]');
          var $currentContainer = $el.find('> [data-level='+ level +']');
          var $nextContainer = $el.find('> [data-level='+ nextLevel +']');
          
          $lastContainer.html(''); // Clear last container.
          $currentContainer.find('a').removeClass('active');
          $link.addClass('active');
  
          var $list = renderList(item.list, false, nextLevel);
          $nextContainer.html($list);
          e.preventDefault();
        }
      });
      

      $el.find('> [data-level=0] li:first-child > a').trigger('click');
    
    }
    
    /**
     * Render the list, handle clicks to links, and insert in the DOM for mobile version.
     */
    this.mobile = function($el) {
      var $list = renderList(data, true);
      $el.html($list);
  
      $el.on('click', 'a', function(e) {
        
        var $link =  $(this);
        var $item  = $link.parent();
        
        if(!$item.hasClass('has-children'))  {
          return;
        }

        $item.parent().find('> li').removeClass('open');

        $item.toggleClass('open');
        e.preventDefault();
      });
    }
  }

  Drupal.behaviors.NjitNavigator = {
    attach: function (context, settings) {
      $('#closemobilenav').click(function() {
        jQuery('.mobile-nav.open .menu-toggle').trigger('click');
      });
      $('.navigator').once('navigator', function() {
          var mql = window.matchMedia('(max-width: 540px)');
          listenMedia(mql);
          mql.addListener(listenMedia); 
      });

      /**
       * Intialize, hide/show mobile/desktop version depending of the screen width.
       */
      function listenMedia(mql) {
	  	var currentNavigator=$('.navigator').attr('id');
        var $navigatorMobile = $('.navigator-mobile');
        var $navigatorDesktop = $('.navigator-desktop');
        var navigator = new Drupal.NjitNavigator(settings.NjitNavigatorMenus[currentNavigator]);

        if(mql.matches) {
          $navigatorMobile.once('navigator-mobile', function() {
            navigator.mobile($navigatorMobile);
          });
          $navigatorMobile.show();
          $navigatorDesktop.hide();
        }
        else {
          $navigatorDesktop.once('navigator-desktop', function() {
            navigator.desktop($navigatorDesktop);
          });
          $navigatorMobile.hide();
          $navigatorDesktop.show().css('display', 'flex');
        }
      }
    }
  }

})(Drupal, jQuery);

/**
 * Twitter Widget behaviour. 
 */

(function (Drupal, $, twttr) {
  "use strict";

  Drupal = Drupal || {};

  /**
   * Init Twitter Widget
   */
  function init () {
    var js, fjs = document.getElementsByTagName("script")[0],
      t = window.twttr || {};
    if (document.getElementById("twitter-wjs")) return t;
    js = document.createElement("script");
    js.id = "twitter-wjs";
    js.src = "https://platform.twitter.com/widgets.js";
    fjs.parentNode.insertBefore(js, fjs);
  }

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.twitterWidget.attach}}
   */

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

      jQuery('body').once('twitter', function() {

        init();

        /*** THIS FOR DEV ONLY *** 
        * As bricks are loaded asyncronus, twttr.widgets.load after each w3c is loaded. */
      
        setTimeout(function() {
          window.twttr.widgets.load();
        }, 500);

      })

    }
  }

})(Drupal, jQuery);

/**
 * Facebook Widget behaviour. 
 */

(function (Drupal, $, twttr) {
  "use strict";

  Drupal = Drupal || {};
  
  /**
   * Init Facebook Widget
   */
  function init () {
    var js, fjs = document.getElementsByTagName('script')[0];
    if (document.getElementById('facebook-jssdk')) {return;}
    js = document.createElement('script'); js.id = 'facebook-jssdk';
    js.src = '//connect.facebook.net/en_US/sdk.js';
    fjs.parentNode.insertBefore(js, fjs);
  }

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.facebookWidget.attach}}
   */

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

      jQuery('body').once('facebook', function() {

        window.fbAsyncInit = function() {

          setTimeout(function() {
            FB.init({
              xfbml      : true,
              version    : 'v2.11'
            });
          }, 500);
        };

        init();



      })

    }
  }

})(Drupal, jQuery);

/**
 * Ellipsis behaviour.
 */

(function (Drupal, $) {
  "use strict";

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.ellipsis.attach}}
   */
  Drupal.behaviors.ellipsis = {
    attach: function (context, settings) {
      $('[data-ellipsis]').once('ellipsis', function (e) {

        var transformDebounced = _.debounce(transform, 700);
        $(window).on('resize', transformDebounced);
        transform();
        
        function transform() {
          $('[data-ellipsis]').each(function() {
            var maxHeight = $(this).attr('data-ellipsis');
            if(!maxHeight) {
              throw new Error('[data-ellipsis] must have a value.')
            }
            $(this).shave(maxHeight);
          });
        }

      });
    }
  }
  
})(Drupal, jQuery);

/**
 * Sticky behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Drupal = Drupal || {};

  Formstone.NoConflict();
  
  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.sticky.attach}}
   */
  Drupal.behaviors.sticky = {
    attach: function (context, settings) {
      $('[data-sticky]').once('sticky', function (e) {
        $('[data-sticky]').fsSticky();
      });
    }
  }

})(Drupal, jQuery);

/**
 * Scrollspy behaviour.
 */

(function (Drupal, $, gumshoe) {
  "use strict";

  Drupal = Drupal || {};

  Formstone.NoConflict();
  
  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.scrollspy.attach}}
   */
  Drupal.behaviors.scrollspy = {
    attach: function (context, settings) {
      $('[data-scrollspy]').once('gumshoe', function (e) {
        gumshoe.init({
          selector: '[data-scrollspy] a',
          container: window,
          offset: $('[data-scrollspy]').attr('data-scrollspy-container-offset') || 0,
        });
      });
    }
  }

})(Drupal, jQuery, gumshoe);

/**
 * Home page hero behaviour.
 */


(function (Drupal, $) {
  "use strict";


  Drupal.NjitHomePageHero = function($container, categories) {
    var drupalDefaultCat = 'default';
    var defaultCategory = getCategory(drupalDefaultCat);

    /**
     * Calculate the position and add the height.
     */

    function adjustNavPosition($container) {
      var $headerContainer = $('div.main-header-container');
      var headerOffset = $headerContainer.height() + $headerContainer.position().top;
      $container.find('.majors-navigation-container').css('top', headerOffset);
    }

    /**
     * Calculate the position and add the height.
     */

    function getBottomOffset($container) {
      var offset = $container.offset();
      var height = $container.height();
      var headerHeight = 144;
      var marginBefore = 70;
      return offset.top + height - headerHeight - marginBefore;
    }

    /**
     * change the content, if the major is unselected, change the content to the default category.
     */

    function slide(event) {
      if($(this).hasClass('active')) {
        changeContent($(this).data('category'));
      }else{ 
        changeContent(defaultCategory);
      }
    }
    
    /**
     * Change dynamically the content of the brick.
    */

    function machineName(text) {
      return text.replace(/[^a-z0-9]/gi, '-').toLowerCase().replace('--', '');
    }

    function changeContent(category) {

      $container.find('.title').text(category.title);
      $container.find('.js-href').attr('href', '//news.njit.edu/'+category.href);
      $container.find('.picture').attr('src', category.media.src);
      $container.find('.picture').attr('alt', category.media.alt);
      if(category.media.type === 'video') {
        $container.find('.video-controls-overlay').fadeIn(400);
        $container.find('.video-controls-overlay .label').text(category.media.label);
        
         $('#homepage-hero-video-embed-close').click(function(event){
            $('#homepage-hero-video').fadeOut(400, function() {
              $('#homepage-hero-video-wrapper').empty();  
            });
            event.stopPropagation();
            event.preventDefault();
         });
        
        $container.find('.video-controls-overlay').click(function(event){
          var htmlString = '<iframe width="854" height="480" frameborder="0" allowfullscreen="allowfullscreen" src="https://www.youtube.com/embed/'+category.media.yt_video_id+'?autoplay=1&amp;start=0&amp;rel=0&amp;enablejsapi=1"></iframe>';
          $('#homepage-hero-video-wrapper').html(htmlString);
          $('#homepage-hero-video').fadeIn();
          event.stopPropagation();
          event.preventDefault();
        });
                
      }else {
        $container.find('.video-controls-overlay').fadeOut(400);
        $('#homepage-hero-video-embed-close').off();
        $container.find('.video-controls-overlay').off();
      }

      //The hide and show of rows
      $('.homepage-image-gallery').each(function() { 
        $(this).removeClass('show-brick-row');
      });
      $('.homepage-testimonials').each(function() { 
        $(this).removeClass('show-brick-row');
      });
      $('.homepage-stats-row').each(function() { 
        $(this).removeClass('show-brick-row');
      });
      if(machineName(category.major) == 'default'){
        $('.general-gallery').addClass('show-brick-row');
        $('.general-testimonials').addClass('show-brick-row');
        $('.general-stats').addClass('show-brick-row');
      } else{
        $('.'+machineName(category.major)+'-gallery').addClass('show-brick-row');
        $('.'+machineName(category.major)+'-testimonials').addClass('show-brick-row');
        $('.'+machineName(category.major)+'-stats').addClass('show-brick-row');
      }
    
      if($.trim(Drupal.settings.degreeFinderUrls[category.major]) !== '' && typeof Drupal.settings.degreeFinderUrls[category.major] !== 'undefined' && category.major != 'default'){
        $('#explore-degrees-and-majors').attr('href', Drupal.settings.degreeFinderUrls[category.major]);
      } else {
        $('#explore-degrees-and-majors').attr('href', Drupal.settings.njitSearchDegreeFinder.degreeFinderPath);
      }

    }
  
    /**
     * Generate a a button given a className and event click, attaching corresponding category.
    */
    
    function buttonGenerator(category, className, onClick) {
      if(typeof Drupal.settings.homePageHeroDefaultCategory !== 'undefined') {
        if(typeof Drupal.settings.homePageHeroDefaultCategory.category !== 'undefined') {
          var theDrupalDefaultCat = Drupal.settings.homePageHeroDefaultCategory.category;
          
          if(theDrupalDefaultCat == category.major) {
            className = className+' active';
          }
        }
      }
      
      return $('<a href="javascript:void(0)">' + category.major + '</a>')
        .addClass(className)
        .attr('data-major', category.major)
        .attr('role', 'listitem')
        .attr('aria-label', 'Category Nav')
        .data('category', category)
        .on('click', function (evt) {
          
          $container.find('.active').not(this).removeClass('active');
          
          if($(this).hasClass('active')) {
            $container.find('[data-major="' + category.major + '"]').removeClass('active');
            
          }else {
            $container.find('[data-major="' + category.major + '"]').addClass('active');
            
          }

          evt.preventDefault();
          
        })
        .on('click', onClick);
    }
  
    /**
     * Generate a button for the top navigation.
    */

    function buttonNavigation(category) {
      return buttonGenerator(category, 'button button--navigation', slide);
    }
  
    /**
     * Generate a button for the mobile navigation.
    */
    function buttonMobileNavigation(category) {
      return buttonGenerator(category, 'link', slide);
    }
    
    /**
     * Generate a button for the navigation inside the content.
    */

    function buttonContent(category) {
      return buttonGenerator(category, 'button button--content', slide);
    }
  
    /**
     * Generate a list item element a recursive render and append the list.
    */

    function navigationGenerator(button) {
      return categories.map(function(category) {
        
        if(category.major === 'default') {
          return;
        }

        return button(category);
      });
    }
  
    /**
     * Get category if exists.
    */

    function getCategory(major) {
      var matches = categories.filter(function(category) {
        return category.major === major;
      });
  
      if(matches && matches.length) {
        return matches[0];
      }
    }
    
    /**
    * Render the navigation given a navigations object where key is the container and Button Generator is the value 
    */

    function renderNavigations(navigations) {
      Object.keys(navigations).forEach(function(navigation) {
        var $nav = $container.find(navigation);
        var $buttons = navigationGenerator(navigations[navigation]);
        $nav.append($buttons);
      });
    }

    var mqlDesktop = window.matchMedia('(min-width: 992px)');
    var isDesktop  = mqlDesktop.matches;

    mqlDesktop.addListener(function(mql) {
      isDesktop  = mql.matches;
      if(!isDesktop) {
        $($container).find('.majors-navigation-container').removeAttr("style");
      }
    });

    /**
     * Show navigation fade in the navigator when the scroll position is after the bottom offset of the container.
    */

    function showNavigation() {
      var end = getBottomOffset($($container));
      var scrollY = $(document).scrollTop();
      
      if(!isDesktop) {
        return;
      }
      adjustNavPosition($container);

      if(scrollY > end)  {
        $($container).find('.majors-navigation-container').fadeIn(200);
      }else {
        $($container).find('.majors-navigation-container').fadeOut(200);
      }
    }

    function resetFade() {
      $($container).find('.majors-mobile');
    }

    var navigations = {
      '.majors-navigation': buttonNavigation,
      '.majors-mobile-navigation': buttonMobileNavigation,
      '.majors': buttonContent
    }

    renderNavigations(navigations);
    if(typeof Drupal.settings.homePageHeroDefaultCategory !== 'undefined') {
      if(typeof Drupal.settings.homePageHeroDefaultCategory.category !== 'undefined') {
        var theDrupalDefaultCat = Drupal.settings.homePageHeroDefaultCategory.category;
        if(theDrupalDefaultCat == 'General') {
          theDrupalDefaultCat = 'default';
        }
        changeContent(getCategory(theDrupalDefaultCat));
      }
    }
    
    var showNavigationransformDebounced = _.throttle(showNavigation, 50);
    $(window).scroll(showNavigationransformDebounced);

    var resetFadeDebounced = _.throttle(resetFade, 50);
    $(window).resize(resetFadeDebounced);

    $($container).find('.majors-navigation-container').fadeOut(0);
    
  }


  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.close.attach}}
   */
  Drupal.behaviors.NjitHomePageHero = {
    attach: function (context, settings) {

    $('.home-page-hero').once('homePageHero', function() {
      var homePageHero = Drupal.NjitHomePageHero($('.home-page-hero'), Drupal.settings.homepageHeroData);
    });

    }
  }

})(Drupal, jQuery);

/**
 * NjitCollapse behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Drupal = Drupal || {};

  Drupal.NjitCollapse = function(trigger) {
      trigger.find('[data-collapsible-toggle]').on('click', function(e) {
        var parent = $(this).parent();
        if(parent.hasClass('open')) {
          parent.removeClass('open');
        } else {
          parent.addClass('open');
        }
        e.preventDefault();
      });
  }

  Drupal.behaviors.NjitCollapse = {
    attach: function (context, settings) {
      $('[data-collapsible]').once('collapse', function() {
        var collapse = new Drupal.NjitCollapse($(this));
      });
    }
  }

})(Drupal, jQuery);

/**
 * NjitSteppedContent behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Drupal = Drupal || {};

  Drupal.settings = Drupal.settings || {};

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.NjitSteppedContent.attach}}
   */
  Drupal.behaviors.NjitSteppedContent = {
    attach: function (context, settings) {
      // Copy the HTML from tab content to tab nav for mobile display purpose.
      var steppedContent = $('.stepped-content');
      if(steppedContent.attr('data-processed')!="true"){ 
      $('.tab-contents .tab-content', steppedContent).each(function() {
        var tabName = $(this).attr('rel');
        var tabHtml = $(this).html();
        $('.tab-nav ul li[data-target="' + tabName + '"]')
          .append('<div class="tab-contents"><div class="tab-content clearfix">' + tabHtml + '</div></div>');
      });
      }
      steppedContent.attr('data-processed',"true");
    }
  };
})(Drupal, jQuery);
/**
 * local-navigation behaviour. (hide on mobile if no child pages)
 */

(function (Drupal, $) {
  "use strict";

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.localnavigation.attach}}
   */
  Drupal.behaviors.localnavigation = {
    attach: function (context, settings) {
      $('.local-navigation .menu .active').once('local-navigation', function (e) {

        var transformDebounced = _.debounce(transform, 700);
        $(window).on('resize', transformDebounced);
        transform();

        function transform() {
          if (window.matchMedia("(min-width: 992px)").matches) {
            if (!$('.local-navigation .menu .active .menu--submenu').length >= 1) {
              $('.local-navigation [data-collapsible-toggle]').hide();
            }
          }
          else {
            $('.local-navigation [data-collapsible-toggle]').not(":visible").show();
          }
        }

      });
    }
  }

})(Drupal, jQuery);

/**
 * NjitSearch behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Drupal = Drupal || {};

  Drupal.settings = Drupal.settings || {};

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.NjitSearch.attach}}
   */
  Drupal.behaviors.NjitSearch = {
    attach: function (context, settings) {
      var $searchModal = $('.search-modal');

      $('.search-toggle, .search-form #edit-submit, .search-form #edit-keyword').on('click', function () {
        $searchModal.show();
        $('html, body').addClass('lightbox-no-scroll');
        // Focus the mouse in the keywords input.
        $('input[name="as_q"]', $searchModal).focus();
        return false;
      });

      $('.close-btn', $searchModal).on('click', function() {
        $('html, body').removeClass('lightbox-no-scroll');
        $('input[name="as_q"]').val('');
        $searchModal.hide();
        $('input[name="as_q"]', $searchModal).trigger('keyup');
      });

      $('input[name="as_q"]', $searchModal).keyup(function() {
        if ($(this).val() === '') {
          $('.search-popular', $searchModal).show();
          $('.search-results', $searchModal).hide();
        }
        else {
          $('.search-popular', $searchModal).hide();
          $('.search-results', $searchModal).show();
        }
      });
    }
  };
})(Drupal, jQuery);

/**
 * NjitSearch behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Drupal = Drupal || {};

  Drupal.settings = Drupal.settings || {};

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.NjitPrimaryTable.attach}}
   */
  Drupal.behaviors.NjitPrimaryTable = {
    attach: function (context, settings) {
      // For mobile.
      var $primaryTable = $('.primary-table .mobile');
      $('button.more-info-button', $primaryTable).on('click', function (e) {
        var $curRow = $(this).closest('div.table.actions');
        var $moreInfoRow = $curRow.next().find('.more-info-row');

        if ($(this).hasClass('closed')) {
          $(this).removeClass('closed').addClass('opened');
          $curRow.removeClass('closed').addClass('opened');
          $moreInfoRow.removeClass('closed').addClass('opened');
        }
        else {
          $(this).removeClass('opened').addClass('closed');
          $curRow.removeClass('opened').addClass('closed');
          $moreInfoRow.removeClass('opened').addClass('closed');
        }
      });

      // For desktop.
      var $primaryTable = $('.primary-table .desktop');
      $('button.more-info-button', $primaryTable).on('click', function (e) {
        var $curRow = $(this).closest('tr');
        var $moreInfoRow = $curRow.next();

        if ($(this).hasClass('closed')) {
          $(this).removeClass('closed').addClass('opened');
          $curRow.removeClass('closed').addClass('opened');
          $moreInfoRow.removeClass('closed').addClass('opened');
        }
        else {
          $(this).removeClass('opened').addClass('closed');
          $curRow.removeClass('opened').addClass('closed');
          $moreInfoRow.removeClass('opened').addClass('closed');
        }
      });
    }
  };
})(Drupal, jQuery);

/**
 * NjitProfileOverlay behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Drupal = Drupal || {};

  Drupal.settings = Drupal.settings || {};

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.NjitProfileOverlay.attach}}
   */
  Drupal.behaviors.NjitProfileOverlay = {
    attach: function (context, settings) {
      $(".colorbox-profile-overlay").colorbox({
        fixed: false,
        scrolling: true,
        overlayClose: true,
        escKey: true,
        inline: true,
        width: '1100px',
        height: '960px',
        top: '129px',
        className: 'colorbox-njit',
        onOpen: function() {
          $(window).on('update.tabs', function() {
            $.colorbox.resize();
          });
        },
        onComplete: function() {
          Drupal.attachBehaviors(Drupal.NjitTabbedContent);
        },
        onClosed: function() {

        }
      });
    }
  };
})(Drupal, jQuery);

/* just a custom js file misc */

jQuery(window).on('beforeunload', function(){
  jQuery(window).scrollTop(0);
});
/**
 * Close behaviour.
 */

(function (Drupal, $) {
  "use strict";

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.sitealert.attach}}
   */
  Drupal.behaviors.sitealert = {
    attach: function (context, settings) {
      $('.alert-level-site').once('alert', function () {
        var throttledPageAlert = _.throttle(Drupal.showPageAlert, 200);
        Drupal.showPageAlert();

        $(window).on('resize', function () {
          throttledPageAlert();
        });
      });
    }
  };

  /**
   * Shows Site level alert and adjusts header components to fit it
   */
  Drupal.showPageAlert = function () {
    var padding = $('.alert-level-site').css('height', 'auto').outerHeight();
    $('body > div.wrapper').css('padding-top', padding);
    $('.main-header-container').css('top', padding);
  };

})(Drupal, jQuery);

/**
 * NjitFindYourAdmissionsCounselor behaviour.
 */

(function (Drupal, $) {
  "use strict";

  Drupal = Drupal || {};

  Drupal.settings = Drupal.settings || {};

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.NjitFindYourAdmissionsCounselor.attach}}
   */
  Drupal.behaviors.NjitFindYourAdmissionsCounselor = {
    attach: function (context, settings) {
      ////////////////////////////////////////////////////////
      // Form filter events.
      ////////////////////////////////////////////////////////

      var $modal = $('.modal-your-admissions-counselor');
      var $fyacStudent = $('select[name="fyac-student"]', $modal);
      var $fyacCollege = $('select[name="fyac-college"]', $modal);
      var $fyacState = $('select[name="fyac-state"]', $modal);
      var $fyacCounty = $('select[name="fyac-county"]', $modal);

      populaceForm();
      $($fyacStudent).change(function() {
        // Reset values.
        $fyacCollege.val('').trigger("change");
        $fyacState.val('').trigger("change");
        $fyacCounty.val('').trigger("change");
        // Re-populace the form.
        populaceForm();
      });
      $($fyacCollege).change(function() {
        $fyacState.val('').trigger("change");
        $fyacCounty.val('').trigger("change");
        populaceForm();
      });
      $($fyacState).change(function() {
        $fyacCounty.val('').trigger("change");
        populaceForm();
      });
      $($fyacCounty).change(function() {
        populaceForm();
      });

      function populaceForm() {
        var fyacStudent = $fyacStudent.val();
        var fyacCollege = $fyacCollege.val();
        var fyacState = $fyacState.val();
        var fyacCounty = $fyacCounty.val();

        $('.item-college', $modal).hide();
        $('.item-state', $modal).hide();
        $('.item-county', $modal).hide();

        // Show/hide drop-downs.
        switch (fyacStudent) {
          case 'undergraduate':
            $('.item-state', $modal).show();
            break;
          case 'graduate':
            $('.item-college', $modal).show();
            break;
          case 'transfer':
          default:
            break;
        }

        switch (fyacState) {
          case 'ny':
          case 'nj':
          case 'pa':
            $('.item-county', $modal).show();
            break;
          default:
            break;
        }

        // Disable/Enable the button.
        var flag = false;
        switch (fyacStudent) {
          case 'undergraduate':
            if (fyacState !== '') {
              if (fyacState === 'ny' || fyacState === 'nj' || fyacState === 'pa') {
                if (fyacCounty !== '') {
                  flag = true;
                }
              }
              else {
                flag = true;
              }
            }
            break;
          case 'graduate':
            if (fyacCollege !== '') {
              flag = true;
            }
            break;
          case 'transfer':
            flag = true;
            break;

          default:
            break;
        }
        if (flag) {
          $('button.find', $modal).removeAttr('disabled');
          $('button.find', $modal).on('click', function() {
            $('.step-finish', $modal).removeClass('disabled').click();
          });
        }
        else {
          $('button.find', $modal).attr('disabled', 'disabled');
        }

        // Resize colorbox.
        $.colorbox.resize();
      }

      ////////////////////////////////////////////////////////
      // Step navigation events.
      ////////////////////////////////////////////////////////

      $('ul.form-progress-nav li', $modal).on('click', function () {
        if (!$(this).hasClass('disabled')) {
          $('ul.form-progress-nav li', $modal).each(function () {
            $(this).removeClass('active');
          });
          $(this).addClass('active');

          if ($(this).hasClass('step-about-you')) {
            $('.section-about-you', $modal).show();
            $('.section-finish', $modal).hide();
            $('.step-finish', $modal).addClass('disabled');

            //$fyacStudent.val('').trigger("change");
            //$fyacCollege.val('').trigger("change");
            //$fyacState.val('').trigger("change");
            //$fyacCounty.val('').trigger("change");
          }
          else {
            $('.section-about-you', $modal).hide();
            $('.section-finish', $modal).show();
          }
        }
        $.colorbox.resize();
      });

      ////////////////////////////////////////////////////////
      // Find button events.
      ////////////////////////////////////////////////////////

      $('button.find', $modal).on('click', function() {
        //Drupal.attachBehaviors(Drupal.NjitTabbedContent);
      });

      ////////////////////////////////////////////////////////
      // Start Over button events.
      ////////////////////////////////////////////////////////

      $('.step-back', $modal).on('click', function () {
        // Reset values.
        //$fyacStudent.val('').trigger("change");
        //$fyacCollege.val('').trigger("change");
        //$fyacState.val('').trigger("change");
        //$fyacCounty.val('').trigger("change");

        $('.step-about-you', $modal).click();
        $.colorbox.resize();
      });

      ////////////////////////////////////////////////////////
      // Colorbox.
      ////////////////////////////////////////////////////////

      $(".button-your-admissions-counselor").colorbox({
        fixed: false,
        scrolling: true,
        overlayClose: false,
        escKey: false,
        inline: true,
        width: '1097px',
        height: '100%',
        top: '129px',
        className: 'colorbox-njit',
        onOpen: function() {

        },
        onComplete: function() {
          //Drupal.attachBehaviors(Drupal.NjitTabbedContent);
        },
        onClosed: function() {
          // Reset values.
          $fyacStudent.val('').trigger("change");
          $fyacCollege.val('').trigger("change");
          $fyacState.val('').trigger("change");
          $fyacCounty.val('').trigger("change");
          // Go back to the step 1.
          $('.step-about-you', $modal).click();
        }
      });
    }
  };
})(Drupal, jQuery);

/**
 * Embedded video controller plugin for jQuery
 * Implements easy controls for embedded vimeo and youtube videos
 *
 * @author antroxim@gmail.com
 */

(function ($) {
  'use strict';


}(jQuery));


(function (Drupal, $) {
  "use strict";

  Drupal = Drupal || {};

  Drupal.behaviors.videoController = {
    attach: function (context, settings) {
      var youtubeApi = false;
      var vimeoApi = false;

      $('iframe').each(function (i) {
        var src = $(this).attr('src');

        if (typeof src !== typeof undefined && src !== false) {
          // Checking if any youtube players with JSapi enabled
          if (src.includes("youtube.com") && src.includes("enablejsapi=1")) {
            $(this).attr('id', '#youtube-player-' + i).addClass('youtube-iframe-api');
            youtubeApi = true;
          }
          // Checking if any vimeo embeds
          if (src.includes("vimeo.com")) {
            $(this).attr('id', 'id', '#vimeo-player-' + i).addClass('vimeo-iframe-api');
            vimeoApi = true;
          }
        }

      });

      // Getting Youtube / Vimeo JS iframe API
      if (!window.YT && youtubeApi) {
        $.getScript('https://www.youtube.com/iframe_api');
      }
      if (!window.Vimeo && vimeoApi) {
        $.getScript('https://player.vimeo.com/api/player.js', function () {
          onVimeoPlayerAPIReady();
        });
      }

      // Vimeo API ready
      function onVimeoPlayerAPIReady() {
        $('iframe.vimeo-iframe-api').each(function (i) {
          /* global Vimeo */
          $(this).data('player', {
            type: 'vimeo',
            player: new Vimeo.Player(this)
          });
          assignControlls($(this));
        });
      }

      // Youtube API ready callback
      window.onYouTubePlayerAPIReady = function () {
        $('iframe.youtube-iframe-api').each(function () {
          /* global YT */
          var id = $(this).attr('id');
          var theIframe = $(this);
          $(this).data('player', {
            type: 'youtube', player: new YT.Player(id, {
              events: {
                onReady:  function() { youtubePlayerReady(theIframe); },
                onStateChange: youtubePlayerStateChange
              }
            })
          });
        });
      };

      // Youtube player ready callback
      function youtubePlayerReady(event) {
        var iframe = $(event);
        assignControlls(iframe);
      }

      // Passing events to iframe object
      function youtubePlayerStateChange(event) {
        var iframe = $(event.target.a);
        switch (event.data) {
          case 0:
            iframe.trigger('onStop');
            break;
          case 1:
            iframe.trigger('onPlay');
            break;
          case 2:
            iframe.trigger('onPause');
            break;

          default:
            break;
        }
      }

      // Assigning controlls to player to use them
      function assignControlls(iframe) {
        var player = iframe.data('player');

        switch (player.type) {
          case 'vimeo':
            // Assigning player controls
            player.controls = {
              play: function () {
                player.player.play();
              },
              pause: function () {
                player.player.pause();
              },
              stop: function () {
                player.player.unload();
              }
            };

            // Assigning Vimeo player events
            player.player.on('play', function () {
              iframe.trigger('onPlay');
            });
            player.player.on('pause', function () {
              iframe.trigger('onPause');
            });
            player.player.on('ended', function () {
              iframe.trigger('onStop');
            });

            break;

          case 'youtube':
            player.controls = {
              play: function () {
                player.player.playVideo();
              },
              pause: function () {
                player.player.pauseVideo();
              },
              stop: function () {
                player.player.stopVideo();
              }
            };
            break;

          default:
            break;
        }
      }
    }
  };
})(Drupal, jQuery);

(function ($) {
  'use strict';


  var init = function (paragraph) {
    var $videoContainer = paragraph.find('.video');
    var $player = paragraph.find('iframe');
    var $cta = paragraph.find('.cta-block');
    $player.attr('allow', 'autoplay');
    if ($player.length) {
      //var $videoButton = paragraph.find('.video-controls-overlay a.play-video');
      var $videoButton = paragraph.find('.video-controls-overlay');
      var $closeBtn = paragraph.find('span.close');

      $player.on('onStop', function () {
        $videoContainer.fadeOut(600);
        paragraph.removeClass('playing');
      });


      $videoButton.on('click', function (e) {
        paragraph.addClass('playing');
        $videoContainer.delay(300).fadeIn(600, function () {
           $player.remove();
           $videoContainer.find('.video-embed-field-responsive-video').append($player.get(0).outerHTML);
           $player = paragraph.find('iframe');
        });
       // $player.data('player').controls.play();
        e.preventDefault();
      });

      $closeBtn.on('click', function () {
        //$player.data('player').controls.pause();
        paragraph.removeClass('playing');
        $videoContainer.fadeOut(600, function () {          
          //$player.data('player').controls.stop();
          $player.remove();
        });
      });
    }
  };

  Drupal.behaviors.initVideoPlayer = {
    attach: function (context) {
      $(context).find('.hero-option-1.video').once('video-formatter').each(function () {
        init($(this));
      });
    }
  };
}(jQuery));

/**
 * The degree finder behaviour.
 */

(function (Drupal, $) {
  "use strict";
  var vueJsRootSelector = '#degree-finder';
  var isInit = false;

  if ($(vueJsRootSelector).length > 0) {
    Drupal.degreeFinder = Drupal.degreeFinder || {};


    const eventChangeComparingList = new Vue();

    /**
     * The degree finder behaviour.
     *
     * @type {{attach: Drupal.behaviors.njitHeader.attach}}
     */
    Drupal.behaviors.degreeFinder = {

      attach: function (context, settings) {
        if(isInit) {
          return;
        }
        isInit = true;
        const $router_degree_finder_el = $('#router-degree-finder');
        const filterNames = ['accelerated_option', 'areas_of_study', 'college', 'degree_level', 'degree_offerings', 'department', 'searchText'];
                  
        // Init ES client.
        const esclient = new $.es.Client({
          hosts: Drupal.settings.njitSearchDegreeFinder.eshost
        });

        if ($router_degree_finder_el.length > 0) {
          $router_degree_finder_el.once("router_degree_finder_el", function () {
            // Register pager component.
            Vue.component('paginate', VuejsPaginate);

            /**

             * Construct the config object for the filters options.
             *
             * @param definition
             * @constructor
             */
            function FilterOptions(definition) {
              let defaultDef = {
                options: [],
                type: 'checkbox',
                value: '*',
                multiple: true,
                filterTooltip: {},
                tab: 'degree'
              };

              $.extend(this, defaultDef, definition);
            }

            const SORT_SIZE_INIT_PARAMS={
              sort: [
                    {"title.keyword": {order: 'asc'}},
                    "_score"
                  ],
              size: 15
            }
                  


            Drupal.vuedegreeFinder = Vue.component('vuedegreefinder', {

              data:  function () {
                return {
                  isHonors: false,
                  showMobilefilterNav: false,
                  seletedDegree: '',
                  toggleShowMoreDeptOptions: true,
                  isDeptFiltered: false,
                  formatLookupTable: {
                    'on-campus': 'On Campus',
                    'online': 'Online',
                    'offf-campus': 'Off Campus',
                    'off-campus': 'Off Campus'
                  },
                  isPrefetched: new Promise(function(resolve, reject) { }),
                  isBusy: true,
                  timerId: 0,
                  comparingListIds: [],
                  initRouteDone: false,
                  masterCollegeDeptTree: {},
                  esFrom: 0,
                  esSize: SORT_SIZE_INIT_PARAMS.size,
                  // Total number of results.
                  esTotal: 0,
                  // Total number of pages slitted by this.esSize.
                  esTotalPages: 0,
                  esSort: SORT_SIZE_INIT_PARAMS.sort,
                  viewMoreLinkText: 'Learn More',
                  filters: {
                    searchText: {
                      aggFilterName: 'text',
                      options: [],
                      value: '',
                      multiple: false,
                      type: 'textfield', //searchText
                      tab: 'all'
                    },
                    areas_of_study: new FilterOptions({
                      aggFilterName: 'areas_of_study_terms.keyword',
                      tab: 'major'
                    }),
                    degree_level: new FilterOptions({
                      aggFilterName: 'degree_level_terms.keyword'
                    }),
                    college: new FilterOptions({
                      aggFilterName: 'department_college_terms',
                      tab: 'all'
                    }),
                    department: new FilterOptions({
                      aggFilterName: 'department_terms'
                    }),
                    accelerated_option: new FilterOptions({
                      aggFilterName: 'accelerated_option_boolean', multiple: false, value: true
                    }),
                    degree_offerings: new FilterOptions({
                      aggFilterName: 'degree_offerings',
                      filterTooltip: {
                        "on-campus": "Classes will meet in a physical location with some optional online offerings",
                        "online": "100% of required classes can be taken online"
                      }
                    })
                  },
                  resultItems: []
                }
              },
              computed: {

                toUrlObjectFilters: function () {
                  const result = {};
                  for (let nameFilter in this.filters){
                    const listOption = this.filters[nameFilter].options.filter( option => option.checked ).map(option => option.value);

                    if (listOption.length > 0) {
                      result[nameFilter] = listOption;
                    }

                    if (this.filters[nameFilter].type === 'textfield'){
                      result[nameFilter] = {};
                      result[nameFilter].value = this.filters[nameFilter].value;
                    }
                  }

                  return result;
                }

              },

              watch: {

                tab: {
                  handler: function (tab, prev) {
                    let $this = this;
                    
                    $this.buildFacetsOptions($this)
                    .then(function(response) {
                      $this.seedDeptOptionList();
                      $this.esSort = SORT_SIZE_INIT_PARAMS.sort;
                      $this.esSize = SORT_SIZE_INIT_PARAMS.size;
                      $this.createUrls();
                    }, function(error) { 
                       alert(`Error: ${error}`)
                      
                    });
                  }
                },

                '$route' : {
                  handler: function (to, from) {
                    this.initRoute();
                  }
                },

                filters: {
                  handler: function (filters) {
                    if(typeof this.filters.searchText.value  !== 'undefined') { 
                      this.filters.searchText.value = this.filters.searchText.value.replace(/[^a-z0-9 ]/gi,'');
                    }
                    var cleanCurrent = _.pick(filters, filterNames);
                    if(typeof this.filtersCached == 'undefined') {
                      this.filtersCached = {};
                    }
                    var cleanOld = _.pick(this.filtersCached, filterNames);

 
                    this.filtersCached = _.clone(filters, true);
                    var currentTest = {}, oldTest = {};

                    _.each(filterNames, function(item, key) {
                      if(item != 'searchText'){ 
                        currentTest[item] = _.map(cleanCurrent[item].options, function(d,k){
                          return d.checked;
                        });

                        if(typeof cleanOld[item] == 'undefined') {
                          cleanOld[item] = [];
                        }
                        /*if(typeof cleanOld[item].options == 'undefined') {
                          cleanOld[item].options = [];
                        }*/
                        if(typeof cleanOld[item].options != 'undefined') {
                          oldTest[item] = _.map(cleanOld[item].options, function(d,k){
                            return d.checked;
                          });
                        }
                      }

                      if(item == 'searchText'){ 
                        currentTest[item] = cleanCurrent[item];
                        if(typeof cleanOld[item] == 'undefined') {
                          cleanOld[item] = '';
                        }
                        if(typeof cleanOld[item] != 'undefined') {
                          oldTest[item] = cleanOld[item];
                        }
                      }
                      
                    });


                    if(!_.isEqual(currentTest, oldTest)) {
                      
                      if(typeof this.xhrTimer != 'undefined') {
                        clearTimeout(this.xhrTimer);
                      }
                      this.createUrls();
                      this.xhrTimer = setTimeout(function () { 
                        this.esFrom = 0;
                        if($(window).width() < 768) {
                          this.showMobilefilterNav = false;
                        }
                        this.watchFilters(filters);
                        //this.filtersCached = filters;
                       // if(!_.isEqual(currentTest.college, oldTest.college)) {
                           this.seedDeptOptionList();
                       // }
                       //
                      }.bind(this), 500);
                      
                    }

                  },
                  deep: true,
                  immediate:true
                },
                comparingListIds: {
                  handler: function (comparingListIds) {
                    if(comparingListIds.length > 3){
                      comparingListIds.pop();
                      return;
                    }

                    eventChangeComparingList.$emit("comparingListIdsСhange", comparingListIds, this.tab);
                    this.createUrls();
                  }
                },
                esSize: {
                  handler: function () {
                    this.createUrls();
                    this.watchFilters(this.filters);
                  }
                },
                esSort: {
                  handler: function (sort) {
                    this.createUrls();
                    this.watchFilters(this.filters);
                  },
                  deep: true
                }
              },

              /**
               * Subscribe to "updated" event.
               */
              updated: function () {
                this.$nextTick(function () {
                  // TODO: Use fsEqualize elements.

                })
              },

              /**
               * Subscribe to "created" event
               */
              created: function () {
                let $this = this;
                $this.initGeneralRoute();//
                this.isPrefetched = new Promise(function(resolve, reject) { 
                  $this.buildFacetsOptions($this).then(function() {
                
                    $this.initRoute();
                    resolve();
                  });
                });
                
                /*this.buildFacetsOptions(this)
                .then(
                  response => { 
                    this.initRoute();
                  },
                  error => alert(`Error: ${error}`)
                );*/

                
                eventChangeComparingList.$on("clearComparingList", ()=>{
                  this.comparingListIds = [];
                });
                eventChangeComparingList.$on("deleteComparingList", (index)=>{
                  this.comparingListIds.splice(index, 1);
                });
              },


              methods: {
                clearAllFilters: function() {
                  var $this = this;
                  this.filters.searchText.value = ''
                  var lists = filterNames;
                  _.each(lists, function(item, key){
                    if(typeof $this.filters[item] != 'undefined') {
                      if($this.filters[item].options.length) {
                        _.each($this.filters[item].options, function(option, index){
                          option.checked = false;
                        });
                      }

                    }
                  })
                },
                getObjectDiff: function(obj1, obj2) {
                    if(typeof obj1 == 'undefined') {
                      return true;
                    }
                    const diff = Object.keys(obj1).reduce((result, key) => {
                        if (!obj2.hasOwnProperty(key)) {
                            result.push(key);
                        } else if (_.isEqual(obj1[key], obj2[key])) {
                            const resultKeyIndex = result.indexOf(key);
                            result.splice(resultKeyIndex, 1);
                        }
                        return result;
                    }, Object.keys(obj2));

                    if(diff.length) {
                      return true;
                    } else {
                      return false;
                    }
                },
                getDegreeFromMulti: function() {
                  return '-';
                },
                setDegreeToMulti: function(evt) {
                  var $this = this;
                  _.each($this.filters.degree_level.options, function(item, key){ 
                    item.checked = false;
                    if(event.target.value == item.title) {
                      item.checked = true;
                    }
                  });

                },
                createUrls: function () {
                  if ( !this.initRouteDone ) {
                    return;
                  }

                  const model = this;
                  
                  let pushUrls = function(){
                    var obj = {
                      //general: [model.esFrom, model.esSize, model.esTotal, model.esTotalPages, model.tab],
                      //filters: model.toUrlObjectFilters,
                      tab: model.tab,
                      //page: model.page,
                     // totalPages: model.esTotalPages,
                     // total: model.esTotal,
                     // size: model.esSize,
                     // from: model.esFrom,
                    //  sort: model.esSort[0]['title.keyword'].order,
                      items: model.comparingListIds
                    }

                    if(model.filters.searchText.value != '') {
                      obj.searchText = model.filters.searchText.value;
                    }
                    var lists = filterNames;
                    
                    _.each(lists, function(item, key){
                      if(typeof model.filters[item] != 'undefined') {
                        if(model.filters[item].options.length) {
                          var dataset = {};
                          _.each(model.filters[item].options, function(option, index){

                            if(typeof dataset[item] == 'undefined') {
                              dataset[item] = [];
                            }
                            if(option.checked) {
                              if(item == 'accelerated_option'){
                                dataset[item].push(option.checked);
                              } else {
                                dataset[item].push(option.value);  
                              }
                              
                            }
                            
                            
                          });

                          if(dataset[item].length) {
                            obj[item] = dataset[item].join(',');
                          }

                        }

                      }
                    });
                    if(model.tab == 'degree') {
                      delete obj['areas_of_study'];
                    } else {
                      delete obj['degree_level'];
                      delete obj['department'];
                      delete obj['accelerated_option'];
                      delete obj['degree_offerings'];
                    }

                    //let str = JSON.stringify(obj) // + `&sort=${JSON.stringify(this.esSort)}`;
                    router.push({ query: obj })
                    //model.$router.push(`/params/${encodeURI(str)}`);
                  };

                  clearTimeout(this.timerId); 
                  this.timerId = setTimeout(pushUrls, 500);
                },

                isActiveFilter: function (tabFilter) {
                  return (tabFilter === this.tab) || ( tabFilter === 'all');
                },


                initGeneralRoute: function () {
                  let params = this.$router.currentRoute.query;
                  this.filters.searchText.value = (params.searchText != '') ? params.searchText: ''; 
                  this.esSort[0]['title.keyword'].order = (params.sort) ? params.sort: 'asc';
                  this.seletedDegree = (params.degree_level) ? params.degree_level: '';
                  this.esFrom = params.from ? params.from: 0;
                  this.esSize = params.size ? params.size: 15;
                  this.page = params.page ? params.page: 1;
                  this.esTotal = params.total ? params.total: 0;
                  this.esTotalPages = params.totalPages ? params.totalPages: 0;
                  this.tab = params.tab ? params.tab: 'major';
                  return params;
                },

                /**
                 * Change object filters from Url.
                 *
                 * @param params
                 */
                initRoute: function () {
                  //const objectUrls = this.initGeneralRoute();
                  /*
                  if (objectUrls) {
                    for (let nameFilter in objectUrls.filters) {
                      const filter = this.filters[nameFilter];
                      filter.options.map( option => {
                        option.checked = objectUrls.filters[nameFilter].includes(option.value);
                      })

                       if (objectUrls.filters[nameFilter].value  && objectUrls.filters[nameFilter].value !== '*' &&
                            filter.value != objectUrls.filters[nameFilter].value){
                         filter.value = objectUrls.filters[nameFilter].value;
                       }
                    }

                    this.comparingListIds = objectUrls.items;
                  }*/

                  this.initRouteDone = true;
                },

                /**
                 * Check the URL for filters.
                 *
                 * Does the url string contain the option (optionKey) of the
                 * specified filter (nameFilter).
                 *
                 * @param params
                 * @param nameFilter
                 * @param optionKey
                 * @returns {boolean}
                 */
                isOptionRoute: function (params, nameFilter, optionKey) {
                  
                  if(typeof params[nameFilter] != 'undefined') {
                    if(nameFilter == 'accelerated_option'){
                      return true;
                    } else {
                      var checker = params[nameFilter].split(',');
                      if(checker.indexOf(optionKey) != -1) {
                        return true;
                      } else {
                        return false;
                      }
  
                    }
                    
                  } else {
                    return false;
                  }
                },

                /**
                 * Build the filter id with filter mane as prefix.
                 *
                 * @param prefix
                 * @param text
                 * @returns {string}
                 */
                buildFilterId: function (prefix, text) {
                  return prefix + '--' + text.replace(' ', '');
                },

                /**
                 * Pager click callback.
                 *
                 * @param data
                 */
                pagerClickCallback: function (data) {
                  //let obj = this.$router.currentRoute.query;
                  //obj.page = data;
                  this.page = data;

                  this.esFrom = data * this.esSize - this.esSize;
                  this.watchFilters(this.filters);
                                 
                  
                  //router.push({ query: obj })
                  //const $context = $(this.$el);
                  //$('html,body').animate({scrollTop: $('#degree-finder-results-list', $context).offset().top - 200}, 'slow');
                },

                /**
                 * Init pager for query.
                 *
                 * @param body
                 */
                initPager: function (body) {
                  //let obj = this.$router.currentRoute.query;
                  //this.page = obj.page;
                  this.esTotal = body.hits.total;
                  this.esTotalPages = Math.ceil(body.hits.total / this.esSize);
                },

                /**
                 * Helper function to check if value is in array.
                 *
                 * @param needle - item to search
                 * @param haystack - array
                 */
                inArray: function(needle, haystack) {
                  return haystack.includes(needle);
                },

                /**
                 * Helper function to check checkbox on container click.
                 *
                 * @param event
                 */
                addCompare: function (itemId,event) {
                  itemId = itemId.toString();
                  if (this.comparingListIds.includes(itemId)) {
                    const index = this.comparingListIds.indexOf(itemId);

                    if (index > -1) {
                      this.comparingListIds.splice(index, 1);
                    }
                  }
                  else {
                    if(this.comparingListIds.length == 3) {
                      this.comparingListIds.splice(2, 1);
                    } 
                    this.comparingListIds.push(itemId);
                    
                    
                  }
                  event.stopPropagation()
                },

                setBusy: function(flag) {
                  var timerAmt = 100;
                  if(!flag){
                    timerAmt = 500;
                  }
                  if(typeof this.isBusyTimer != 'undefined') {
                      clearTimeout(this.isBusyTimer);
                    }
                    this.isBusyTimer = setTimeout(function () { 
                      if(flag){
                        if(!this.isBusy) {
                          this.isBusy = flag;
                        }
                      } else {
                        if(this.isBusy) {
                          this.isBusy = flag;
                        }
                      }

                    }.bind(this), timerAmt);
                  
                },
                /**
                 * React on filters changes.
                 *
                 * @param filters
                 */
                watchFilters: function (filters) {
                  let model = this;
                  model.isHonors = false;
                  let esquery = this.buildFilterQuery(filters);
                  var $context = $(this.$el);
                  if(this.initialized) { 
                    $('html,body').animate({scrollTop: $('#degree-finder-results-list', $context).offset().top - 600}, 0);
                    
                  }
                  this.initialized = true;
                  esquery.body.sort = this.esSort;
                  model.setBusy(true);
                  return esclient.search(esquery).then(function (body) {
                    model.initPager(body);
                    let hits = body.hits.hits;
                    model.resultItems = [];

                    for (let i in hits) {
                      hits[i]._source.id = hits[i]._id;
                      model.resultItems.push(hits[i]._source);
                    }

                    model.setBusy(false);
                  
                  }, function (error) {
                    model.setBusy(false);
                    console.trace(error.message);
                  });
                },

                /**
                 * Central function to convert user input to ES filters.
                 *
                 * @param filters
                 * @returns {{index: string, type: string, body: *, from: number,
                 *   size: number}}
                 */
                buildFilterQuery: function (filters) {
                  let esbody = bodybuilder();

                  let esquery = {
                    index: Drupal.settings.njitSearchDegreeFinder.esindex,
                    type: this.tab,
                    body: esbody,
                    from: this.esFrom,
                    size: this.esSize
                  };

                  let model = this;
                  
                  for (let filterName in filters) {
                    if (filters.hasOwnProperty(filterName)) {
                      switch (filters[filterName].type) {
                        case 'textfield':
                          if(typeof filters[filterName].value  != 'undefined') { 
                            /*if (filters[filterName].value.length > 0) {
                              var querySplit = filters[filterName].value.split(' ');
                              _.each(querySplit, function(item, key) {
                                  esbody.query('wildcard', {'_all': '*'+$.trim(item)+'*'})
                              });
                            }*/
                            
                            esbody.query('bool', {
                               "should": [
                                 {
                                   "query_string": {
                                     "query": filters[filterName].value,
                                     "fields": [
                                        "title"
                                      ],
                                     "boost": 10 
                                   }
                                 },{
                                   "query_string": {
                                     "query": filters[filterName].value
                                   }
                                 },{
                                "nested": {
                                  "boost": 5 ,
                                  "path": "summary", 
                                  "query": {
                                    "bool": {
                                      "must": [ 
                                        {
                                          "match": {
                                            "summary.value": filters[filterName].value
                                          }
                                        }
                                      ]
                                    }
                                  }
                                }
                              }
                               ],
                              "minimum_should_match": 2
                            })
                            console.log('esbody', esbody.build());
                          }
                          break;
                        case 'select':
                          if (filters[filterName].value !== '*') {
                            esbody.filter('term', filterName, filters[filterName].value);
                          }
                          break;
                        case 'button':
                        case 'checkbox':
                          // The narrowing search must work as OR within specific
                          // filter and as AND between the filters.
                          let subfilter = {}, hasActiveSelection = false;
                          subfilter[filters[filterName].aggFilterName] = [];
                          // Extract the only checked filters.
                          for (let option in filters[filterName].options) {
                            if (filters[filterName].options[option].checked) {
                              subfilter[filters[filterName].aggFilterName].push(filters[filterName].options[option].value);
                              hasActiveSelection = true;
                            }
                          }

                          if (hasActiveSelection) {
                            esbody.andFilter('bool', function (q) {
                              for (let fieldName in subfilter) {
                                for (let i in subfilter[fieldName]) {
                                  if(filterName === 'accelerated_option') {
                                    q.orFilter('term', fieldName, true);
                                  } else if (fieldName === 'department_college_terms') {
                                    if(subfilter[fieldName][i] !== 'Albert Dorman Honors College') {
                                      q.orFilter('term', fieldName, subfilter[fieldName][i]);
                                    } else {
                                      model.isHonors = true;
                                    }
                                  }else {
                                    q.orFilter('term', fieldName, subfilter[fieldName][i]);
                                  }
                                }
                                return q;
                              }
                            });
                          }
                          break;
                      }
                    }
                  }

                  esquery.body = esbody.build();
                  return esquery;
                },

                /**
                 * Init results and filters data.
                 *
                 * TODO: merge that method with this.watchFilters(), and use
                 * watchFilters() every where.
                 * The difference between watchFilters() is that method builds
                 * the
                 * data for filters and they are stay the *  same when narrow the
                 * search.
                 * However, common use case for narrowed search is to remove
                 * options and filters which doesn't has the results or hide them
                 * from user.
                 */
                buildFacetsOptions: function (model) {
                  let $this = this;
                  return new Promise(function(resolve, reject) {
                    //
                    let filterNames = Object.keys(model.filters);
                    let esbody = bodybuilder().query('match_all');

                    for (let i in filterNames) {
                      esbody.aggregation('terms', model.filters[filterNames[i]].aggFilterName, filterNames[i]);
                    }

                    let build_q = esbody.build();

                    let esquery = {
                      index: Drupal.settings.njitSearchDegreeFinder.esindex,
                      type: model.tab,
                      body: build_q,
                      from: model.esFrom,
                      size: 0
                    };
                    $this.setBusy(true);
                    return esclient.search(esquery).then(function (body) {
                      // Build filters options, aka facets.
                      $this.setBusy(false);
                      $.each(model.filters, function (filterName, filterParams) {
                        if(filterName != 'college' && filterName != 'department') {
                          model.buildFilterOptions(filterName, body);
                          
                        }

                        if(filterName == 'college'){
                          model.getDepartments(body.aggregations.college, $this).then(function(data) {
                            data['Albert Dorman Honors College'] = {};
                            model.buildFilterOptions(filterName, data);
                            $this.masterCollegeDeptTree = data;
                            $this.seedDeptOptionList();
                            resolve();
                          });
                        }
                        
                      });
                    }, function (error) {
                      $this.setBusy(false);
                      console.trace(error.message);
                      reject(error);
                    });
                  });

                  
                },
                seedDeptOptionList: function() {
                  let params = this.$router.currentRoute.query;
                  let selectedColleges =  [];
                  if(typeof params.college != 'undefined'){
                    selectedColleges = params.college.split(',');
                  }
                    let $this = this;
                    let options = [];
                    _.each($this.masterCollegeDeptTree, function(item, key) { 
                      _.each(item, function(i, k) { 
                        var d = {
                          value: i.key,
                          title: i.key,
                          filtered: (selectedColleges.indexOf(key) != -1 || !selectedColleges.length) ? true: false,
                          checked: $this.isOptionRoute($this.$router.currentRoute.query, 'department', i.key) // false
                        };
                        options.push(d);
                      });
                      
                    });
                    options = _.sortBy(options, ['title']);
                    let options_filtered = _.filter(options, function(item) { 
                      return item.filtered;
                    });
                    let options_nofiltered = _.filter(options, function(item) { 
                      return !item.filtered;
                    });
                    if(options_nofiltered.length && options_filtered.length) {
                      $this.isDeptFiltered = true;
                    } else{
                      $this.isDeptFiltered = false;
                    }
                    $this.filters['department']['options'] = options_filtered.concat(options_nofiltered);

                },
                toggleMobileFilterNav: function() {
                  this.showMobilefilterNav = !this.showMobilefilterNav;
  
                },
                toggleShowMoreDept: function() {
                  this.toggleShowMoreDeptOptions = !this.toggleShowMoreDeptOptions;
                },
                getDepartments: function(collegeAggs, model) {
                  var promises = [];
                  collegeAggs.buckets.forEach(function(item, index) { 
                    let esbody = bodybuilder();
                    

                    //esbody.filter('term', 'department_college_terms', item.key);
                    esbody.andFilter('bool', function (q) {
                      q.orFilter('term', 'department_college_terms', item.key);
                      return q;
                    });

                    esbody.aggregation('terms', 'department_terms', 'department');
                    
                    var payload = {
                      index: Drupal.settings.njitSearchDegreeFinder.esindex,
                      type: model.tab,
                      body: esbody.build()
                    }
                    payload.body.sort = [
                      { 
                        'title.keyword': {
                          'order': 'asc'
                        }
                      }
                    ];
                    promises.push(esclient.search(payload));

                  });

                  return Promise.all(promises).then(function(values) { 
                    var colleges_and_departments = {};
                    collegeAggs.buckets.forEach(function(item, index) { 
                      colleges_and_departments[item.key] = values[index].aggregations.department.buckets;
                    });
                    return colleges_and_departments;
                  });

                  /*esbody.andFilter('bool', function (q) {
                    q.orFilter('term', 'college_department_term', 'klejsle');
                  });
                  
                  console.log
                  */
                },

                /*
                 * Helper function to build fiters options from ES client query.
                 *
                 * @param filterName
                 * @param rawBody
                 */
                buildFilterOptions: function (filterName, rawBody) {
                  let model = this;
                  let body = rawBody;
                  let options = [];
                  if(filterName != 'college' && filterName != 'department') {
                    if (typeof body.aggregations === 'object') {
                      if (body.aggregations.hasOwnProperty(filterName)) {
                        if(filterName === 'accelerated_option'){
                          const item = {
                            value: true,
                            title: filterName,
                            checked: this.isOptionRoute(this.$router.currentRoute.query, filterName, true) // false
                          };
                          options.push(item);
                        } else {
                          for (let i in body.aggregations[filterName].buckets) {
                            const key = body.aggregations[filterName].buckets[i].key;
                            const item = {
                              value: key,
                              title: key,
                              checked: this.isOptionRoute(this.$router.currentRoute.query, filterName, key) // false
                            };
                            options.push(item);
                          }
                          
                        }
                        this.filters[filterName]['options'] = options;
                      }
                    }
                  } else {
                    if(filterName == 'college') {
                      _.each(rawBody, function(item, key) {
                        var d = {
                          value: key,
                          title: key,
                          checked: model.isOptionRoute(model.$router.currentRoute.query, filterName, key) // false
                        };

                        options.push(d);
                      });
                      options = _.sortBy(options, ['title']);
                      model.filters[filterName]['options'] = options;
                    }
                    
              
                  }

                },

                /**
                 * Switch between degree/major index.
                 *
                 * @param e
                 */
                switchIndexType: function (e) {
                  let selected = e.target.value;
                  if(this.tab != selected) {
                    //clear compare 
                    eventChangeComparingList.$emit("clearComparingList");
                  }
                  this.tab = selected;

                  this.viewMoreLinkText =
                    (selected === 'degree') ? 'View Degree Details' : 'Learn More';


                  this.buildFacetsOptions(this)
                  this.seedDeptOptionList();
                }

              },

              template: `#degree-finder-tpl`
            });

          })
        }


        var $degree_finder_compare_selected_bar_el = $('#degree-finder-compare-selected-bar');

        if ($degree_finder_compare_selected_bar_el.length > 0) {
          $router_degree_finder_el.once("degree_finder_compare_selected_bar_el", function () {
            /**
             * Bottom bar with selected items.
             *
             * @type {Vue|*}
             */
          //  Drupal.degreeFinderCompareSelected = new Vue({

            Vue.component('vue-degree-finder-compare-selected-bar', {

              data:  function () {
                return {
                    comparingListIds: [],
                    comparingList: [],
                    maxItemsAware: false,
                    comparePath: '',
                    tab: '',
                    comparePathBase: location.protocol + '//' + location.host + '/' + Drupal.settings.njitSearchDegreeFinder.comparePath,
                }
              },
              watch: {
                comparingListIds: {
                  handler: function (comparingListIds) {
                    if (comparingListIds.length >= 0) {
                      this.comparePath = this.comparePathBase + '#?items=' + this.comparingListIds.slice(-3).join('&items=');
                      this.comparePath = this.comparePathBase
                        + '#?items=' + this.comparingListIds.slice(-3).join('&items=')
                        + '&type=' + this.tab;
                    }

                    if (comparingListIds.length <= 3) {
                      this.fetchData(comparingListIds);
                      this.maxItemsAware = false;
                    }
                    else {
                      this.maxItemsAware = true;
                    }
                  }
                }
              },

              created(){

                eventChangeComparingList.$on("comparingListIdsСhange", (comparingListIds, tab)=>{
                    this.comparingListIds = comparingListIds;
                    this.tab = tab;
                });
              },

              methods: {

                /**
                 * Remove all item from comparing list.
                 */
                clearAll: function () {

                  eventChangeComparingList.$emit("clearComparingList");
                },

                setBusy: function(flag) {
                  var timerAmt = 100;
                  if(!flag){
                    timerAmt = 500;
                  }
                  if(typeof this.isBusyTimer != 'undefined') {
                      clearTimeout(this.isBusyTimer);
                    }
                    this.isBusyTimer = setTimeout(function () { 
                      if(flag){
                        if(!this.isBusy) {
                          this.isBusy = flag;
                        }
                      } else {
                        if(this.isBusy) {
                          this.isBusy = flag;
                        }
                      }

                    }.bind(this), timerAmt);
                  
                },
                /**
                 * Remove item from comparing list.
                 *
                 * @param index
                 */
                removeItem: function (index) {
                  if (index > -1) {
                    eventChangeComparingList.$emit("deleteComparingList", index);
                  }
                },

                /**
                 * Get data from server for  comparision tool.
                 *
                 * @param comparingListIds
                 */
                fetchData: function (comparingListIds) {
                  var model = this;
                  if (comparingListIds.length <= 0) {
                    model.comparingList = [];
                    return;
                  }

                  var esquery = {
                    index: Drupal.settings.njitSearchDegreeFinder.esindex,
                    type: settings.njitSearchDegreeFinder.type,
                    body: {ids: comparingListIds},
                  };
                  model.setBusy(true);
                  esclient.mget(esquery).then(function (body) {
                    //TODO: don't clear the list, but just remove the item.
                    model.comparingList = [];
                    for (var index in body.docs) {
                      body.docs[index]._source.id = body.docs[index]._id;
                      model.comparingList.push(body.docs[index]._source);
                    }
                    model.setBusy(false);
                  }, function (error) {
                    model.setBusy(false);
                    console.trace(error.message);
                  });
                }
              },
              template: `#degree-finder-compare-selected-bar`
            });
          });
        }


        const componentDegreeFinder = {
          template: `
          <div>
            <vuedegreefinder></vuedegreefinder>
            <vue-degree-finder-compare-selected-bar></vue-degree-finder-compare-selected-bar>
          </div>
          `
        }

        const routes = [
          { path: '/', component: componentDegreeFinder },
          { path: '/params/:value', component: componentDegreeFinder }
        ]

        /**
         * TODO: Add router.
         *
         * @type {VueRouter|*}
         */

        const router = new VueRouter({
        // mode: 'history',
          routes
        })

        if ($router_degree_finder_el.length > 0) {
          new Vue({
            router
          }).$mount('#router-degree-finder');
        }

      }

    }
  }
})(Drupal, jQuery);
/**
 * The degree finder behaviour.
 */
(function (Drupal, $) {
  "use strict";
  var vueJsRootSelector = '#degree-finder-compare-selected';
  var isInit = false;
  if ($(vueJsRootSelector).length > 0) {
    if (typeof Array.range === 'undefined') {
      Array.range = function(start, end, step) {
        var ar = [];
        if (start < end) {
          if (arguments.length === 2) step = 1;
          for (var i = start; i <= end; i += step) {
            ar.push(i);
          }
        }
        else {
          if (arguments.length === 2) step = -1;
          for (var i = start; i >= end; i += step) {
            ar.push(i);
          }
        }
        return ar;
      };
    }
  
    Drupal.degreeFinderCompareSelected = Drupal.degreeFinderCompareSelected || {};
    Drupal.majorDegreeComparsion = Drupal.majorDegreeComparsion || {};
    /**
     * The degree finder behaviour.
     *
     * @type {{attach: Drupal.behaviors.njitHeader.attach}}
     */
    Drupal.behaviors.degreeFinderCompare = {
  
      attach: function (context, settings) {
          if(isInit) {
            return;
          }
          isInit = true;
          // Init ES client.
          var esclient = new $.es.Client({
            hosts: Drupal.settings.njitSearchDegreeFinder.eshost
          });

          var cacheStore = {
            dataStore: {
              documents: {}
            },
            getDocument: function(id) {
              return this.dataStore.documents[id];
            },
            storeCache: function(obj, searchType, data){
              var $this = this;
              var cachekey = this.generateHash(JSON.stringify(obj)+":"+searchType);
              this.dataStore[cachekey] = data;
              if(searchType === 'mget') {
                _.each(data.docs, function(item) { 
                  $this.dataStore.documents[item._id] = item;
                });
              }
              return this.dataStore[cachekey];
            },
            generateHash: function(s) {
              return _.reduce(s.split(""), function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);              
            },
            getLoadedDocumentIds: function() {
              return _.map(this.dataStore.documents, function(item, key) {
                return item._id;
              })
            },
            getCache: function(obj, searchType) {
              var cachekey = this.generateHash(JSON.stringify(obj)+":"+searchType);
              if(typeof this.dataStore[cachekey] !== 'undefined') {
                return this.dataStore[cachekey];
              } else {
                return false;
              }
            }
          };
  
          /**
           * Construct the config object for the filters options.
           *
           * @param definition
           * @constructor
           */
          function FilterOptions(definition) {
            var defaultDef = {
              options: [],
              type: 'select',
              value: '*'
            };
            $.extend(this, defaultDef, definition);
          }

  
          /**
           * Get base filters (facets) definition.
           *
           * This is base definition which use to clone from for
           * this.filters in this.buildFacetsOptions().
           *
           * @param type
           *   major/degree
           * @returns {*}
           */
          var getFiltersBaseDefinition = function(type) {
            var filtersDef = {
              degree: {
                degree_level: new FilterOptions({
                  label: 'Degree',
                  aggFilterName: 'degree_level_terms.keyword'
                }),
                college: new FilterOptions({
                  label: "College",
                  aggFilterName: 'department_college_terms'
                }),
                department: new FilterOptions({
                  label: "Department",
                  aggFilterName: 'department_terms'
                }),
                /*accelerated_option: new FilterOptions({
                  label: 'Accelerated_option',
                  aggFilterName: 'accelerated_option_terms.keyword'
                }),*/
                degree_offerings: new FilterOptions({
                  label: "Degree offerings",
                  aggFilterName: 'degree_offerings'
                })
              },
              major: {
                college: new FilterOptions({
                  label: "College",
                  aggFilterName: 'department_college_terms'
                })
              }
            };
            return filtersDef[type];
          };
  
          /**
           * TODO: Add router.
           *
           * @type {VueRouter|*}
           */
          var routes = new VueRouter({
            // mode: 'history',
            routes:  [
              { path: '/', component: {} }
            ]
          });
  
          /**
           * Comparision tool.
           *
           * Incomplete.
           *
           * @type {Vue|*}
           */
          Drupal.majorDegreeComparsion = new Vue({
            router: routes,
            el: vueJsRootSelector,
            watch: {
              $route: {
                handler: function (to, from) {
                  this.comparingListIds = this.getComparingListIdsFromRoute();
                }
              },
              comparingListIds: {
                handler: function (comparingListIds) {
                  this.comparingList = [];
                  if (this.comparingListIds.length > 0) {
                    this.fetchData();
                  }
                }
              }
            },
            data: {
              fields_to_compare: {
                degree: {
                  // title: "",
                  // summary: "Program Summary",
                  /*degree_level_terms: "Degree level",
                  accelerated_option_terms: "Special Options",
                  department_college_terms: "College",
                  department_terms: "Department",*/
                  degree_offerings: "Format",
                  areas_of_study_terms: "Areas of Study",
                  recommended_for: "Recommended For",
                  common_job_titles_terms: "Common Job Titles",
                  //in_state_tuituion_cost: "In-State Tuition Cost",
                  required_credits: "Required Credits"
                },
                major: {
                  // title: "",
                  // summary: "Program Summary",
                  job_titles_terms: "Common Job Titles",
                  top_employers_terms: "Top Employers",
                  related_degrees: "Degrees Offered"
                
                }
              },
              formatLookupTable: {
                'on-campus': 'On Campus',
                'online': 'Online',
                'offf-campus': 'Off Campus',
                'off-campus': 'Off Campus'
              },
              comparingListIds: [],
              comparingListIdsForward: [],
              comparingList: [],
              showComparing: true,
              fieldsToCompare: {},
              totalCompareItems: Array.range(0, 2, 1),
              searchToolSelectOptions: Array.range(0, 2, 1),
              type: 'degree',
              filters: Array.range(0, 2, 1),
              filtersBase: {},
              esFrom: 0,
              esSize: 15
            },
  
            /**
             * Subscribe to "created" event.
             */
            updated: function () {
              var $this = this;
              this.$nextTick(function () {
                //setTimeout(function() { 

                $this.equalizeHeights('.title_wrapper h4 .txt');
                $this.equalizeHeights('.compare-summary');
                $this.equalizeHeights('.compare-salary');
                $this.equalizeHeights('.compare-job_titles_terms');
                $this.equalizeHeights('.compare-degree_offerings');
                $this.equalizeHeights('.compare-areas_of_study_terms');
                $this.equalizeHeights('.compare-recommended_for');
                $this.equalizeHeights('.compare-common_job_titles_terms');
                $this.equalizeHeights('.compare-in_state_tuition_cost');
                $this.equalizeHeights('.compare-in_state_required_credits');
                $this.equalizeHeights('.compare-top_employers_terms');
                
                //}, 0);
                
                // Code that will run only after the
                // entire view has been re-rendered
              })
            },

            created: function () {
  
              this.comparingListIds = this.getComparingListIdsFromRoute();
              this.comparingListIdsForward = this.clone(this.comparingListIds);
              // First determine the index type.
              this.setType();
              // Define the fields to compare.
              this.fieldsToCompare = this.getFieldsToCompare(this.type);
              // Define the filters
              this.filtersBase = getFiltersBaseDefinition(this.type);
              // Populate the filters options.
              this.buildFacetsOptions();
            },
            methods: {
  
              /**
               * Helper method to clone the object without the events listeners.
               *
               * @param variable
               * @returns {any}
               */
              sortAndClean(item) {
                var cleaned = item;
                _.each(this.fields_to_compare[this.type], function(d,k){ 

                  if(k.indexOf('_terms') != -1) {;
                    cleaned[k] = item[k].sort();
                  }
                });

                return cleaned;
              },
              getFieldsToCompare(type) {
                return this.fields_to_compare[type];
              },
              isDefined: function(test) {
                if(typeof test == 'undefined'){
                  return false;
                } else {
                  return true;
                }
              },
              formatSalary: function(value) {
                if(parseInt(value)) {
                  return '$'+value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");;
                } else {
                  return '-'
                }
              },

              clone: function (variable) {
                return JSON.parse(JSON.stringify(variable))
              },
  
              /**
               * React on Major/Degree select action.
               *
               * Assign the value to temp storage this.comparingListIdsForward.
               *
               * @param event
               */
              comparingItemSelectorChanged: function (event) {
                this.comparingListIdsForward.push(event.target.value);
              },
  
              /**
               * React on Major/Degree select action button press.
               *
               * Change the comparingListIds.
               *
               * @param event
               */
              addToComparisonList: function (event) {
                routes.push({ query: {items: this.comparingListIdsForward, type: this.type } })
                this.comparingListIds = this.clone(this.comparingListIdsForward);
              },
              addCommasToFloat: function(value) {
                
                  return '$'+value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");;

              },
              getTuitionCost: function(item) {
                if(typeof item.required_credits != 'undefined') {
                  var credits = (item.required_credits) ? parseInt(item.required_credits): 0;
                  if(item.degree_level_terms.indexOf("Bachelor's") != -1) {
                    return this.addCommasToFloat((credits * 456.26).toFixed(2));
                  } else {
                    return this.addCommasToFloat((credits * 615.10).toFixed(2));
                  }
                } else {
                  return '-';
                }
                
              },
              /**
               * Constuct the ES query.
               *
               * @param filtersBase
               * @param esbody
               * @returns {*}
               */
              buildFilterQuery: function (filtersBase, esbody) {
                for (var filterName in filtersBase) {
                  if (filtersBase.hasOwnProperty(filterName)) {
                    switch (filtersBase[filterName].type) {
                      case 'select':
                        if (filtersBase[filterName].value !== '*') {
                          esbody.andQuery('term', filtersBase[filterName].aggFilterName, filtersBase[filterName].value);
                        }
                        break;
                    }
                  }
                }
              },
              getDegrees: function(term) {
                if(term.length) {
                  var model = this;
                  var esbody = bodybuilder();
                  _.each(term, function(item) {

                    esbody.andFilter('bool', function (q) {
                      q.orFilter('term', 'major_terms', item);
                      return q;
                    });

                  });

                  esbody.rawOption('_source', 'title')
                  
                  var esquery = {
                    index: Drupal.settings.njitSearchDegreeFinder.esindex,
                    type: 'degree',
                    body: esbody.build(),
                    size: 1000
                  };
                  var cachekey = JSON.stringify(esquery);
                  var cache = cacheStore.getCache(esquery, 'search');
                  if(cache) {
                    var prom = new Promise(function(resolve, reject) {
                      resolve(cache);
                    });
                    return prom;
                  } else {
                    var prom = new Promise(function(resolve, reject) {
                      esclient.search(esquery).then(function(resp) {
                        cacheStore.storeCache(esquery, 'search', resp);
                        resolve(resp);
                      });
                    });
                    return prom;
                  }
                  

                }
                /*
  
                esclient.mget(esquery).then(function (body) {
                  // Set Results.
                  var docs = body.docs;
                  for (var i in docs) {
                    docs[i]._source.id = docs[i]._id;
                    docs[i]._source.body = docs[i]._source.summary;
                    models.getDegrees(docs[i]._source.major_terms);
                    //docs[i]._source.related_degrees = models.getDegrees(docs[i]._source.major_terms);
                    model.comparingList.push(docs[i]._source);
                  }
                  

                }, function (error) {
                  console.trace(error.message);
                });*/
              },
              /**
               * Get the array of IDs to compare from route.
               *
               * @returns {*}
               */
              getComparingListIdsFromRoute: function () {
  
                if (typeof this.$route.query.items === 'string') {
                  return new Array(this.$route.query.items);
                }
                else if (typeof this.$route.query.items === 'object') {
                  return this.$route.query.items;
                }
                return [];
              },
  
              /**
               * Index type getter.
               *
               * The index type must be definde in URL.
               *
               * @returns {*}
               */
              getType: function () {
                if (typeof this.$route.query.type === 'string') {
                  return this.$route.query.type;
                }
                return [];
              },
  
              /**
               *  Set the index type.
               */
              setType: function () {
                this.type = this.getType();
              },
  
              /**
               * Helper method to build the body class.
               *
               * @param text
               * @param preffix
               * @returns {string}
               */
              buildClass: function (text, preffix) {
                //TODO: sanitize text.
                var value = [preffix, text];
                return value.join('-');
              },
  
              /**
               * Remove item from comparing list.
               *
               * @param index
               */
              removeItem: function (index, id) {
                var ids = _.filter(this.comparingListIds, function(item) {
                  return item != id;
                });
                
                routes.push({ query: {items: ids, type: this.type } })
                if (index > -1) {
                  this.comparingListIds.splice(index, 1);
                  this.comparingListIdsForward = this.clone(this.comparingListIds);
                }
              },
  
              /**
               * React on filters selection.
               *
               * @param event
               */
              filterChanged: function (event) {
                var column = $(event.target).data('column');
                var filterName = $(event.target).data('filter');
                this.filters[column][filterName].value = $(event.target).val();
                this.updateAvailableOptions(column);
              },
    
              equalizeHeights: function(selector) {
                var maxHeight = 0;
                $(selector).each(function(){
                  $(this).css('height', 'initial');
                });

                $(selector).each(function(){
                   if ($(this).height() > maxHeight) { 
                    maxHeight = $(this).outerHeight(); 
                  }
                });

                $(selector).css('height', maxHeight+'px');
              },

              /**
               * Fetch the data for comparing items
               * Based on comparingListIds.
               */
              fetchData: function () {
                var model = this;
                var loadedDocumentIds = cacheStore.getLoadedDocumentIds();
                
                var nonLoadedIds = _.filter(this.comparingListIds, function(item, key) {
                  return loadedDocumentIds.indexOf(item) == -1
                });

                var loadedIds = _.filter(this.comparingListIds, function(item, key) {
                  return loadedDocumentIds.indexOf(item) != -1
                });

                var esquery = {
                  index: Drupal.settings.njitSearchDegreeFinder.esindex,
                  type: this.type,
                  body: {ids: nonLoadedIds}
                };
                var handleResponse = function (body) {
                  // Set Results.
                  var docs = body.docs;
                  _.each(loadedIds, function(d) {
                    model.comparingList.push( cacheStore.getDocument(d)._source);
                  });

                  _.each(docs, function(d) { 
                    model.getDegrees(d._source.major_terms).then(function (degrees) {
                      if(degrees.hits.total) { 
                        d._source.related_degrees = _.map(degrees.hits.hits, function(item,key) {
                          return item._source.title;
                        });
                      }
                      var sortedAndCleaned = model.sortAndClean(d._source);
                      model.comparingList.push(sortedAndCleaned);
                    }, function (error) {
                      console.trace(error.message);
                    });
                    

                  });
                  cacheStore.storeCache(esquery, 'mget', body);

                }
                var cache = cacheStore.getCache(esquery, 'mget');
                if(cache) {
                  var prom = new Promise(function(resolve, reject) {
                    handleResponse(cache);
                    resolve(cache);
                  });
                  return prom;
                } else {
                  if(nonLoadedIds.length) { 
                    var prom = new Promise(function(resolve, reject) {
                      esclient.mget(esquery).then(function(body) {
                          handleResponse(body);
                          resolve(body);
                        }, function (error) {
                        //console.trace(error.message);
                      });
                    });
                    return prom;
                  } else {
                    handleResponse({ docs: []});
                  }
                }


                
              },
              /**
               * Update the options in degree/major selector.
               *
               * @param column
               *   The column number from this.totalCompareItems.
               */
              updateAvailableOptions: function (column) {
                var esbody = bodybuilder().query('match_all');
                this.buildFilterQuery(this.filters[column], esbody);
                var body = esbody.build();
                body.sort = [
                    {"title.keyword": {order: 'asc'}},
                    "_score"
                  ];
                var esquery = {
                  index: Drupal.settings.njitSearchDegreeFinder.esindex,
                  type: this.type,
                  body: body,
                  from: this.esFrom,
                  size: 1000
                };
  
                var model = this;
                esclient.search(esquery).then(function (body) {
                  // Set Results.
                  var hits = body.hits.hits;
                  var initialOptions = [];
                  for (var hit in hits) {
                    initialOptions.push(
                      {
                        title: hits[hit]._source.title,
                        value: hits[hit]._id
                      });
                  }
  
                  model.$set(model.searchToolSelectOptions, column, initialOptions);
  
                }, function (error) {
                  console.trace(error.message);
                });
  
              },
  
              /**
               * Helper method to build the facets options.
               */
              buildFacetsOptions: function (filtersBase) {
                var model = this;
                var filterNames = Object.keys(this.filtersBase);
                console.log('filterNames', filterNames);
                var esbody = bodybuilder().query('match_all');
                // esbody = this.buildFilterQuery(this.filtersBase, esbody);
  
                for (var i in filterNames) {
                  esbody.aggregation('terms', this.filtersBase[filterNames[i]].aggFilterName, { "size": 1000, "field": this.filtersBase[filterNames[i]].aggFilterName }, filterNames[i]);
                }
                var body = esbody.build();
                body.sort = [
                    {"title.keyword": {order: 'asc'}},
                    "_score"
                  ];
                var esquery = {
                  index: Drupal.settings.njitSearchDegreeFinder.esindex,
                  type: this.type,
                  body: body,
                  from: this.esFrom,
                  size: 1000
                };
                esclient.search(esquery).then(function (body) {
                  // Extract the filtersBase options.
                  _.each(body.aggregations, function(item, key) {
                    if(typeof item.buckets != 'undefined'){
                      item.buckets = _.sortBy(item.buckets, ['key'], ['asc']);
                    }
                  });
                  for (var i in filterNames) {
                    model.buildFilterOptions(filterNames[i], body);
                  }
  
                  // Set Results.
                  var hits = body.hits.hits;
  
                  model.resultItems = [];
                  var initialOptions = [];
                  for (var hit in hits) {
                    initialOptions.push(
                      {
                        title: hits[hit]._source.title,
                        value: hits[hit]._id
                      });
                  }
  
                  // model.searchToolSelectOptions = initialOptions;
                  for (var column in model.searchToolSelectOptions) {
                    model.$set(model.searchToolSelectOptions, column, initialOptions);
                  }
  
                  // Populate the facets options.
                  // We use deep clone with JSON here, to keep filters
                  // independent between columns.
                  for (var i in model.totalCompareItems) {
                    model.filters[i] = model.clone(model.filtersBase);
                  }
  
                }, function (error) {
                  console.trace(error.message);
                });
              },
  
              /**
               * Helper function to build filters options from ES client query.
               *
               * @param filterName
               * @param rawBody
               */
              buildFilterOptions: function (filterName, rawBody) {
                var body = rawBody;
                var options = [];
  
                if (this.filtersBase[filterName]['type'] === 'select') {
                  options = [{value: '*', title: 'All'}];
                }
  
                for (var i in body.aggregations[filterName].buckets) {
                  var item = {
                    value: body.aggregations[filterName].buckets[i].key,
                    title: body.aggregations[filterName].buckets[i].key
                  };
  
                  options.push(item);
                }
                this.filtersBase[filterName].options = options;
              }
  
            }
          });
  
        
      }
    }

  }
})(Drupal, jQuery);

//Fix cbox empty buttons
(function (Drupal, $) {

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.addText.attach}}
   */

  Drupal.behaviors.addText = {
    attach: function (context, settings){
      var thetimerinterval = setInterval(function() {
        if($.colorbox) {
          $('#cboxPrevious')[0].innerHTML='Prev';
          $('#cboxNext')[0].innerHTML='Next';
          $('#cboxSlideshow')[0].innerHTML='SlideShow';
           clearInterval(thetimerinterval);
        }
      }, 1000);
    }
  }
})(Drupal, jQuery);

//For role=button tabbing 
(function (Drupal, $) {

  /**
   * JS Behaviour.
   *
   * @type {{attach: Drupal.behaviors.tabButton.attach}}
   */

  Drupal.behaviors.tabButton = {
    attach: function (context, settings){
      $('.cta-area').click(function(e) {
        var parent = $(this).parent().parent();  // or $.closest, or any travese to get to the div that should get the click
        parent.trigger('click');
        e.preventDefault();
        e.stopPropagation();
        return false;
    });
      // setTimeout(()=>{
      //   document.querySelectorAll('div[role="button"]').forEach(el => {
      //     el.addEventListener('keydown', e => {
      //         const keyDown = e.key !== undefined ? e.key : e.keyCode;
      //         if ( (keyDown === 'Enter' || keyDown === 13) || (['Spacebar', ' '].indexOf(keyDown) >= 0 || keyDown === 32)) {
      //             // (prevent default so the page doesn't scroll when pressing space)
      //             e.preventDefault();
      //             jQuery(el).trigger('click') ;
      //         }
      //     });

      //     if(!el.hasAttribute('tabindex')){
      //       el.setAttribute('tabindex','0');
      //     }
      //   });
      // },1000)
    }
  }
})(Drupal, jQuery);