"use strict";

var audio_playing = false;
var audio_paused = false;

(function ($, Drupal) {
  Drupal.behaviors.textResize = {
    // D7 "Changed Drupal.behaviors to objects having the methods "attach" and "detach"."
    attach: function attach(context) {
      function getSize(domel) {
        var classList = $(domel).attr('class').split(/\s+/);
        var tsize = 0;
        $.each(classList, function (index, item) {
          if (item.substring(0, 10) == 'text-size-') {
            tsize = item.substring(10);
          }
        });
        return tsize;
      }

      var text_resize_minimum = "14";
      var text_resize_maximum = "22";
      var text_resize_line_height_allow = 0;
      var text_resize_line_height_min = "16";
      var text_resize_line_height_max = "36";
      var element_to_resize = $('.field-collection-container'); // Set the initial font size if necessary

      if ($.cookie('text_resize') != null) {
        element_to_resize.removeClass('text-size-0 text-size-1 text-size-2');
        element_to_resize.addClass('text-size-' + parseInt($.cookie('text_resize')));
      } // Changer links will change the text size when clicked


      $('#text_resize_increase').unbind('click').bind('click', function (e) {
        // Set the current font size of the specified section as a variable
        var currentFontSize = getSize(element_to_resize); // javascript lets us choose which link was clicked, by ID

        var new_font_size = parseInt(currentFontSize) + 1; // Allow resizing as long as font size doesn't go above text_resize_maximum.

        if (new_font_size < 3) {
          $.cookie('text_resize', new_font_size, {
            path: '/'
          });
          var allow_change = true;
        } else {
          $.cookie('text_resize', 0, {
            path: '/'
          });
          var reset_size_min = true;
        } // jQuery lets us set the font size value of the main text div


        if (allow_change == true) {
          element_to_resize.removeClass('text-size-0 text-size-1 text-size-2');
          element_to_resize.addClass('text-size-' + new_font_size); //element_to_resize.css('font-size', new_font_size + 'px'); // Add 'px' onto the end, otherwise ems are used as units by default

          return false;
        } else if (reset_size_min == true) {
          element_to_resize.removeClass('text-size-0 text-size-1 text-size-2');
          element_to_resize.addClass('text-size-0'); //element_to_resize.css('font-size', text_resize_minimum + 'px');

          return false;
        } else if (reset_size_max == true) {
          element_to_resize.removeClass('text-size-0 text-size-1 text-size-2');
          element_to_resize.addClass('text-size-2'); //element_to_resize.css('font-size', text_resize_maximum + 'px');

          return false;
        } else if (reset_size_original == true) {
          element_to_resize.removeClass('text-size-0 text-size-1 text-size-2');
          element_to_resize.addClass('text-size-0'); //element_to_resize.css('font-size', null);

          return false;
        }

        return false;
      });
    }
  };
  Drupal.behaviors.consumer = {
    attach: function attach(context, settings) {
      // code that needs to be run on doc ready AND post-ajax call

      /* SITE SEARCH */
      $('#mobile-menu-trigger a').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        $('body').toggleClass('active-search');
        $('body').toggleClass('active-mobile-menu');
      });
      $('#block-search-form *').focus(function () {
        $('body').addClass('active-search');
      });
      $('.region-header form *').on('click', function (e) {
        e.stopPropagation();
      });
      $('#main-menu a, #logo').on('focus', function () {
        $('body').removeClass('active-search');
      });
      $('body').on('click', function (e) {
        if ($(e.target).attr('id') === 'edit-search-api-fulltext' || $(e.target).attr('id') === 'edit-search-api-fulltext--2') {//  do nothing if user selects search input text area
        } else {
          $(this).removeClass('active-search');
          $(this).removeClass('active-mobile-menu');
        }
      });
      $('#mobile-menu-trigger').click(function () {
        $('body').removeClass('active-search');
      });
    }
  };
  $(document).ajaxComplete(function () {// callback after drupal-registered ajax is complete.
  });
  $(window).scroll(function () {
    if ($(document).scrollTop() > 50) {
      $('.menu-block-wrapper').addClass('shrink');
    } else {
      $('.menu-block-wrapper').removeClass('shrink');
    }
  });
  $(document).ready(function () {
    $('.math tr:last-child').addClass('last'); // Hide Tabs except first on load.

    $('.field--tab .field-item').not(':eq(0)').hide();
    var activetab = 0;
    var currentTab = $(".article-tab");
    var tabActive = $('#tab-' + activetab);
    var audioPlayer = $('.ftc-audio-player-html5');
    currentTab.addClass('inactive-tab-btn');
    tabActive.removeClass('inactive-tab-btn');
    tabActive.addClass('active-tab-btn');
    var numtabs = $('.tab-wrapper .field--tab > .field-items > .field-item').length;
    $('#tab-body-' + (numtabs - 1) + ' .btn-next-tab').remove(); // Tabs.

    var tabMap = [];
    currentTab.each(function () {
      var tabNum = $(this).attr('id').match(/[0-9]+/);
      var tabName = $('#tab-body-' + tabNum + ' > .field-collection-view .content .paragraph--type--cg-page-tab > .field--label .field-item').text().toLowerCase();
      tabName = $.trim(tabName);
      tabName = tabName.replace(/ /g, '-');
      tabMap[tabNum] = tabName;
      $(this).attr('href', '#' + tabName);
    }); // Read More.

    $('.field--tab > .field-items > .field-item').each(function () {
      $(this).find('.btn-next-tab').attr('href', '#' + tabMap[$(this).index() + 1]).click(function () {
        $('html, body').animate({
          scrollTop: $("#page-title").offset().top
        }, 200);
      });
      $(this).find('.link-to-tab').click(function () {
        $('html, body').animate({
          scrollTop: $("#page-title").offset().top
        }, 200);
      });
    });

    function movetotab(tabnow) {
      var tabBodyNow = $('#tab-body-' + tabnow);
      var tabNow = $('#tab-' + tabnow); // GTFO if the tab doesn't exist.

      if (tabBodyNow.length === 0) {
        return;
      }

      currentTab.removeClass('active-tab-btn');
      currentTab.addClass('inactive-tab-btn');
      tabNow.removeClass('inactive-tab-btn');
      tabNow.addClass('active-tab-btn');
      $('.tab-wrapper > .field-collection-container > .field--tab > .field-items > .field-item').hide();
      tabBodyNow.show();
      activetab = tabnow;
      var audio_playing = false;

      if (audioPlayer) {
        audioPlayer.trigger('pause');
        audioPlayer.src = audioPlayer[activetab];
      }
    }

    function checkHash(hash) {
      hash = hash.replace("#", "");

      if (hash === '') {
        hash = tabMap[0];
      }

      hash = decodeURIComponent(hash);

      if ($.inArray(hash, tabMap) > -1) {
        movetotab($.inArray(hash, tabMap));
      }
    }

    $(window).on('hashchange', function () {
      var hash = window.location.hash;
      checkHash(hash);
    }); // Check for hash on page load.

    $(window).on('hashchange');

    function rgb2hex(rgb) {
      rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

      function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
      }

      return '0x' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }

    function audio_player_statusUpdate(status) {
      /* Potential values for this function are:
       *  playing
       *  paused
       *  completed
       *  volume_over
       *  volume_out
       */
      switch (status) {
        case 'playing':
          // Switch to show ||
          audio_playing = true;
          $('.btn-listen div').attr('class', 'playing-btn');
          break;

        case 'paused':
          audio_paused = true;
          audio_playing = false;
          $('.btn-listen div').attr('class', 'stopped-btn');
          break;

        case 'completed':
          // Switch to show >
          audio_playing = false;
          audio_paused = false;
          $('.btn-listen div').attr('class', 'stopped-btn');
          break;

        case 'volume_over':
          $('.audio-file').addClass('volume_over');
          break;

        case 'volume_out':
          $('.audio-file').removeClass('volume_over');
          break;
      }
    }

    if (audioPlayer.length > 0) {
      audioPlayer.on("playing", function () {
        audio_player_statusUpdate('playing');
      });
      audioPlayer.on("pause", function () {
        audio_player_statusUpdate('paused');
      });
      audioPlayer.on("ended", function () {
        audio_player_statusUpdate('completed');
      });
      $("#listen-btn").click(function () {
        if (audio_playing) {
          audioPlayer.trigger('pause');
          $('.btn-listen div').attr('class', 'stopped-btn');
          audio_playing = false;
          audio_paused = true;
        } else {
          if (audio_paused === false) {
            audioPlayer.src = audioPlayer[activetab];
          }

          audioPlayer[activetab].play();
          $('.btn-listen div').attr('class', 'playing-btn');
          audio_playing = true;
        }

        return false;
      });
    }
    /* SECONDARY NAVIGATION */


    $('.sidebars .menu-block-wrapper li:has(.menu),#main-menu .menu-block-wrapper > ul > li:has(ul)').each(function () {
      if ($(this).hasClass('is-active-trail')) {
        $(this).addClass('open').removeClass('closed').prepend('<div class="menu-level-toggle"><a href="" class="open"><span class="visuallyhidden">Show/Hide Submenu Items</span></a></div>');
      } else {
        $(this).removeClass('open').addClass('closed').prepend('<div class="menu-level-toggle"><a href="" class="closed"><span class="visuallyhidden">Show/Hide Submenu Items</span></a></div>');
      }
    });
    $('.menu-level-toggle a').on('click', function (e) {
      e.preventDefault();
      $(this).toggleClass('closed').toggleClass('open');
      $(this).closest('li').toggleClass('closed').toggleClass('open');
    });
    $('.region-sidebar-second .menu-block-wrapper ul ul a').focus(function () {
      $(this).closest('ul').closest('li').removeClass('closed').addClass('open');
    });
    /* MAIN MENU */
    // Main Menu No-touch Mouse.

    $('.no-touchevents .menu-name-main-menu li').hover(function () {
      $(this).addClass('hover');
    }, function () {
      $(this).removeClass('hover');
    }); // Main Menu Touch.

    $('.touchevents .menu-name-main-menu > .menu > li.expanded > a').click(function (e) {
      if (!$('body').hasClass('active-mobile-menu')) {
        if (!$(this).parent('li').hasClass('hover')) {
          e.preventDefault();
          $(this).parent('li').addClass('hover').siblings().removeClass('hover');
        }
      }
    }); // Main Menu No-touch Keyboard.

    $('.no-touchevents .menu-name-main-menu ul.menu ul li a').focus(function () {
      $(this).parents('li').addClass('hover');
      $(this).parents('li').siblings().removeClass('hover');
      $('body').addClass('active-mobile-menu');
      $(this).closest('ul').closest('li').removeClass('closed').addClass('open');
    });
    $('.no-touchevents .menu-name-main-menu > ul.menu > li > a').focus(function () {
      $(this).closest('li').siblings().removeClass('hover');
    });
    $('#site-logo a, #banner a, #titling-wrapper a, #main-wrapper a').focus(function () {
      $('.no-touchevents .menu-name-main-menu .hover').removeClass('hover');
      $('body').removeClass('active-search');
      $('body').removeClass('active-mobile-menu');
    });
    /* MOBILE MENU */

    $('#mobile-menu-trigger').on('click', function (e) {
      e.preventDefault();
      $('body').toggleClass('active-mobile-menu');
      $('.region-header').detach().insertBefore('#menu-and-search-wrapper');
    });

    function responsive() {
      if ($('.region-header #block-search-form .content form').css('width') === '330px') {
        $('.region-header').detach().insertBefore('#menu-and-search-wrapper');
      } else {
        $('.region-header').detach().appendTo('#menu-and-search-wrapper');
      }
    }

    $('.view-cg_help_for_you_section .btn-print').on('click', function (e) {
      e.preventDefault();
      window.print();
    });
    $(window).on('load', responsive);
    $(window).bind('resize', responsive);
  });
  /* end doc ready */
})(jQuery, Drupal);