//Remove button styling from Save Draft button
jQuery('[data-drupal-selector="edit-actions-01"] input').removeClass( "button btn btn-primary" );

//Update Clipboard link to include full path
//Get current clipboard value
if (document.getElementById("copyToClipboard")) {
  var ClipboardStr = document.getElementById("copyToClipboard").value;
  //New URL: hostname + pathname + token query param + token value
  ClipboardStr = "https://" + window.location.hostname + window.location.pathname +"?token="+ ClipboardStr.split('?token=')[1];
  //Set clipboard value to updated value
  document.getElementById("copyToClipboard").setAttribute('value', ClipboardStr);

  //Update Email link to include full path
  var EmailClipboardStr = "mailto:%20?subject=Link%20to%20your%20SCALER%20checklists&body=" +  ClipboardStr;
  jQuery('.scaler-step-1 .email-link').find('a').attr("href", EmailClipboardStr);
}

//Save Draft/open email client
jQuery('[data-drupal-selector="edit-actions-01"] input, .top-email-link').click(function () {
  
  
  //Open up new email using hidden email link
  location.href=jQuery('.scaler-step-1 .email-link').find('a').attr("href") + "#" + hash;
});

  //Copy Link on click
  jQuery('.top-clipboard-link').click(function () {
  
  //copy link to clipboard
   jQuery('.scaler-step-1 .copy-link').trigger("click");
  
});


//Copy link
function CopyFunction() {
  var copyText = document.getElementById("copyToClipboard");
  copyText.value = copyText.value + "#" + hash;
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  document.execCommand("copy"); 
  document.location = copyText.value + "#" + hash;
  alert('Unique link copied to the clipboard.');
}


//SelectTab for Overview
function selectTab(elm) {
   event.preventDefault();
   hideAlltabs();
   elm.classList.add("active");  
   var panid = elm.getAttribute("aria-controls");
    
  document.getElementById(panid).classList.remove("hidden");
  document.getElementById(panid).setAttribute("aria-hidden","false");
    
};

  function hideAlltabs (event) {
    var elems = document.querySelectorAll('div.tabPanel[role=tabpanel]');
    for(var i=0;i<elems.length;i++){
  
       elems[i].classList.add("hidden");
       elems[i].setAttribute("aria-hidden","true");
    }
     var elems = document.querySelectorAll('a[role=tab]');
    for(var i=0;i<elems.length;i++){
  
       elems[i].classList.remove("active");

    }

  };

// Print out collapsed details items
// https://stackoverflow.com/questions/19646684/force-open-the-details-summary-tag-for-print-in-chrome
// Open collapsed items before printing
// Set up before/after handlers
var beforePrint = function() {
    jQuery("details").attr('open', '');
};
var afterPrint = function() {
    jQuery("details").removeAttr('open');
};

// Webkit
if (window.matchMedia) {
    var mediaQueryList = window.matchMedia('print');
    mediaQueryList.addListener(function(mql) {
        if (mql.matches) {
            beforePrint();
        } else {
            afterPrint();
        }
    });
}
// IE, Firefox
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;



// Page Saving / Navigation //

//Get hash value from URL if it exists
var hash = window.location.hash.substring(1);

//Get hash value from hidden input field if it exists
var hash_hidden_field = jQuery('[data-drupal-selector="edit-webform-page"]').val();

//Check if a hash exists from hidden field if none found in URL
if ( (hash === "") && (hash_hidden_field !== "") ) {
  var hash = hash_hidden_field;
}

//Show page depending on hash found
//Default to overview page
//Set Progress Bar item to is-active
switch (hash) {
    
  case "edit-container-form-help-eoe":
    jQuery('[data-drupal-selector="edit-container-form-help-eoe"]').show();
    jQuery('li[data-webform-page="building_evidence"]').addClass("is-active");
    break;
    
  case "edit-summary":
   jQuery('[data-drupal-selector="edit-summary"]').show();
   jQuery('li[data-webform-page="Results"]').addClass("is-active");
   break;
   
  default: 
    jQuery('[data-drupal-selector="edit-overview-is-there-evidence"]').show();
    jQuery('li[data-webform-page="Overview"]').addClass("is-active");
}

//Reset form based on query parameter (coming from homepage)
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

//Check for Start from homepage, clear form if starting from beginning
var reset = getUrlParameter('reset');

if ( reset == "1" ) {
  jQuery('.webform-submission-form').hide();
  jQuery('.webform-submission-form').before('<h1 class="scaler-page-title">Loading Step 1</h1>');
  
  setTimeout(() => {
    //Update action to remove query string
    jQuery('.webform-submission-form').attr('action', 'scaler-step1');
  
    //Reset form - trigger hidden reset button
    jQuery('.scaler-step-1 .webform-button--reset').trigger("click");
  }, 100);
}

//Scroll window
//to alert message if available
//if no alert, scroll to title
if ( reset != "1" ) {
  if (jQuery(".alert")[0]){
    var elmnt = document.getElementsByClassName("alert")[0];
    elmnt.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
    
  } else {
    var elmnt = document.getElementById("scaler-page-title");
    elmnt.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
  }
}

//If progress link OR back/next link clicked
//Get hash from link. Trigger Save / Save draft.
jQuery('.scaler-step-1 .progress-step a, .scaler-step-1 .nav-button a, .scaler-step-1 a.return-edit').click(function () {
  
  var url_hash = jQuery(this).attr('href').substring(1);
  
  //Update hidden field with link hash
  jQuery('[data-drupal-selector="edit-webform-page"]').val(url_hash);
  
  event.preventDefault();
 
  //Trigger click on Save/Draft link to save progress
  jQuery('.scaler-step-1 .save-draft-hash').trigger("click");
  
});


//Print Button
jQuery('.scaler-step-1 .print-button').click(function () {
  window.print();
});