//Remove button styling from Save Draft button
jQuery('[data-drupal-selector="edit-actions-12"] 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-3 .email-link').find('a').attr("href", EmailClipboardStr);
}

//Save Draft/open email client
jQuery('[data-drupal-selector="edit-actions-12"] input, .top-email-link').click(function () {
  //Open up new email using hidden email link
  location.href=jQuery('.scaler-step-3 .email-link').find('a').attr("href") + "#" + hash;

});

  //Copy Link on click
  jQuery('.top-clipboard-link').click(function () {
  
  //copy link to clipboard
   jQuery('.scaler-step-3 .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.');
}
 

  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");

    }

  };

//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");
    
};

//SelectTab for select dropdown
function dropTab(elm) { 
  
   event.preventDefault();
   hideAlltabs();
  
  jQuery(elm).removeClass('hidden');
  jQuery(elm).attr('aria-hidden','false');
  
}


// 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-specifying-the-intervention-page":
    jQuery('[data-drupal-selector="edit-specifying-the-intervention-page"]').show();
    jQuery('li[data-webform-page="specifying_the_intervention_page"]').addClass("is-active");
    
    //jQuery('li[data-webform-page="Overview"]').addClass("is-complete");
    break;
    
  case "edit-defining-the-target-population":
    jQuery('[data-drupal-selector="edit-defining-the-target-population"]').show();
    jQuery('li[data-webform-page="defining_the_target_population"]').addClass("is-active");
    break;
    
  case "edit-establishing-implementation-supports-":
    jQuery('[data-drupal-selector="edit-establishing-implementation-supports-"]').show();
    jQuery('li[data-webform-page="establishing_implementation_supports_"]').addClass("is-active");
    break;
    
  case "edit-having-an-enabling-context":
    jQuery('[data-drupal-selector="edit-having-an-enabling-context"]').show();
    jQuery('li[data-webform-page="having_an_enabling_context"]').addClass("is-active");
    break;
    
  case "edit-establishing-an-implementation-infrastructure":
    jQuery('[data-drupal-selector="edit-establishing-an-implementation-infrastructure"]').show();
    jQuery('li[data-webform-page="establishing_an_implementation_infrastructure"]').addClass("is-active");
    break;
    
  case "edit-results-title-summary":
   jQuery('[data-drupal-selector="edit-summary"]').show();
   jQuery('li[data-webform-page="Results"]').addClass("is-active");
   break;
   
  default: 
    jQuery('[data-drupal-selector="edit-determining-readiness-to-scale"]').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 3</h1>');
  
  setTimeout(() => {
    //Update action to remove query string
    jQuery('.webform-submission-form').attr('action', 'scaler-step3');
  
    //Reset form - trigger hidden reset button
    jQuery('.scaler-step-3 .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 
//for progress bar, nav buttons, return to edit link
jQuery('.scaler-step-3 .progress-step a, .scaler-step-3 .nav-button a, .scaler-step-3 .return-edit a').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-3 .save-draft-hash').trigger("click");
  
});

//Progress bar - set items not yet done
  var infrastructure_score = Number( jQuery('[data-drupal-selector="edit-total-infrastructure-score"]').val() );
  var total_context_score = Number( jQuery('[data-drupal-selector="edit-total-context-score"]').val() );
  var total_supports_score = Number( jQuery('[data-drupal-selector="edit-total-supports-score"]').val() );
  var total_define_target_pop_score = Number( jQuery('[data-drupal-selector="edit-total-define-target-pop-score"]').val() );
  var total_identifying_intervention_score = Number( jQuery('[data-drupal-selector="edit-total-identifying-intervention-score"]').val() );

  if (infrastructure_score == 0) {
    jQuery('li[data-webform-page="establishing_an_implementation_infrastructure"]').addClass("is-not-started");
  }
  if (total_context_score == 0) {
    jQuery('li[data-webform-page="having_an_enabling_context"]').addClass("is-not-started");
  }
  if (total_supports_score == 0) {
    jQuery('li[data-webform-page="establishing_implementation_supports_"]').addClass("is-not-started");
  }
  if (total_define_target_pop_score == 0) {
    jQuery('li[data-webform-page="defining_the_target_population"]').addClass("is-not-started");
  }
  if (total_identifying_intervention_score == 0) {
    jQuery('li[data-webform-page="specifying_the_intervention_page"]').addClass("is-not-started");
  }


//Print Button
jQuery('.scaler-step-3 .print-button').click(function () {
  window.print();
});

//Add class for webform likert pages
jQuery(".js-form-type-webform-likert").addClass("form-type-webform-likert");