/**
 * @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.
 */



// 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) {


    var execute_sfa_page_flag_once = true ;

    function getUrlParams( prop ) {
        var params = {};
        var search = decodeURIComponent( window.location.href.slice( window.location.href.indexOf( '?' ) + 1 ) );
        var definitions = search.split( '&' );

        definitions.forEach( function( val, key ) {
            var parts = val.split( '=', 2 );
            params[ parts[ 0 ] ] = parts[ 1 ];
        } );

        return ( prop && prop in params ) ? params[ prop ] : params;
    }

Drupal.behaviors.nhlbi_science_filters = {

    attach: function (context) {
      if (typeof window.actions == 'undefined') {
        window.actions = new Array();
      }
      if (typeof window.actions['filter']['all_science'] == 'undefined') {
        window.actions['filter']['all_science'] = 0;
      }

      function clear_url_parameters() {
        var uri = window.location.toString();
        if (uri.indexOf("?") > 0) {
          var clean_uri = uri.substring(0, uri.indexOf("?"));
          window.history.replaceState({}, document.title, clean_uri);
        }
      }

      //var serializedSFAFilter = '';
      function nhlbi_science_ajax_trigger_submit() {
        window.actions['filter']['all_science']++;
        clear_url_parameters();

        if ($('#edit-sfa-options input:checked').length > 0
          || $('#edit-division-options input:checked').length
          || $('.searchbar-text-button #edit-name')[0].value.length > 1) {
          $('#filter_results_wrapper').css("visibility", "hidden");
          // $('#filter_results_wrapper').html('');
          $('#edit-filter-ajax-submit').trigger('mousedown');

          // alert(serializedForm);
          //$('.views-element-container .view-nhlbi-all-science').slideUp(1000);
          $('.views-element-container .view-nhlbi-all-science').css("visibility", "hidden");

        }
        else {
          $('.views-element-container .view-nhlbi-all-science').css("visibility", "visible");
          $('.views-element-container .view-nhlbi-all-science').show("slide", {direction: "down"}, 500);
          $('#filter_results_wrapper').html('');
        }
      }


      $("#edit-add-other-filters").click(function () {
        $(".filters-lightbox-buttons-wrapper").show();
        // $( ".filters-lightbox-buttons" ).css("top",  150);
      });

      $(".filters-lightbox-buttons #sfa-button").click(function () {
        $(".filters-lightbox-buttons-wrapper").hide();
        $("#sfa_filter").hide();
        $(".filters-wrapper-lightbox").show();
        $("#sfa_filter").show(250);
        $("#division_filter").hide();
        // $( ".filters-wrapper" ).css("top",  150);
      });


      $(".filters-lightbox-buttons #division-button").click(function () {
        $(".filters-lightbox-buttons-wrapper").hide();
        $(".filters-wrapper-lightbox").show();
        $("#division_filter").show();
        $("#sfa_filter").hide();
        // $( ".filters-wrapper" ).css("top",  150);
      });

      $("#sfa-selected-filters").click(function (e) {
        if (e.target.className != "selected-filter-options") return;
        $(".filters-lightbox-buttons-wrapper").hide();
        $(".filters-wrapper-lightbox").show();
        $("#sfa_filter").show();
        $("#division_filter").hide();
        // $( ".filters-wrapper" ).css("top",  150);
      });


      $("#division-selected-filters").click(function (e) {
        if (e.target.className != "selected-filter-options") return;
        $(".filters-lightbox-buttons-wrapper").hide();
        $(".filters-wrapper-lightbox").show();
        $("#division_filter").show();
        $("#sfa_filter").hide();
        //$( ".filters-wrapper" ).css("top",  150);
      });

      $(".close-button").click(function () {
        $(".filters-lightbox-buttons-wrapper").hide();
        $(".filters-wrapper-lightbox").hide();

        // Deal with SFA checkboxes by looking at values from local storage.
        const sfaQuery = localStorage.getItem('serializedSFAFilter');
        const sfaParams = new URLSearchParams(sfaQuery);
        $('#edit-sfa-options input:checked').each(
          function (key, element) {
            if (!sfaParams.has(element.name)) {
              element.checked = false;
            }
          }
        );

        const selectedDivisions = $('#selected-divisions').data('values');
        $('#edit-division-options input:checked').each(
          function (key, element) {
            if (typeof selectedDivisions == 'undefined' || !selectedDivisions.includes(element.name)) {
              element.checked = false;
            }
          }
        );
      });


      //localStorage.setItem('serializedSFAFilter','');

      $("#edit-done-button").click(function (e) {
        e.preventDefault();
        var serializedSFAFilterNew = $('#edit-sfa-options').serialize();
        var serializedSFAFilterOld = localStorage.getItem('serializedSFAFilter');
        $(".filters-lightbox-buttons-wrapper").hide();
        $(".filters-wrapper-lightbox").hide();
        //  alert(serializedSFAFilterOld);
        //  alert(serializedSFAFilterNew);
        // if(serializedSFAFilterOld == serializedSFAFilterNew && !( serializedSFAFilterOld == '' && serializedSFAFilterNew == '')){
        //     return false;
        // }else
        {
          //#division-selected-filters:not(:first-child) .selected-filter-options
          localStorage.setItem('serializedSFAFilter', serializedSFAFilterNew);
          var sfa_concat_string = '';
          var first = true;
          var prefix = ''
          $('#edit-sfa-options input:checked').each(function (i) {
            if (first == false) {
              prefix = ', ';
            }
            first = false;
            sfa_concat_string = sfa_concat_string + prefix + this.dataset.shortTitle;
          });

          if (first == false) {
            $("#sfa-selected-filters").html('<div  style="display:none" class="selected-filter-options">' + sfa_concat_string + '<span class="delete-sfa-filter"></span></div>');
            //$('.selected-filter-options').hide();
            $('.selected-filter-options').show('slow');


          }
          else {
            $("#sfa-selected-filters").html('');
          }


          // $('#edit-filter-ajax-submit').trigger('mousedown');
          nhlbi_science_ajax_trigger_submit();
        }

      });


      $("#edit-done-button-division").click(function (e) {
        e.preventDefault();
        $(".filters-lightbox-buttons-wrapper").hide();
        $(".filters-wrapper-lightbox").hide();
        //
        var division_concat_string = '';
        var first = true;
        var prefix = ''
        var divisions = new Array();
        $('#edit-division-options input:checked').each(function (i) {
          if (first == false) {
            prefix = ', ';
          }
          first = false;
          division_concat_string = division_concat_string + prefix + this.dataset.shortTitle;
          divisions.push(this.name);
        });

        if (first == false) {
          $("#division-selected-filters").html('<div id="selected-divisions" data-values="' + divisions.join('|') + '" style="display:none" class="selected-filter-options">' + division_concat_string + '<a class="delete-division-filter"></a></div>');
          $('.selected-filter-options').show('slow');
        }
        else {
          $("#division-selected-filters").html('');
        }

        // $('#edit-filter-ajax-submit').trigger('mousedown');

        nhlbi_science_ajax_trigger_submit();

      });


      $(document).on("click", ".delete-sfa-filter", function (e) {
        e.preventDefault();
        $('#edit-sfa-options input').removeAttr('checked');
        //$("#sfa-selected-filters").hide("slide", { direction: "left" }, 1000);
        //$(".selected-filter-options").slideUp();
        $("#sfa-selected-filters .selected-filter-options").hide("slide", {direction: "left"}, 500);
        $("#sfa-selected-filters").html('');
        nhlbi_science_ajax_trigger_submit();
      });
      $(document).on("click", ".delete-division-filter", function (e) {
        e.preventDefault();
        $('#edit-division-options input').removeAttr('checked');
        $("#division-selected-filters .selected-filter-options").hide("slide", {direction: "left"}, 1000);
        $("#division-selected-filters").html('');
        nhlbi_science_ajax_trigger_submit();
      });


      $(document).on("click", "#text-input-cross", function (e) {
        e.preventDefault();
        $('#edit-name').val('');
        nhlbi_science_ajax_trigger_submit();
      });


      /*    $( "#clear-all a" ).click(function(e) {
              e.preventDefault();
              $("#sfa-selected-filters").html('');
              $("#division-selected-filters").html('');
              $('#edit-sfa-options input').removeAttr('checked');
              $('#edit-division-options input').removeAttr('checked');
              $('#edit-name').val('');
              $('.views-element-container .view-nhlbi-all-science').css("visibility", "visible");
              $('.views-element-container .view-nhlbi-all-science').show();
              $('#filter_results_wrapper').html('');
          });

  */

      $(document).ajaxComplete(function (e, xhr, settings) {
        var url = settings.url;
        var prefix = '/science/all-science'
        if (url.lastIndexOf(prefix, 0) == 0) {
          // $('.views-element-container .view-nhlbi-all-science').css("visibility", "visible");
          $('.views-element-container .view-nhlbi-all-science').slideUp(500);

        }
      });


      var discardKeyCode = [
        16, // shift
        17, // ctrl
        18, // alt
        20, // caps lock
        33, // page up
        34, // page down
        35, // end
        36, // home
        37, // left arrow
        38, // up arrow
        39, // right arrow
        40, // down arrow
        9, // tab
        13, // enter
        27  // esc
      ];
      var befTimeoutID = 0;
      //var befSearchString = '';
      // Don't wait for change event on textfields.
      $(once('nhlbi-auto-submit', '.nhlbi-searchbar #edit-name', context)).each(function (context) {
        $(this).bind('keydown keyup', function (e) {
          if (e.keyCode == 13) {
            e.preventDefault();
            if (this.value != undefined & this.value.length > 1) {
              //befSearchString = this.value;
              befTimeoutID = setTimeout($.proxy(nhlbi_science_ajax_trigger_submit), 500);
            }
          }

          if ($.inArray(e.keyCode, discardKeyCode) === -1) {
            befTimeoutID && clearTimeout(befTimeoutID);
          }
        })

        .keyup(function (e) {

          if ($.inArray(e.keyCode, discardKeyCode) === -1) {
            if (this.value != undefined & this.value.length > 1) {
              // befSearchString = this.value;
              befTimeoutID = setTimeout($.proxy(nhlbi_science_ajax_trigger_submit), 1000);
              $('#text-input-cross').show();
            }
            else if (this.value.length < 2) {
              //befSearchString = this.value;
              befTimeoutID = setTimeout($.proxy(nhlbi_science_ajax_trigger_submit), 1000);
            }
          }
        });
    });

        var nid  = getUrlParams("field_related_sfas_target_id");
        if(execute_sfa_page_flag_once && nid > 0 ) {

            $("#edit-field-related-sfas-target-id-" + nid).trigger('click');
            $("#edit-done-button").trigger('click');
            execute_sfa_page_flag_once =  false;
        }


    }


}



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

//"field_related_sfas_target_id%5B270%5D=1&field_related_sfas_target_id%5B271%5D=1"
//"field_related_sfas_target_id%5B270%5D=1&field_related_sfas_target_id%5B271%5D=1"