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


    Drupal.behaviors.accordions = {
        attach: function(context) {
            //Refreshes the filter window
            function refreshFilterWindow(){
                $( ".ui-accordion-content" ).css('height','100%');
            }
            var addEventListener = (function() {
                if(document.addEventListener) {
                    return function(element, event, handler) {
                        element.addEventListener(event, handler, false);
                    };
                }
                else {
                    return function(element, event, handler) {
                        element.attachEvent('on' + event, handler);
                    };
                }
            }());

            addEventListener(window, 'load', activateAccordion);
            addEventListener(window, 'hashchange', activateAccordion);

            function activateAccordion (){
                //close any active accordion
                $('.general-accordion, .primary-accordion, .secondary-accordion, .supplemental-accordion, .subAccordion, .subSecondAccordion, .subThirdAccordion').accordion({
                    active: false,
                    collapsible: true
                });


                var hash = window.location.hash.substring(1);
                if(hash) {
                    var activeHeaderId = '#' + hash;
                    var position;
                      //Double (nested) accordion (Secondary -> primary accordion)
                      if($(activeHeaderId).parents(".primary-accordion").parents('.ui-corner-bottom').prevAll("h3.ui-accordion-header:first, div.ui-accordion-header:first").hasClass("ui-accordion-header")){
                          $(activeHeaderId).parents(".primary-accordion").parents('.ui-corner-bottom').prevAll("h3.ui-accordion-header:first, div.ui-accordion-header:first").trigger("click");
                          $(activeHeaderId).trigger("click");
                      }
                      //Double (nested) accordion (primary -> sub accordion)
                      else if($(activeHeaderId).parents('.ui-corner-bottom').prevAll("h3.ui-accordion-header:first, div.ui-accordion-header:first").hasClass("ui-accordion-header") && $(activeHeaderId).nextAll('.subAccordion:first')){
                          $(activeHeaderId).parents('.ui-corner-bottom').prevAll("h3.ui-accordion-header:first, div.ui-accordion-header:first ").trigger("click");
                          $(activeHeaderId).trigger("click");
                      }
                      //single layer accordion
                      else if ($(activeHeaderId).parents('.ui-corner-bottom').prevAll("h3.ui-accordion-header:first, div.ui-accordion-header:first").hasClass("ui-accordion-header") && !$(activeHeaderId).parents('.subAccordion').hasClass('subAccordion')){
                          $(activeHeaderId).parents('.ui-corner-bottom').prevAll("h3.ui-accordion-header:first, div.ui-accordion-header:first ").trigger("click");
                      }
                      //Double (nested) accordion
                      else if ($(activeHeaderId).parents('.subAccordion, .subSecondAccordion').prevAll("h3.ui-accordion-header:first").hasClass("ui-accordion-header")){
                          $(activeHeaderId).parents(".ui-corner-bottom").parents(".ui-corner-bottom").prevAll("h3.accordion-header:first, div.accordion-header-secondary:first").trigger("click");
                          $(activeHeaderId).parents('.subAccordion, .subSecondAccordion, .subAccordionContainer').prevAll("h3.ui-accordion-header:first").trigger("click");
                      }
                      else{
                        if($(activeHeaderId).hasClass("ui-accordion-header")){
                          $(activeHeaderId).trigger("click");
                        }
                      }

                    if(window.history.pushState) {
                        window.history.pushState('', '/', window.location.pathname)
                    } else {
                        window.location.hash = '';
                    }

                    if($(activeHeaderId).parentsUntil(".bodytext").hasClass("small-only")){
                        // any table structure produces two anchor tags with same id, one under small-only and another one under large-only. Target the large-only, otherwise, it will scroll all the way to top
                        activateHeaderId(activeHeaderId,2);
                        return;
                    }
                    activateHeaderId(activeHeaderId,1);
                    return;
                }
            }

            function activateHeaderId(activeHeaderId, numb){
              if(numb === 1){
                position = $(activeHeaderId).first().offset().top;
              } else {
                position = $(activeHeaderId).parents('.small-only').nextAll("table.large-only:first").find(activeHeaderId).offset().top;
              }
              setTimeout(function () {
                      $('html, body').animate({
                          scrollTop: position - 180
                          //: theOffset.top -100
                      }, '1000');
              }, 180);
            }

            //Defines the Accordion which contains all of the filters

            // fix the case where it scrolls all the way up when clicking the empty side of the accordion
            //Defines the Accordion which contains all of the filters
            $('.general-accordion, .primary-accordion, .secondary-accordion, .supplemental-accordion, .subAccordion, .subSecondAccordion, .subThirdAccordion').bind('click',function(evt){
                accordion_helper(evt);
                Drupal.blazy.init.revalidate();
            });
            function accordion_helper(evt){
                var clicked = evt.target;

                if ($(clicked).hasClass("ui-accordion-header") || $(clicked).hasClass("ui-icon") || $(clicked).hasClass("field--name-field-panel-title") || $(clicked).hasClass("field--name-field-display-title")){
                  setTimeout(function(){
                    $('html, body').animate({
                      scrollTop: $(clicked).offset().top - 180
                                  //: theOffset.top -100
                                }, '5000');
                      }, 180);
                    return;
                }
            }

            $( ".general-accordion" ).accordion({
                active: false,
                autoheight:true,
                header: ".accordion-header",
                animate:200,
                collapsible: true,
                heightStyle:'content',
                icons: {"header":"view-filter-ui-icon-down",
                    "activeHeader":"view-filter-ui-icon-up"},
                create: function(event,ui){
                },
                activate: function(event,ui){
                    $('.readMore').addClass('hidden');
                    $('.readMoreLink, .readMoreButton').removeClass('hidden');
                    refreshFilterWindow();
                }
            });

            $( ".primary-accordion" ).accordion({
                active: false,
                autoheight:true,
                header: ".accordion-header",
                animate:200,
                collapsible: true,
                heightStyle:'content',
                icons: {"header":"view-filter-ui-icon-down",
                    "activeHeader":"view-filter-ui-icon-up"},
                create: function(event,ui){
                },
                activate: function(event,ui){
                    $('.readMore').addClass('hidden');
                    $('.readMoreLink, .readMoreButton').removeClass('hidden');
                    refreshFilterWindow();
                }
            });

            $( ".clinical-accordion" ).accordion({
                active: false,
                autoheight:true,
                header: ".subaccordion-header",
                animate:200,
                collapsible: true,
                heightStyle:'content',
                icons: {"header":"view-filter-ui-icon-down",
                    "activeHeader":"view-filter-ui-icon-up"},
                create: function(event,ui){
                },
                activate: function(event,ui){
                    $('.readMore').addClass('hidden');
                    $('.readMoreLink, .readMoreButton').removeClass('hidden');
                    refreshFilterWindow();
                }
            });

            $( ".secondary-accordion" ).accordion({
                active: false,
                autoheight:true,
                header: ".accordion-header-secondary",
                animate:200,
                collapsible: true,
                heightStyle:'content',
                icons: {"header":"view-filter-ui-icon-down",
                    "activeHeader":"view-filter-ui-icon-up"},
                create: function(event,ui){
                },
                activate: function(event,ui){
                    $('.readMore').addClass('hidden');
                    $('.readMoreLink, .readMoreButton').removeClass('hidden');
                    refreshFilterWindow();
                }
            });

            $(".supplemental-accordion").accordion({
                active: false,
                autoheight:true,
                header: "h3.graysubaccordionheading",
                animate:200,
                collapsible: true,
                heightStyle:'content',
                icons: {"header":"view-filter-ui-icon-down-first",
                    "activeHeader":"view-filter-ui-icon-up-first"}
            });

            $(".subAccordion").accordion({
                active: false,
                autoheight:true,
                header: "h3.graysubaccordionheading",
                animate:200,
                collapsible: true,
                heightStyle:'content',
                icons: {"header":"view-filter-ui-icon-down-second",
                    "activeHeader":"view-filter-ui-icon-up-second"}
            });

            $(".subSecondAccordion").accordion({
                active: false,
                autoheight:true,
                header: "h3.graysubSecondHeader.accordionOn",
                animate:200,
                collapsible: true,
                heightStyle:'content',
                icons: {"header":"view-filter-ui-icon-down-third",
                    "activeHeader":"view-filter-ui-icon-up-third"}
            });
            $(".subThirdAccordion").accordion({
                active: false,
                autoheight:true,
                header: "h3.graysubThirdHeader",
                animate:200,
                collapsible: true,
                heightStyle:'content',
                icons: {"header":"view-filter-ui-icon-down-third",
                    "activeHeader":"view-filter-ui-icon-up-third"}
            });

            $('.ui-accordion-header').attr('tabindex', '0');
            // Reset the accordion header tabindex to "0" for all items when any accordion on the page is toggled.
            $('.ui-accordion-header').on('click', function() {
                $('.ui-accordion-header').attr('tabindex', '0');
            });
        }
    };
// To understand behaviors, see https://drupal.org/node/756722#behaviors
})(jQuery, Drupal, this, this.document);