// JS code start - for date range dropdown on search page
(function ($) {
  $(function () {

    if (!String.prototype.startsWith) {
      String.prototype.startsWith = function (searchString, position) {
        position = position || 0;
        return this.indexOf(searchString, position) === position;
      };
    }
    if (!String.prototype.includes) {
      String.prototype.includes = function () {
        'use strict';
        return String.prototype.indexOf.apply(this, arguments) !== -1;
      };
    }

    if (!Array.prototype.findIndex) {
      Object.defineProperty(Array.prototype, 'findIndex', {
        value: function (predicate) {
          // 1. Let O be ? ToObject(this value).
          if (this == null) {
            throw new TypeError('"this" is null or not defined');
          }

          var o = Object(this);

          // 2. Let len be ? ToLength(? Get(O, "length")).
          var len = o.length >>> 0;

          // 3. If IsCallable(predicate) is false, throw a TypeError exception.
          if (typeof predicate !== 'function') {
            throw new TypeError('predicate must be a function');
          }

          // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
          var thisArg = arguments[1];

          // 5. Let k be 0.
          var k = 0;

          // 6. Repeat, while k < len
          while (k < len) {
            // a. Let Pk be ! ToString(k).
            // b. Let kValue be ? Get(O, Pk).
            // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
            // d. If testResult is true, return k.
            var kValue = o[k];
            if (predicate.call(thisArg, kValue, k, o)) {
              return k;
            }
            // e. Increase k by 1.
            k++;
          }

          // 7. Return -1.
          return -1;
        }
      });
    }

    function setDateRangeDropdownLabel() {
      if (!$('#label-date-range-lower').length) {
        var label_date_lower = $('<label id="label-date-range-lower" for="year_data_collected_taxonomy_term_name-lower" class="date-range-dropdown-label">').html('<span id="facet_year_data_collected_taxonomy_term_name-lower_label">From:</span>');
        label_date_lower.insertBefore($('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-lower"]'));
        ($('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-lower"]').attr("id", "year_data_collected_taxonomy_term_name-lower"));
      }
      if (!$('#label-date-range-upper').length) {
        var label_date_upper = $('<label id="label-date-range-upper" for="year_data_collected_taxonomy_term_name-upper" class="date-range-dropdown-label">').html('<span id="facet_year_data_collected_taxonomy_term_name-upper_label">To</span>:');
        label_date_upper.insertBefore($('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-upper"]'));
        ($('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-upper"]').attr("id", "year_data_collected_taxonomy_term_name-upper"));
      }
    }

    $(document).ready(function () {
      if (typeof Drupal.facets != "undefined") {
        setDropdowns();
        setDateRangeDropdownLabel();

        $("#edit-keys--2").on('change paste', function () {

          $('#edit-sort-bef-combine--2 *').removeAttr('selected');
          //   $("#edit-sort-bef-combine--2").children('option[value="search_api_relevance_DESC"]').attr("selected", "selected");
          $("#edit-sort-bef-combine--2").children('option[value="field_date_printed_on_report_DESC"]').attr("selected", "selected");

        });

      }

      $("#bodySearchAll").click(function (e) {
        e.preventDefault();
        var searchKey = $('#q').val();
        var searchURL = "/" + window.location.pathname.split('/')[1] + "/all-reports?sort_bef_combine=field_date_printed_on_report_DESC&items_per_page=15";
        if (searchKey.length > 0) {
          //  searchURL = "/" + window.location.pathname.split('/')[1] + "/all-reports?sort_bef_combine=search_api_relevance_DESC&items_per_page=15";
          searchURL = "/" + window.location.pathname.split('/')[1] + "/all-reports?sort_bef_combine=field_date_printed_on_report_DESC&items_per_page=15";
        }

        window.location = searchURL + '&keys=' + searchKey;
      });

      $("#bodySearchAllHeader, #mobileSearchAllHeader").click(function (e) {
        e.preventDefault();
        var searchKey = $('#q').val();
        var searchKey2 = $('#r').val(); // separate, unique variable for the mobile-only search bar

        var searchURL = "https://search.usa.gov/search?utf8=%E2%9C%93&affiliate=samhsa_main&query=&commit=Search";

        if (searchKey.length > 0) {
          var searchURL = "https://search.usa.gov/search?utf8=%E2%9C%93&affiliate=samhsa_main&query=" + searchKey + "&commit=Search";
        }
        if (searchKey2.length > 0) {
          var searchURL = "https://search.usa.gov/search?utf8=%E2%9C%93&affiliate=samhsa_main&query=" + searchKey2 + "&commit=Search";
        }

        window.location = searchURL;
      });

    });

    $(document).ajaxStop(function () {
      if (typeof Drupal.facets != "undefined") {
        setDropdowns();
        setDateRangeDropdownLabel();
      }
    });

    function setDropdowns() {

      if (window.location.search.substring(1).indexOf("year_data_collected") > 0) {

        $('select[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-"]').each(function () {
          //$(this).find('option').get(0).remove();
          $(this).children().first().remove();
        });
        $('ul[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-"]').each(function () {
          //$(this).find('li').get(0).remove();
          $(this).children().first().remove();
        });

        var min = getDateRange('year_data_collected', 1);
        var minExp = new RegExp('%28min%3A\d+%2C');
        var maxExp = new RegExp('%2Cmax%3A\d+%29');
        var max = getDateRange('year_data_collected', 2);

        $('select[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-lower"] option').each(function () {
          $(this).attr('value', $(this).attr('value').replace(/%2Cmax%3A\d+%29/, '%2Cmax%3A' + max + '%29'));
          $(this).text($(this).text().replace('(0)', ''));
        });

        $('ul[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-lower"] a').each(function () {
          $(this).attr('href', $(this).attr('href').replace(/%2Cmax%3A\d+%29/, '%2Cmax%3A' + max + '%29'));
        });

        $('select[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-upper"] option').each(function () {
          $(this).attr('value', $(this).attr('value').replace(/%28min%3A\d+%2C/, '%28min%3A' + min + '%2C'));
          $(this).text($(this).text().replace('(0)', ''));
        });

        $('ul[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-upper"] a').each(function () {
          $(this).attr('href', $(this).attr('href').replace(/%28min%3A\d+%2C/, '%28min%3A' + min + '%2C'));
        });

        var currentDateRangeQuery = 'year_data_collected_taxonomy_term_name%3A%28min%3A' + min + '%2Cmax%3A' + max + '%29';

        if ($('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-lower"] option[value*="' + currentDateRangeQuery + '"]').length) {
          $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-lower"] option[value*="' + currentDateRangeQuery + '"]').attr("selected", "selected");
        } else {
          $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-lower"] option:first').attr("selected", "selected");
        }

        if ($('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-upper"] option[value*="' + currentDateRangeQuery + '"]').length) {
          $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-upper"] option[value*="' + currentDateRangeQuery + '"]').attr("selected", "selected");
        } else {
          $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-upper"] option:last').attr("selected", "selected");
        }

        $('select[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-upper"] option').each(function () {
          if ($(this).text() < $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-lower"] option:selected').text()) {
            $(this).remove();
          }
        });

        $('select[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-lower"] option').each(function () {
          if ($(this).text() > $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-upper"] option:selected').text()) {
            $(this).remove();
          }
        });


      } else {

        $('select[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-"]').each(function () {
          //$(this).find('option').get(0).remove();
          $(this).children().first().remove();
        });
        $('ul[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-"]').each(function () {
          //$(this).find('li').get(0).remove();
          $(this).children().first().remove();
        });

        $('select[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-lower"] option').each(function () {
          $(this).attr('value', $(this).attr('value').replace(/%2Cmax%3A\d+%29/, '%2Cmax%3A' + max + '%29'));
          $(this).text($(this).text().replace('(0)', ''));
        });

        $('select[data-drupal-facet-id^="year_data_collected_taxonomy_term_name-upper"] option').each(function () {
          $(this).attr('value', $(this).attr('value').replace(/%28min%3A\d+%2C/, '%28min%3A' + min + '%2C'));
          $(this).text($(this).text().replace('(0)', ''));
        });

        $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-lower"] option:first').attr("selected", "selected");
        $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-upper"] option:last').attr("selected", "selected");

      }

    }

    function getDateRange(sParam, limit) {
      var sPageURL = window.location.search.substring(1);
      var sURLVariables = sPageURL.split('&');
      for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[1].startsWith(sParam)) {
          if (limit == 1) {
            return decodeURIComponent(sParameterName[1]).split(':')[2].split(',')[0];
          } else if (limit == 2) {
            return decodeURIComponent(sParameterName[1]).split(':')[3].split(')')[0];
          } else {
            return null;
          }
        }
      }
    }

  });
})(jQuery);

// JS code end - for date range dropdown on search page


// JS code start - for sorting, # of results, and fulltext search box on search page
(function ($) {
  $(function () {

    function urlParameters() {
      var urlParams = [];
      if (window.location.search != '') {
        var sPageURL = window.location.search.substring(1);
        urlParams = sPageURL.split("&").map(function (k) {
          return k.split("=", 2);
        });
      }
      return urlParams;
    }

    function submitAjaxQuery(query) {
      var url = window.location.pathname + '?' + query;
      var $widget = $('ul.js-facets-widget:first');
      $widget.trigger('facets_filter', [url]);
    }

    var searchFlag;
    var resetElementID = "reset-search-filters";

    function removeFacetParameter(url, param) {
      var urlArray = url.split("?");
      var newParameter = "";
      var updatedURL = urlArray[0];
      var currentParameter = urlArray[1];
      var temp = "";
      if (currentParameter) {
        var paramArray = currentParameter.split("&");
        for (var i = 0; i < paramArray.length; i++) {
          if (paramArray[i].split('=')[0].substring(0, param.length) != param) {
            newParameter += temp + paramArray[i];
            temp = "&";
          }
        }
      }
      if (newParameter) {
        updatedURL += "?" + newParameter;
      }
      return updatedURL;
    }

    $(document).ready(function () {

      $('#ifrm').on('load', function (e) {

        $("#ifrm").contents().find('a').click(function (e) {

          e.preventDefault();
          $('#ifrm').css('height', '1050px');
          $("#ifrm").attr('src', this.href);

        });

      });

      setBackLink();

      searchFlag = false;

      if (typeof Drupal.facets != "undefined") {

        // if ($('.facets-widget-checkbox input:checked').length > 0 || $('#edit-keys--2').val().length > 0 || $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-lower'] option:selected").index() > 0 || $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option:selected").index() < $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option").length - 1) {

        //   $('#reset-search-filters').show();
        //   $('#reset-search-filters').click(function () {
        //     window.location.href = window.location.pathname + "?sort_bef_combine=field_date_printed_on_report_DESC&items_per_page=15";
        //     //window.location.href = "./all-reports?sort_bef_combine=field_date_printed_on_report_DESC&items_per_page=15";
        //     //window.history.replaceState({}, '', '/data');
        //   });
        // } else {
        //   $('#reset-search-filters').hide();
        // }

        // filter reset button
        if ($("#" + resetElementID).length) {

          var newURL = removeFacetParameter(window.location.href, "f%5B");

          if (window.location.href != newURL) {
            $("#" + resetElementID).show();
            $("#" + resetElementID).on("click", function () {
              window.location = newURL;
            });
          } else {
            $("#" + resetElementID).hide();
          }
        }

        $("#edit-sort-bef-combine--2").children('option[value="search_api_relevance_ASC"]').remove();
        $("#edit-sort-bef-combine--2").children('option[value="search_api_relevance_DESC"]').text('Relevance');
        $("#edit-sort-bef-combine--2").children('option[value="field_date_printed_on_report_ASC"]').text('Date - oldest first');
        $("#edit-sort-bef-combine--2").children('option[value="field_date_printed_on_report_DESC"]').text('Date - newest first');
        $("#edit-sort-bef-combine--2").children('option[value="title_ASC"]').text('Alphabetical A-Z');
        $("#edit-sort-bef-combine--2").children('option[value="title_DESC"]').text('Alphabetical Z-A');

        $('#block-exposedformsolr-search-contentpage #edit-submit-solr-search-content--2').off('click').click(function (e) {

          e.preventDefault();

          var param = urlParameters();

          var searchKeywords = $('#edit-keys--2').val();

          searchKeywords = searchKeywords.trim();

          // if (param.findIndex((obj => obj[0] == 'page')) >= 0) {
          //     param.splice(param.findIndex((obj => obj[0] == 'page')), 1);
          // }

          "use strict";

          if (param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param.splice(param.findIndex(function (obj) {
              return obj[0] == 'page';
            }), 1);
          }

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'keys')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'keys'))][1] = searchKeywords;
          // } else {
          //     param.push(['keys', searchKeywords]);
          // }

          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'keys';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'keys';
            })][1] = searchKeywords;
          } else {
            param.push(['keys', searchKeywords]);
          }

          var sortOption = $('select#edit-sort-bef-combine--2 option:checked').val().replace(' ', '+');
          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'sort_bef_combine';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'sort_bef_combine';
            })][1] = sortOption;
          } else {
            param.push(['sort_bef_combine', sortOption]);
          }

          //var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);

        });

        $('select#edit-items-per-page--2').on('change', function (e) {

          e.preventDefault();

          var param = urlParameters();

          var itemsPerPage = $('select#edit-items-per-page--2 option:checked').val();

          // if (param.findIndex((obj => obj[0] == 'page')) >= 0) {
          //     param.splice(param.findIndex((obj => obj[0] == 'page')), 1);
          // }

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'items_per_page')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'items_per_page'))][1] = itemsPerPage;
          // } else {
          //     param.push(['items_per_page', itemsPerPage]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');

          if (param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param.splice(param.findIndex(function (obj) {
              return obj[0] == 'page';
            }), 1);
          }

          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'items_per_page';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'items_per_page';
            })][1] = itemsPerPage;
          } else {
            param.push(['items_per_page', itemsPerPage]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);

        });

        $('select#edit-sort-bef-combine--2').on('change', function (e) {

          e.preventDefault();

          var param = urlParameters();

          var sortOption = $('select#edit-sort-bef-combine--2 option:checked').val();
          // if (param.findIndex((obj => obj[0] == 'page')) >= 0) {
          //     param.splice(param.findIndex((obj => obj[0] == 'page')), 1);
          // }

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'sort_bef_combine')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'sort_bef_combine'))][1] = sortOption;
          // } else {
          //     param.push(['sort_bef_combine', sortOption]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          if (param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param.splice(param.findIndex(function (obj) {
              return obj[0] == 'page';
            }), 1);
          }

          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'sort_bef_combine';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'sort_bef_combine';
            })][1] = sortOption;
          } else {
            param.push(['sort_bef_combine', sortOption]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);

        });

        $('div.pagerer-container a').off('click').click(function (e) {
          e.preventDefault();
        });

        $('div.pagerer-container a[title="Go to next page"]').off('click').click(function (e) {
          e.preventDefault();
          var param = urlParameters();

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'page')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'page'))][1] = +param[param.findIndex((obj => obj[0] == 'page'))][1] + 1;
          // } else {
          //     param.push(['page', 1]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] = +param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] + 1;
          } else {
            param.push(['page', 1]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);
        });

        $('div.pagerer-container a[title="Go to previous page"]').off('click').click(function (e) {
          e.preventDefault();
          var param = urlParameters();

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'page')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'page'))][1] = +param[param.findIndex((obj => obj[0] == 'page'))][1] - 1;
          // } else {
          //     param.push(['page', 0]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] = +param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] - 1;
          } else {
            param.push(['page', 0]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);
        });

        $('div.pagerer-container a[title="Go to last page"]').off('click').click(function (e) {
          e.preventDefault();
          var param = urlParameters();
          var totalPage = $('div.pagerer-container li.pager__item.pagerer-suffix span').text().replace('of ', '');

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'page')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'page'))][1] = +totalPage - 1;
          // } else {
          //     param.push(['page', +totalPage - 1]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] = +totalPage - 1;
          } else {
            param.push(['page', +totalPage - 1]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);
        });

        $('div.pagerer-container a[title="Go to first page"]').off('click').click(function (e) {
          e.preventDefault();
          var param = urlParameters();

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'page')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'page'))][1] = 0;
          // } else {
          //     param.push(['page', 0]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] = 0;
          } else {
            param.push(['page', 0]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);
        });


        if ($('#edit-keys--2').val().length > 0) {
          $('#all_reports_keyword_title span.keyword').text('"' + $('#edit-keys--2').val() + '"');
          $('#all_reports_keyword_title').show();
        } else {
          $('#all_reports_keyword_title span.keyword').text('');
          $('#all_reports_keyword_title').hide();
        }

        // Bind a new keypress event (for enter key) on the search box.
        $('#edit-keys--2').bind("enterKey", function (e) {
          // If user clicks on the enter key while in the searchbox, the autocomplete list will be dismissed.
          $('ul#ui-id-1').css("display", "none");
        });
        $('#edit-keys--2').keyup(function (e) {
          if (e.keyCode == 13) {
            $(this).trigger("enterKey");
          }
        });

        var checkedFacets = '';

        if ($("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-lower'] option:selected").index() > 0 || $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option:selected").index() < $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option").length - 1) {

          var dateRange = $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-lower"] option:selected').text() + ' - ' + $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-upper"] option:selected').text();
          //checkedFacets = '<a class="selected-date-range" href="#">' + dateRange + '</a>  ';
          checkedFacets = '<div class="facet-selected">' + dateRange + '<a class="selected-facet selected-date-range" href="#">' + '<span class="sr-only">close this facet</span>' + ' X ' + '</a></div>  ';

        }

        if ($('.facets-widget-checkbox input:checked').length > 0) {

          $('.facets-widget-checkbox input:checked').each(function () {
            var facetTitle = $("h2", $(this).closest("div.block-facets-ajax")).text();
            if (facetTitle.indexOf('Report Type') > -1) {
              facetTitle = 'Report Type';
            }
            if (checkedFacets == '') {
              //checkedFacets = facetTitle + ': ' + $(this).next().children('span.facet-item__value').html();
              checkedFacets = '<div class="facet-selected">' + $(this).next().children('span.facet-item__value').html() + '<a class="selected-facet" href="' + $(this).attr('id') + '">' + '<span class="sr-only">close this facet</span>' + ' X ' + '</a></div>  ';
            } else {
              //checkedFacets += ', ' + facetTitle + ': ' + $(this).next().children('span.facet-item__value').html();
              checkedFacets += checkedFacets = '<div class="facet-selected">' + $(this).next().children('span.facet-item__value').html() + '<a class="selected-facet" href="' + $(this).attr('id') + '">' + '<span class="sr-only">close this facet</span>' + ' X ' + '</a></div>  ';
            }
          });

        }

        if (checkedFacets != '') {
          $('#all_reports_facet_selected span.facet-filters').html(checkedFacets);
          $(".view-solr-search-content .view-content").toggleClass("margin-view-content");
          $('#all_reports_facet_selected span.facets-label').show();
          $('#all_reports_facet_selected').show();
        } else if ($('#edit-keys--2').val().length > 0) {
          $('#all_reports_facet_selected span.facets-label').hide();
          $(".view-solr-search-content .view-content").toggleClass("margin-view-content");
          $('#all_reports_facet_selected').show();
          var as = 1;
        } else {
          $('#all_reports_facet_selected span.facet-filters').html('');
          $('#all_reports_facet_selected').hide();
        }

      }

      $('form.views-exposed-form.bef-exposed-form').submit(function () {
        if ($('#edit-keys').length && $('#edit-keys').val().length == 0) {
          $("#edit-sort-bef-combine").children('option[value="field_date_printed_on_report_DESC"]').attr("selected", "selected");
        }
        if ($('#edit-keys--2').length && $('#edit-keys--2').val().length == 0) {
          $("#edit-sort-bef-combine--2").children('option[value="field_date_printed_on_report_DESC"]').attr("selected", "selected");
        }
      });

      $('span.facet-filters a.selected-facet:not(.selected-date-range)').on('click', function (e) {
        e.preventDefault();
        $('#' + $(this).attr('href')).trigger('click');
      });

      $('span.facet-filters a.selected-date-range').on('click', function (e) {
        e.preventDefault();

        // $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-lower']").val($("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-lower'] option:first").val());
        // $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper']").val($("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option:last").val());

        var param = urlParameters();

        // if (param.findIndex(obj => obj[1].includes('year_data_collected_taxonomy_term_name')) >= 0) {
        //     param.splice(param.findIndex(obj => obj[1].includes('year_data_collected_taxonomy_term_name')), 1);
        // }

        // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');

        if (param.findIndex(function (obj) {
          return obj[1].indexOf('year_data_collected_taxonomy_term_name');
        }) >= 0) {
          param.splice(param.findIndex(function (obj) {
            return obj[1].indexOf('year_data_collected_taxonomy_term_name') > -1;
          }), 1);
        }

        var query = Object.keys(param).map(function (k) {
          return param[k][0] + '=' + param[k][1];
        }).join('&');

        submitAjaxQuery(query);

      });


    });

    $(document).ajaxComplete(function (event, xhr, settings) {

      if (settings.url.indexOf('all-reports') > 0) {

        searchFlag = true;

      }

    });

    $(document).ajaxStart(function () {
      $('#searchProcessing').show();
    });

    $(document).ajaxStop(function () {

      if (typeof Drupal.facets != "undefined") {

        $('#searchProcessing').hide();

        // if ($('.facets-widget-checkbox input:checked').length > 0 || $('#edit-keys--2').val().length > 0 || $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-lower'] option:selected").index() > 0 || $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option:selected").index() < $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option").length - 1) {

        //   $('#reset-search-filters').show();
        //   $('#reset-search-filters').click(function () {
        //     window.location.href = window.location.pathname + "?sort_bef_combine=field_date_printed_on_report_DESC&items_per_page=15";
        //     //window.location.href = "/all-reports?sort_bef_combine=field_date_printed_on_report_DESC&items_per_page=15";
        //     //window.history.replaceState({}, '', '/data');
        //   });
        // } else {
        //   $('#reset-search-filters').hide();

        // }

        // filter reset button

        if ($("#" + resetElementID).length) {

          var newURL = removeFacetParameter(window.location.href, "f%5B");

          if (window.location.href != newURL) {
            $("#" + resetElementID).show();
            $("#" + resetElementID).on("click", function () {
              window.location = newURL;
            });
          } else {
            $("#" + resetElementID).hide();
          }
        }

        if (typeof searchFlag !== 'undefined' && searchFlag) {

          if ($('#edit-keys--2').val().length > 0) {
            $('#all_reports_keyword_title span.keyword').text('"' + $('#edit-keys--2').val() + '"');
            $('#all_reports_keyword_title').show();
          } else {
            $('#all_reports_keyword_title span.keyword').html('');
            $('#all_reports_keyword_title').hide();
          }

          var checkedFacets = '';

          if ($("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-lower'] option:selected").index() > 0 || $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option:selected").index() < $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option").length - 1) {

            var dateRange = $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-lower"] option:selected').text() + ' - ' + $('select[data-drupal-facet-id="year_data_collected_taxonomy_term_name-upper"] option:selected').text();
            //checkedFacets = '<a class="selected-date-range" href="#">' + dateRange + '</a>  ';
            checkedFacets = '<div class="facet-selected">' + dateRange + '<a class="selected-facet selected-date-range" href="#">' + '<span class="sr-only">close this facet</span>' + ' X ' + '</a></div>  ';

          }


          if ($('.facets-widget-checkbox input:checked').length > 0) {

            $('.facets-widget-checkbox input:checked').each(function () {
              var facetTitle = $("h2", $(this).closest("div.block-facets-ajax")).text();
              if (facetTitle.indexOf('Report Type') > -1) {
                facetTitle = 'Report Type';
              }
              if (checkedFacets == '') {
                //checkedFacets = facetTitle + ': ' + $(this).next().children('span.facet-item__value').html();
                checkedFacets = '<div class="facet-selected">' + $(this).next().children('span.facet-item__value').html() + '<a class="selected-facet" href="' + $(this).attr('id') + '">' + '<span class="sr-only">close this facet</span>' + ' X ' + '</a></div>  ';
              } else {
                //checkedFacets += ', ' + facetTitle + ': ' + $(this).next().children('span.facet-item__value').html();
                checkedFacets += checkedFacets = '<div class="facet-selected">' + $(this).next().children('span.facet-item__value').html() + '<a class="selected-facet" href="' + $(this).attr('id') + '">' + '<span class="sr-only">close this facet</span>' + ' X ' + '</a></div>  ';
              }
            });

          }

          if (checkedFacets != '') {
            $('#all_reports_facet_selected span.facet-filters').html(checkedFacets);
            $(".view-solr-search-content .view-content").toggleClass("margin-view-content");
            $('#all_reports_facet_selected span.facets-label').show();
            $('#all_reports_facet_selected').show();
          } else if ($('#edit-keys--2').val().length > 0) {
            $('#all_reports_facet_selected span.facets-label').hide();
            $(".view-solr-search-content .view-content").toggleClass("margin-view-content");
            $('#all_reports_facet_selected').show();
          } else {
            $('#all_reports_facet_selected span.facet-filters').html('');
            $('#all_reports_facet_selected').hide();
          }

          $('span.facet-filters a.selected-facet:not(.selected-date-range)').on('click', function (e) {
            e.preventDefault();
            $('#' + $(this).attr('href')).trigger('click');
          });

          $('span.facet-filters a.selected-date-range').on('click', function (e) {
            e.preventDefault();

            // $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-lower']").val($("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-lower'] option:first").val());
            // $("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper']").val($("select[data-drupal-facet-id='year_data_collected_taxonomy_term_name-upper'] option:last").val());

            var param = urlParameters();

            // if (param.findIndex(obj => obj[1].includes('year_data_collected_taxonomy_term_name')) >= 0) {
            //     param.splice(param.findIndex(obj => obj[1].includes('year_data_collected_taxonomy_term_name')), 1);
            // }

            // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');

            if (param.findIndex(function (obj) {
              return obj[1].indexOf('year_data_collected_taxonomy_term_name');
            }) >= 0) {
              param.splice(param.findIndex(function (obj) {
                return obj[1].indexOf('year_data_collected_taxonomy_term_name') > -1;
              }), 1);
            }

            var query = Object.keys(param).map(function (k) {
              return param[k][0] + '=' + param[k][1];
            }).join('&');

            submitAjaxQuery(query);

          });

          searchFlag = false;

        }

        $('div.pagerer-container a').off('click').click(function (e) {
          e.preventDefault();
        });

        $('div.pagerer-container a[title="Go to next page"]').off('click').click(function (e) {
          e.preventDefault();
          var param = urlParameters();

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'page')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'page'))][1] = +param[param.findIndex((obj => obj[0] == 'page'))][1] + 1;
          // } else {
          //     param.push(['page', 1]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] = +param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] + 1;
          } else {
            param.push(['page', 1]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);
        });

        $('div.pagerer-container a[title="Go to previous page"]').off('click').click(function (e) {
          e.preventDefault();
          var param = urlParameters();

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'page')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'page'))][1] = +param[param.findIndex((obj => obj[0] == 'page'))][1] - 1;
          // } else {
          //     param.push(['page', 0]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] = +param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] - 1;
          } else {
            param.push(['page', 0]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);
        });

        $('div.pagerer-container a[title="Go to last page"]').off('click').click(function (e) {
          e.preventDefault();
          var param = urlParameters();
          var totalPage = $('div.pagerer-container li.pager__item.pagerer-suffix span').text().replace('of ', '');

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'page')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'page'))][1] = +totalPage - 1;
          // } else {
          //     param.push(['page', +totalPage - 1]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] = +totalPage - 1;
          } else {
            param.push(['page', +totalPage - 1]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);
        });

        $('div.pagerer-container a[title="Go to first page"]').off('click').click(function (e) {
          e.preventDefault();
          var param = urlParameters();

          // if ((param.length > 0) && (param.findIndex((obj => obj[0] == 'page')) >= 0)) {
          //     param[param.findIndex((obj => obj[0] == 'page'))][1] = 0;
          // } else {
          //     param.push(['page', 0]);
          // }

          // var query = Object.keys(param).map(k => param[k][0] + '=' + param[k][1]).join('&');
          if (param.length > 0 && param.findIndex(function (obj) {
            return obj[0] == 'page';
          }) >= 0) {
            param[param.findIndex(function (obj) {
              return obj[0] == 'page';
            })][1] = 0;
          } else {
            param.push(['page', 0]);
          }

          var query = Object.keys(param).map(function (k) {
            return param[k][0] + '=' + param[k][1];
          }).join('&');

          submitAjaxQuery(query);
        });

      }

    });

    function setBackLink() {

      var backLink = document.getElementById("lnkBackLink");
      var referrer = document.referrer;

      var v1 = backLink;
      var v2 = referrer.length;
      var v3 = referrer.indexOf('/all-reports');

      if (backLink != null && referrer.length > 0 && referrer.indexOf('/all-reports') > 0) {

        backLink.classList.add("go-back-to-search");
        backLink.innerHTML = '<a href="' + referrer + '" title="Return to the referring results page">« Back to Search Results</a>';

      } else if (backLink != null && referrer.length > 0 && referrer.indexOf('/data-we-collect') > 0) {

        backLink.classList.add("go-back-to-data-source");
        backLink.innerHTML = '<a href="' + referrer + '" title="Return to the referring data source page">« Back to Data We Collect</a>';

      }

    }

  });
})(jQuery);

// JS code end - for sorting, # of results, and fulltext search box on search page