/**
 * @file
 * A JavaScript file for the theme.
 *
 * In order for this JavaScript to be loaded on pages, see the instructions in
 * the README.txt next to this file.
 */

// Avoid `console` errors in browsers that lack a console.

(function() {

    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }

    if (typeof String.prototype.endsWith !== 'function') {
        String.prototype.endsWith = function(suffix) {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        };
    }

}());

// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it with an "anonymous closure". See:
// - https://drupal.org/node/1446420
// - http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
(function ($, Drupal, window, document, undefined) {
    if(typeof window.actions == 'undefined') {
      window.actions = new Array();
    }
    window.actions['loadmore'] = new Array();
    window.actions['filter'] = new Array();

    /**
     * Add an extra listener to the window load event and perform revalidation.
     * This makes sure that Safari also loads images on initial requests.
     */
    window.addEventListener('load', function () {
        Drupal.blazy.init.revalidate();
    });

    // Override the original "clearing" success callback from the Drupal blazy
    // module with our own custom function.
    Drupal.blazy.originalClearing =  Drupal.blazy.clearing;  // Keep track of the original.
    Drupal.blazy.clearing = function(el) {
        Drupal.blazy.originalClearing(el); // Call the original function.
        // Force picturefill reevaluate.
        if (typeof picturefill !== "undefined") {
            picturefill(
                {
                    reevaluate: true,
                }
            );
        }
        // Call function to resize captions in IE.
        fixIECaptions();
    }

    function CheckBrowser(e) {
        if (window.event)
            key = window.event.keyCode;     //IE
        else
            key = e.which;     //firefox
        return key;
    }

    function nhlbiSelectHandler(event, ui) {
        window.location.href = ui.item.value;
    }

    //Make IE properly size captions to img size
    function fixIECaptions() {
        var isIE11 = !!(navigator.userAgent.match(/Trident/) && navigator.userAgent.match(/rv[ :]11/));
        if (isIE11){
            $( "figure.caption" ).each(function(i) {
                var containerWidth = $(this).parent().width();
                $(this).find('img').each(function(j) {
                    imgWidth = $(this).width();
                    if (imgWidth > (containerWidth-10)){
                        $(this).siblings().width((containerWidth-10));
                    }else{
                        $(this).siblings().width(imgWidth);
                    }
                });
            });

            $(".embedded-image-and-photocredit-container").each(function (k) {
                var containerWidth = $(this).parent().width();
                $(this).find('img').each(function(l) {
                    imgWidth = $(this).width();
                    if (imgWidth > (containerWidth-10)){
                        $(this).closest(".embedded-image-and-photocredit-container").siblings(".embedded-image-caption").width((containerWidth-10));
                    }else{
                        $(this).closest(".embedded-image-and-photocredit-container").siblings(".embedded-image-caption").width(imgWidth);
                    }
                });
            });
        }
    }
    Drupal.behaviors.IEImageFix = {
        attach: function(context, settings){
            fixIECaptions();

            $('figure img').on('load',function(){
              fixIECaptions();
            });
            $('.embedded-image-and-photocredit-container img').on('load',function(){
                fixIECaptions();
            });
        }
    };
    // Adding sandbox attribute to iframes.
    Drupal.behaviors.addSandboxToIFrame = {
        attach: function(context, settings) {

            function waitForElm(selector) {
                return new Promise(resolve => {
                    if (document.querySelector(selector)) {
                        return resolve(document.querySelector(selector));
                    }

                    const observer = new MutationObserver(mutations => {
                        if (document.querySelector(selector)) {
                            resolve(document.querySelector(selector));
                            observer.disconnect();
                        }
                    });

                    observer.observe(document.body, {
                        childList: true,
                        subtree: true
                    });
                });
            }

            waitForElm('iframe').then((elm) => {
                $('iframe').not("#a2a_sm_ifr").attr("sandbox", "allow-same-origin allow-scripts");
                $("#a2a_sm_ifr").attr("sandbox", "");
            });
        }
    };

    //Make Picturefill reevaluate on page load to fix blazy issues.
    Drupal.behaviors.picturefillBlazyFix = {
        attach: function(context, settings){

            if (typeof picturefill !== "undefined") {
                picturefill(
                    {
                        reevaluate: true,
                    }
                );
            }
        }
    };

    Drupal.behaviors.lazyImagePrint = {
        attach: function (context, settings) {
            (function () {
                /*
                BROWSER'S NATIVE PRINT EVENTS LISTENERS
                ---------------------------------------
                In order to make browsers load all the images before printing
                even if the user doesn't press the custom print button.
                NOTE that this works only partially in some browsers! */
                var isSafari = /^((?!chrome|android).)*safari/i.test(
                    navigator.userAgent
                );
                if (!isSafari) {
                    window.onbeforeprint = function () {
                        $('.b-lazy').each(function() {
                            $(this).attr('src', $(this).data('src'));
                            $(this).removeClass('b-lazy');
                        });

                    };
                } else {
                    // Safari doesn't support the onbeforeprint event
                    var mediaQueryList = window.matchMedia("print");
                    mediaQueryList.addListener(function (mql) {
                        if (mql.matches) {
                            $('.b-lazy').each(function() {
                                $(this).attr('src', $(this).data('src'));
                                $(this).removeClass('b-lazy');
                            });

                        }
                    });
                }

                // Handle health topics print button.
                jQuery('.nhlbi-print-modal').on('click', function () {
                    $('.b-lazy').each(function() {
                        $(this).attr('src', $(this).data('src'));
                        $(this).removeClass('b-lazy');
                    });
                })
            }());

        }
    };


    Drupal.behaviors.moveLanguageToggle = {
        attach: function(context, settings) {
            $('.view-mode-full .links').insertBefore('#content h1');

        }
    };

    Drupal.behaviors.removeEmptyBody = {
        attach: function(context, settings){
            $('#content article .field-name-body p').filter(function(){
                return $(this).html() == " ";
            }).remove();
        }
    }

    Drupal.behaviors.bannerImage = {
        attach: function(context, settings){
            var url = document.URL;
            if(url.match('stories-of-success-landing-page')) {
                //move the banner image
                $(".pane-center-above").insertBefore("#content > h1");
            }
        }
    }

    Drupal.behaviors.moveFeatured = {
        attach: function(context, settings){
            var url = document.URL;
            if(!url.endsWith('/spotlight')) {
                $("#content .view-display-featured-fact-sheet, #content .view-display-featured-story").insertAfter($("#content .field-name-body:first"));
            }
        }
    }


    Drupal.behaviors.responsiveTables = {
        attach: function(context, settings){
            $('.text-formatted  table').stacktable();
        }
    }
    Drupal.behaviors.pager_mobile = {
        attach: function(context, settings){
          $(".pager .pager__items li.is-active").prev().addClass('before-is-active');
          if ($(".pager__items li").hasClass('pager__item--first')) {
            if ($(".pager__items li").hasClass('pager__item--last')) {
              return;
            }
            else {
              $(".pager .pager__items li.before-is-active").prev().addClass('pager-is-visible');
              $(".pager .pager__items li.before-is-active").addClass('before-is-active-last');
            }
          }
          else {
            $(".pager__items li:nth-child(3)").addClass('pager-is-visible');
          }
        }
    }
    Drupal.behaviors.autocompleteSupervisor = {
        attach: function (context) {
            $('#edit-name', context).bind('autocompleteclose', function(event, node) {

                // if selected redirect to url.
                //alert("hello");

            });
        }
    };

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

            var sourceUrl = $( ".views-autocomplete .autocomplete-box" ).data('source');
            if(sourceUrl !== null && sourceUrl !== undefined ){
                $( ".views-autocomplete .autocomplete-box" ).autocomplete({
                    minLength: 2,
                    html:true,
                    source: sourceUrl
                });
            }
            // override drupal default of one char for all autocompletes.
            if( Drupal.autocomplete != undefined ){
                Drupal.autocomplete.options.minLength = 2;
                // Drupal.autocomplete.options.select = nhlbiSelectHandler;


            }

        }
    }


    Drupal.behaviors.readMoreAlert = {
        attach: function(context) {


            $( ".readMoreAlertLink" ).click(function(event){
                $(this).addClass('hidden');
                $(this).closest('.sitewide-alert').find(".readMoreAlertText").removeClass('hidden');
            });
            $( ".readLessAlertLink" ).click(function(){
                var $myPanel = $(this).closest('.sitewide-alert');
                $myPanel.find('.readMoreAlertLink').removeClass('hidden');
                $myPanel.find('.readMoreAlertText').addClass('hidden');
            });
        }
    };

    Drupal.behaviors.hideSocialMediaIcons = {
        attach: function(context) {

            if ($('.field--name-field-hide-social-media-icons').text() == '1') {
              $('.block-addtoany').addClass('hidden');
            }
        }
    };
    Drupal.behaviors.hideSocialMediaBlock = {
        attach: function(context) {

            if ($('.field--name-field-hide-social-media-icons').text() == '1') {
              $('.block-type-social-media-block').addClass('hidden');
            }
        }
    };

    // Fix for empty <th> tags created by stackable.js
    Drupal.behaviors.fixemptytableheader= {
        attach: function(context, settings){
            $('th.st-head-row').each(function() {
                var innerText = $(this).html().trim();
                if(typeof  innerText == 'undefined' || innerText.length == 0 || innerText == ' ' ||  innerText == '<p> </p>') {
                    $(this).replaceWith( "<td>" + $(this).html() + "</td>" );
                }
            });
        }
    }


    Drupal.behaviors.trackLoadMore = {
        attach: function(context, settings){
            $('.pager .button').on('click', function(e){

                // Figure out what view id ths button is on in case there are multiple views on the page.
                var parentView = $(this).parents('.view');
                if(parentView.length > 0) {
                    var classes = parentView.attr('class').split(' ');

                    var viewID = classes.filter(function(item){
                        return typeof item == 'string' && item.indexOf("view-id-") > -1;
                    });
                    }
                else {
                    viewID = 'unknown_view';
                }

                if(viewID.length == 0) {
                    viewID = 'unknown_view';
                }
                // If the array already has a number for this view, increment it.
                if(typeof window.actions['loadmore'][viewID] == 'number'){
                    window.actions['loadmore'][viewID]++;
                }
                // If there is no number for this view, this is the first click.
                else {
                    window.actions['loadmore'][viewID] = 1;
                }
            });

        }
    };

    Drupal.behaviors.trackFilter = {
        attach: function(context, settings){
            // This is a bit ugly but we only want to run this on views with a searchbar,
            // not every form.
            $('.nhlbi-searchbar-container').parent().find('.form-submit').on('click', function(e) {
                // Don't execute this for the all science view.
                if(typeof window.actions['filter']['all_science'] == 'undefined') {
                    // Figure out what view id ths button is on in case there are multiple views on the page.
                    var parentView = $(this).parents('.view');
                    if (parentView.length > 0) {
                        var classes = parentView.attr('class').split(' ');
                        var viewID = classes.filter(function (item) {
                            return typeof item == 'string' && item.indexOf("view-id-") > -1;
                        });
                    } else {
                        viewID = 'unknown_view';
                    }

                    if (viewID.length == 0) {
                        viewID = 'unknown_view';
                    }

                    // If the array already has a number for this view, increment it.
                    if (typeof window.actions['filter'][viewID] == 'number') {
                        window.actions['filter'][viewID]++;
                    }
                    // If there is no number for this view, this is the first click.
                    else {
                        window.actions['filter'][viewID] = 1;
                    }
                }
            });
        }
    };

    Drupal.behaviors.viewMoreFilters = {
        attach: function(context) {

            $( ".clinical-trials-landing-filters-view-more a" ).click(function(event){
                $('.clinical-trials-landing-filters').find('.clinical-trials-landing-filters-view-more').addClass('visually-hidden')
                $('.clinical-trials-landing-filters').find('.clinical-trials-landing-filters-container').addClass('clinical-trials-landing-filters-container-active');
                $('.clinical-trials-landing-filters').find('.clinical-trials-landing-filters-view-less').removeClass('visually-hidden');
                $('.clinical-trials-landing-filters').find('.clinical-trials-filters-label a').removeClass('visually-hidden');
            });
            $( ".clinical-trials-landing-filters-view-less a" ).click(function(){
                $('.clinical-trials-landing-filters').find('.clinical-trials-landing-filters-view-less').addClass('visually-hidden');
                $('.clinical-trials-landing-filters').find('.clinical-trials-landing-filters-container').removeClass('clinical-trials-landing-filters-container-active');
                $('.clinical-trials-landing-filters').find('.clinical-trials-landing-filters-view-more').removeClass('visually-hidden');
            });
            $( ".clinical-trials-filters-label a" ).click(function(){
                $('.clinical-trials-landing-filters').find('.clinical-trials-filters-label a').addClass('visually-hidden');
                $('.clinical-trials-landing-filters').find('.clinical-trials-landing-filters-container').removeClass('clinical-trials-landing-filters-container-active');
                $('.clinical-trials-landing-filters').find('.clinical-trials-landing-filters-view-more').removeClass('visually-hidden');
            });
        }
    };

    Drupal.behaviors.publicationsLanding = {
        attach: function(context) {
           $(once('pubfilter', '#views-exposed-form-publications-search-block-1 [data-drupal-selector=\'edit-sort-by\']', context)).each(function (context) {

             $(this).on('change', function(e) {
               $('#views-exposed-form-publications-search-block-1 [data-drupal-selector="edit-actions"] .form-submit').first().click();
             });
           });
        }
    };


    // Unselect letter filter on HT landing if it is clicked while active.
    Drupal.behaviors.htlandingFilters = {
      attach: function (context, settings) {
        $('.view-id-health_topics_a_z .views-exposed-form input[name=letter]').click(function (e) {
          if ($(this).attr('checked') == 'checked') {
             $(this).removeAttr('checked');
             $(this).trigger('change');
          }
        });
      }
    };

    Drupal.behaviors.mainMenuNavigation = {
        attach: function(context) {

            var window_height_for_menu = $(document).height();

            // Unbind any existing click and focus events on the main menu.
            $( 'ul.menu-level-0 > li > span ' ).off('click focus');
            //When clicking or tabbing through a menu item, open or close its sub-menu
            $( 'ul.menu-level-0 > li > span ' ).on('click focus', function(e){
                e.preventDefault();
                e.stopPropagation();

                if(e.type=='click'){
                    if($(this).data('justfocussed')){
                        $(this).data('justfocussed', false);
                    }else{
                        toggleSubMenu(this);
                    }
                }
                else if(e.type=='focus'){
                    showSubMenu(this);
                    $(this).data('justfocussed', true);
                }
            });

            //On focus out of last element in the submenu, close the submenu
            $( 'ul.menu-level-1 > li.highlighted:last > ul.menu-level-2:last > li:last > a' ).on('blur', function(){
                $('.level1-menu-wrapper').addClass('hidden');
                $('#main-menu-blur-shadow').hide();
                $('.menu-item-link').removeClass('menu-expanded');
            });

            //Toggle submenu visibility
            function toggleSubMenu(ele){
                var child_id = $(ele).parent().attr('id') + '_children';

                //if children sub-menu is hidden, show submenu
                if($( '#' + child_id).hasClass('hidden')){
                    showSubMenu(ele);
                }else{
                    $('.level1-menu-wrapper').addClass('hidden');
                    $( '#main-menu-blur-shadow').hide();
                    $(ele).parent().removeClass('menu-expanded');
                }
            }

            //Show submenu
            function showSubMenu(ele){
                var child_id = $(ele).parent().attr('id') + '_children';
                // remove all and add to one
                $('.level1-menu-wrapper').addClass('hidden');
                $( '#' + child_id).removeClass('hidden');
                if($(window).width() > 1100 ) {
                    $('#main-menu-blur-shadow').show();
                    $('#main-menu-blur-shadow').height(window_height_for_menu);
                }
                // remove all and add to one
                $( 'ul.menu-level-0 > li ' ).removeClass('menu-expanded');
                $(ele).parent().addClass('menu-expanded');
            }

             if($(window).width() < 1100 ) {
               $( "ul.menu-level-0 > li span.level-0-link").click(function(e){
                    e.preventDefault();

                    if($(".menu-level-0 > li").hasClass("menu-expanded")){
                        $(".menu-item-link-main").addClass("menu-item-link-main-expanded");
                        $(".menu-item-link-main").removeClass("hidden");
                        $(".menu-level-0 > li").addClass("hidden");
                        $(".menu-level-0 > li.menu-expanded").removeClass("hidden");
                        $(".menu-level-0 > li.menu-item-link-home").removeClass("hidden");

                    }
                    else {
                      $(".menu-item-link-main").removeClass("menu-item-link-main-expanded");
                      $(".menu-level-0 > li").removeClass("hidden");
                    }
                });
               $( ".menu-item-link-main span a").click(function(e){
                   e.preventDefault();
                   $( "ul.menu-level-0 > li" ).removeClass("hidden menu-expanded");
                   $(".menu-item-link-main").removeClass("menu-item-link-main-expanded");
                   $(".level1-menu-wrapper").addClass("hidden");
                   //$(".menu-item-link-main").addClass("menu-item-link-main-expanded");
               });

             }
             $( "#main-menu-blur-shadow" ).click(function(e){
                 e.preventDefault();
                 $('.level1-menu-wrapper').addClass("hidden");
                 $( "#main-menu-blur-shadow").hide();
                 $( "ul.menu-level-0 > li " ).removeClass("menu-expanded");
                 $(".menu-item-link-main").removeClass("menu-item-link-main-expanded");

             });


            $(once('mobilemenuclick', '#hamburger-nav-icon', context)).each(function (context) {
              $(this).on('click', function(e) {
                e.preventDefault();
                if($( this ).hasClass("menu-expanded-hamburger")){
                  $( "ul.menu-level-0 > li " ).removeClass("hidden menu-expanded");
                  $( "ul.menu-level-0 > .menu-item-link-main " ).removeClass("menu-item-link-main-expanded");
                  $( ".level1-menu-wrapper" ).addClass("hidden");
                  $("#searchBoxIconInner" ).removeClass("visually-hidden");
                }
                else {
                  $("#searchBoxIconInner").toggleClass("visually-hidden");
                }
                $( this ).toggleClass("menu-expanded-hamburger");
                $("ul.menu-level-0" ).toggleClass("menu-expanded");
                //$("ul.menu-level-0").height(window_height_for_menu);
                $("#main-menu-blur-shadow-tablet-mobile").height(window_height_for_menu);
                $("#main-menu-blur-shadow-tablet-mobile").toggle();
                $("#global-search-bar-phone" ).toggleClass("menu-expanded");

              });
            });

            $(once('mobilemenuclick', '#searchBoxIconInner', context)).each(function (context) {
              $(this).on('click', function (e) {
                e.preventDefault();
                if ($(this).hasClass("menu-expanded-hamburger")) {
                  $("ul.menu-level-0 > li ").removeClass("menu-expanded");
                  $(".level1-menu-wrapper").addClass("hidden");
                }
                $("#hamburger-nav-icon").toggleClass("menu-expanded-hamburger");
                $("ul.menu-level-0").toggleClass("menu-expanded");
                $("#main-menu-blur-shadow-tablet-mobile").height(window_height_for_menu);
                $("#main-menu-blur-shadow-tablet-mobile").toggle();
                $("#global-search-bar-phone").toggleClass("menu-expanded");
                $("#searchBoxIconInner").addClass("visually-hidden");

              });
            });

            $( "#main-menu-blur-shadow-tablet-mobile" ).click(function(e){
                e.preventDefault();
                $( "ul.menu-level-0" ).removeClass("menu-expanded");
                $( "#main-menu-blur-shadow-tablet-mobile" ).hide();
                $( "#hamburger-nav-icon" ).removeClass("menu-expanded-hamburger");
                $("#global-search-bar-phone").removeClass("menu-expanded");
                $("#searchBoxIconInner" ).removeClass("visually-hidden");
            });


            $( window ).resize(function() {
                fixIECaptions();
                if($(window).width() > 1100 ) {
                    //     $("#main-menu-blur-shadow").show();
                    $("#main-menu-blur-shadow").hide();
                    $("#main-menu-blur-shadow-tablet-mobile").hide();
                    $("ul.menu-level-0").height("inherit");
                    $("ul.menu-level-0").removeClass("menu-expanded");
                }


            });

            // Unbind any existing click and focus events on the search box.
            $( '#searchBoxIcon' ).off('click focus');
            //Allow the search box to open and close when clicking or tabbing through the search Box Icon
            $( '#searchBoxIcon' ).on('click focus', function(e){
                e.preventDefault();
                e.stopPropagation();

                //On click event
                if(e.type=='click'){
                    //Trigger focus event and ignore on click if the search box icon wasnt on focus
                    if($(this).data('justfocussed')){
                        $(this).data('justfocussed', false);
                    }else{
                        //If the search box was clicked while on focus
                        toggleSearchBox(this);
                    }
                }
                //When the search icon comes into focus open the search box
                else if(e.type=='focus'){
                    showSearchBox(this);
                    $(this).data('justfocussed', true);
                }
            });

            //Toggle the SearchBox visibility
            function toggleSearchBox(ele){
                if($(window).width() > 767 ) {
                    $('#global-search-bar-tablet-desktop').toggle();
                }else{
                    $('#global-search-bar-phone').toggle();
                }
                $( '#search-bar-blur-shadow' ).toggle();

                $(ele).toggleClass('search-bar-expanded');
            }

            //Show the SearchBox
            function showSearchBox(ele){
                if($(window).width() > 767 ) {
                    $('#global-search-bar-tablet-desktop').show();
                }else{
                    $('#global-search-bar-phone').show();
                }
                $( '#search-bar-blur-shadow' ).show();

                $(ele).addClass('search-bar-expanded');
            }

            //Toggle the search bar off when focusing away from the search button
            $('div.global-search-bar > form > input.submit-button').on('blur', function(){
                if($(window).width() > 767 ) {
                    $('#global-search-bar-tablet-desktop').toggle();
                }else{
                    $('#global-search-bar-phone').toggle();
                }
                $( '#search-bar-blur-shadow' ).toggle();

                $('#searchBoxIcon').toggleClass('search-bar-expanded');
            });


            $( "#search-bar-blur-shadow" ).click(function(e){
                e.preventDefault();
                $( "#searchBoxIcon" ).removeClass("search-bar-expanded");
                $( "#search-bar-blur-shadow").hide();
                if($(window).width() > 767 ) {
                    $("#global-search-bar-tablet-desktop").hide();
                }else{
                    $("#global-search-bar-phone").hide();
                }
            });

        }
    };

    Drupal.behaviors.htSearchClearLetter = {
        attach: function(context) {

            // Execute clearLetter() if the submit button is clicked or "enter"
            // is pressed inside the search field.
            $('.view-health-topics-a-z .form-submit').on({
                mousedown: function (e) {
                    clearLetter();
                },
                keydown: function (e) {
                    clearLetter();
                }
            });

            $('.view-health-topics-a-z input[name="search"]').on('keypress', function (e) {
                if(e.keyCode == 13) {
                    clearLetter();
                }
            });

            function clearLetter() {
                if($('.view-health-topics-a-z input[name="search"]').val().length > 0) {
                    $('.view-health-topics-a-z input[name="letter"][value="All"]').trigger('click');
                }
            }
        }
    };

  Drupal.behaviors.FacetSummaryClear = {
    attach: function(context, settings){
        $(once('facetclear', '.facet-summary-item--clear', context)).each(function (context) {
          $(this).on('click', function(e) {
            $('.clinical-trials-landing-search-block input[name="query"]').val('');
          });
      });
    }
  };

  Drupal.behaviors.JobsMobileSort = {
    attach: function(context, settings){
      // When an option is chosen from the sort dropdown, attempt to trigger
      // the corresponding clicksort on the table.
      $(once('jobsmobilesort', '#jobs-mobile-sort', context)).each(function (context) {
        $(this).on('change', function(e) {
          var column = $(this).val();
          $('th.views-field-' + column).find('a').triggerHandler('click');
        });
      });

      // Make the mobile sort dropdown match the clicksort selection.
      $('.view-id-jobs th').each(function(i) {
        if($(this).hasClass('is-active')) {
          var matches = $(this).attr('class').match(/views-field-([\w-]+)/i);
          if(matches.length == 2) {
            $('#jobs-mobile-sort').val(matches[1]);
          }
          return false;
        }
      });
    }
  };

// To understand behaviors, see https://drupal.org/node/756722#behaviors
})(jQuery, Drupal, this, this.document);