(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.usgs_tables = {
    attach: function(context, settings) {
      if (settings.views && settings.views.ajaxViews) {
        var instances = settings.views.ajaxViews;
        $.each( instances , function getInstance( index, element){
          var viewName = element.view_name;
          var viewDisplay = element.view_display_id;

          if ((viewName === 'group_lp' && viewDisplay === 'directory') || (viewName === 'hq_page' && viewDisplay === 'location_table')) {

            $(".usgs-table-magnify").click(function() {
              var clickedColumn = $(this);
              // Insert exposed form into each of the columns inside table
              $(".usgs-table-exposed-form").show().detach().appendTo($(clickedColumn).siblings('.usgs-table-searchbox').children('.usgs-table-bubble'));
              $(clickedColumn).siblings('.usgs-table-searchbox').toggle();
              $('.usgs-table-magnify').not($(this)).siblings('.usgs-table-searchbox').hide();
              var activeColumn = clickedColumn.data('filter').replaceAll('-', '_');
              var split = activeColumn.split(" ")[0];
              // Hide all form fields and select by default
              $(this).siblings('.usgs-table-searchbox').find( "input.fa-search" ).show();
              $(this).siblings('.usgs-table-searchbox').find('input.form-text').hide();
              $(this).siblings('.usgs-table-searchbox').find('input.fa-times').hide();
              $(this).siblings('.usgs-table-searchbox').find('select.form-select').hide();
              $('.table-reset').hide();
              var active = $(this).siblings('.usgs-table-searchbox').find( "input[name*='"+split+"']" );
              var search = $(this).siblings('.usgs-table-searchbox').find( "input.fa-search" );

              // Special case for location type
              var textsplit = 'node_location_type';
              $(this).siblings('.hq_page-node-title').find( "select[name*='"+textsplit+"']" ).show();
              $(active).show();

              if(active.val().length !== 0 ) {
                $('.submit-test').show();
                $(this).siblings('.usgs-table-searchbox').find( "input.fa-times" ).show();
                $(this).siblings('.usgs-table-searchbox').find( "input.fa-search" ).hide();
              }

              $('.table-reset').click(function(e){
                e.preventDefault();
                // reset form field val to mimick a 'reset'
                $(active).val("");
                $(search).click();
              });

            });
          }

        });

      }
    }
  };

})(jQuery, Drupal);
