// variables for TABS + ACCORDION
var tabIsSet = true; 
var resizeListener;

//the amount of time to wait after the resizing has finished before calling our function
var pause = 1900;


/* ACCORDION ONLY
-----------------------------------------------------------------------------------------
*/
function accordionUIOnly(){
  console.log("accordionUIOnly Function Ran");
  
  var i = 0;

  $('.accordion > .title-bar').each(function() {
   console.log("accordion only code"); 

  var $this = $(this);

  // create unique id for a11y relationship

  var id = 'collapsible-' + i;
  i++;

  // wrap the content and make it focusable

  $this.nextUntil('.title-bar ').wrapAll('<div id="'+ id +'" class="cui collapsible" aria-hidden="true">');
  var panel = $this.next();

  // Add the button inside the <h2> so both the heading and button semanics are read

  $this.wrapInner('<button aria-expanded="false" aria-controls="'+ id +'">');
  var button = $this.children('button');

  // Toggle the state properties

  button.on('click', function() {
    var state = $(this).attr('aria-expanded') === 'false' ? true : false;
	// slide down panels
	panel.slideToggle(500, function(){});
	$(this).attr('aria-expanded', state);
	panel.attr('aria-hidden', !state);
	
  });

});

} /*end accordionUIOnly */ 



/* TABS + ACCORDION
-----------------------------------------------------------------------------------------
*/

//Tabs function
function tabsUI(){
  console.log("function tabsUI ran");
  
  // The class for the container div
  var $container = '.tab-interface';  

  // if tabs don't exist 
  if($('[role="tabpanel"]').length == 0){

	// The setup
	$($container +' ul').attr('role','tablist');
	$($container +' [role="tablist"] li').attr('role','presentation');
	$('[role="tablist"] a').attr({
	  'role' : 'tab',
	  'tabindex' : '-1'
	});

	// Make each aria-controls correspond id of targeted section (re href)
	$('[role="tablist"] a').each(function() {
	$(this).attr(
	  'aria-controls', $(this).attr('href').substring(1)
	);
	});

	// Make the first tab selected by default and allow it focus
	$('[role="tablist"] li:first-child a').attr({
	  'aria-selected' : 'true',
	  'tabindex' : '0'
	});

	// Make each section -CHANGED focusable and give it the tabpanel role
	$($container +' div.tab-content').attr({
	'role' : 'tabpanel'
	}).not(':first-of-type').attr({
	'aria-hidden' : 'true'
	}); 

	// Make first child of each panel focusable programmatically
	$($container +' div.tab-content > *:first-child').attr({
	  'tabindex' : '0'
	});

	// Make other tab unselected by default - for switch from accordion to tabs)
	$('[role="tablist"] li:not(:first-child) a').attr({
	  'aria-selected' : null
	});    

  }

  // fix tabs if they've been shown after accodion view
  if($($container +' .cui.collapsible').length){ 

	// remove .cui.collapsible div
	$('.cui.collapsible > .tab-content').unwrap();

	// hide tab panels
	$('[role=tabpanel]').attr({
	'aria-hidden' : 'true'
	}); 

	// show first tab panel
	$('[role="tabpanel"]:first-of-type').attr({
	'aria-hidden' : null
	});  

	// Make other tab unselected by default - for switch from accordion to tabs)
	$('[role="tablist"] li:not(:first-child) a').attr({
	  'aria-selected' : null
	});    

  }

  // Change focus between tabs with arrow keys
  $('[role="tab"]').on('keydown', function(e) {

    // define current, previous and next (possible) tabs
    var $original = $(this);
    var $prev = $(this).parents('li').prev().children('[role="tab"]');
    var $next = $(this).parents('li').next().children('[role="tab"]');
    var $target;

    // find the direction (prev or next)
    switch (e.keyCode) {
        case 13:
            $(this).click();
            $target = $(this);
            break;
        case 37:
            $target = $prev;
            break;
        case 39:
            $target = $next;
            break;
        default:
            $target = false;
            break;
    }

    if ($target.length) {
        $original.attr({
          'tabindex' : '-1',
          'aria-selected' : null
        });
        $target.attr({
          'tabindex' : '0',
          'aria-selected' : true
        }).focus();
    }

  });

  // Handle click on tab to show + focus tabpanel
  $('[role="tab"]').on('click', function(e) {

    e.preventDefault();

    // remove focusability [sic] and aria-selected
    $('[role="tab"]').attr({
      'tabindex': '-1',
      'aria-selected' : null
      });

    // replace above on clicked tab
    $(this).attr({
      'aria-selected' : true,
      'tabindex' : '0'
    });

    // Hide panels
    $($container +' [role="tabpanel"]').attr('aria-hidden', 'true');

    // show corresponding panel
    $('#' + $(this).attr('href').substring(1))
      .attr('aria-hidden', null);
  });

} //end Tabs function




//Accordion function
function accordionUI(){
  console.log("function accordionUI (tab combo) ran");
  
  var i = 0;
  
  // rebuild accordions if switching from tabs to accordion view
  if($('[role="tabpanel"]').length){
	
	// remove buttons
	$('.collapsible-tab .title-bar > button').contents().unwrap();
	
	// remove tabpanel role, remove .cui.collapsible divs
	$('.cui.collapsible > .tab-content').unwrap().removeAttr('role');
	
  }
    
  // if just resizing screen (not switching from tabs), don't rebuild accordions
  if(!$('.collapsible-tab .title-bar > button').length){

  //DISPLAY THE ACCORDION
	$('.collapsible-tab .title-bar').each(function() {

	  var $this = $(this);
	  $this.next().removeAttr('role');

	  // create unique id for a11y relationship
	  var id = 'collapsible-tab' + i;
	  i++;
	  
	  // wrap the content and make it focusable
	  $this.nextUntil('.title-bar ').wrapAll('<div id="'+ id +'" class="cui collapsible" aria-hidden="true">');
	  var panel = $this.next();

	  // Add the button inside the <h2> so both the heading and button semanics are read
	  $this.wrapInner('<button aria-expanded="false" aria-controls="'+ id +'">');
	  var button = $this.children('button');

	  // Toggle the state properties

	  button.on('click', function(e) {
		var state = $(this).attr('aria-expanded') === 'false' ? true : false;
		// slide down panels
		panel.slideToggle(500, function(){});
		$(this).attr('aria-expanded', state);
		panel.attr('aria-hidden', !state);
		e.preventDefault();
		return false;
	  });

	});

	}

 } /*end accordionUI */ 

 /* ACCORDION (end)
-----------------------------------------------------------------------------------------
*/ 

function windowWidth(){
    //check the width and set tab variable
    console.log("windowWidth function ran");
    if (window.innerWidth < 768){
            console.log(window.innerWidth);
            console.log("mobile width");
            tabIsSet =  false;  //less than 768, display accordion
            console.log("tabIsSet to " + tabIsSet);
    } else if (window.innerWidth >= 768) {
            console.log(window.innerWidth);
            console.log("desktop");
            tabIsSet = true; //greaterh than 768, display tabs
            console.log("tabIsSet to " + tabIsSet);
    }
    
}

//onload,  set the UI to tabs or accordion display based on tabIsSet variable
function renderTabsAccordionUI(){ 
    console.log("renderTabsAccordionUI function ran");

    if(tabIsSet === true){
      console.log("tabIsSet to true");
      tabsUI();
    } else if(tabIsSet === false){
      console.log("tabIsSet to false");
      accordionUI();
    }
}


function tabsAccordionUI(){

  $(window).on('load', function(){
    //check window width and set the tab setting with tabIsSet variable
    windowWidth();
    renderTabsAccordionUI();

  });


  $(window).resize(function(){
      console.log("window resize function");
      //every time the window resize is called cancel the setTimeout() function

	  clearTimeout(resizeListener);
	  resizeListener = setTimeout(function() {
		//location.href = location.href;
		windowWidth();
		renderTabsAccordionUI();
				
	  }, 50);

  }); 
} //end tabsAccordionUI function

