// URL updates and the element focus is maintained
// originally found via in Update 3 on http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links

// filter handling for a /dir/ OR /indexordefault.page
function filterPath(string) {
  return string
    .replace(/^\//, '')
    .replace(/(index|default).[a-zA-Z]{3,4}$/, '')
    .replace(/\/$/, '');
}

var locationPath = filterPath(location.pathname);
jQuery('a[href*="#"]').each(function () {
  var thisPath = filterPath(this.pathname) || locationPath;
  var hash = this.hash;
  if (jQuery("#" + hash.replace(/#/, '')).length) {
    if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
      var $target = jQuery(hash), target = this.hash;
      if (target) {
        jQuery(this).click(function (event) {
          event.preventDefault();
          jQuery('html, body').animate({scrollTop: $target.offset().top}, 600, function () {
            location.hash = target;
            $target.focus();
            if ($target.is(":focus")){ //checking if the target was focused
              return false;
            }else{
              $target.attr('tabindex','-1'); //Adding tabindex for elements not focusable
              $target.focus(); //Setting focus
            };
          });
        });
      }
    }
  }
});

 jQuery(document).ready(function($) {
    $(document).foundation();
 })

jQuery(document).ready(function($){
  $('.mobile-icon').on('click', function(){
		$('.full-navigation').toggleClass('toggled');
    $('body').toggleClass('overflow-hidden');
    $('.mobile-icon').toggleClass('clicked');
  	});
  });

(function(){	
								
  // Support for IE11
  // src: https://www.sitepoint.com/get-url-parameters-with-javascript/
  function getAllUrlParams(url) {
    // get query string from url (optional) or window
    var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

    // we'll store the parameters here
    var obj = {};

    // if query string exists
    if (queryString) {

      // stuff after # is not part of query string, so get rid of it
      queryString = queryString.split('#')[0];

      // split our query string into its component parts
      var arr = queryString.split('&');

      for (var i = 0; i < arr.length; i++) {
        // separate the keys and the values
        var a = arr[i].split('=');

        // set parameter name and value (use 'true' if empty)
        var paramName = a[0];
        var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];

        // (optional) keep case consistent
        paramName = paramName.toLowerCase();
        if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();

        // if the paramName ends with square brackets, e.g. colors[] or colors[2]
        if (paramName.match(/\[(\d+)?\]$/)) {

          // create key if it doesn't exist
          var key = paramName.replace(/\[(\d+)?\]/, '');
          if (!obj[key]) obj[key] = [];

          // if it's an indexed array e.g. colors[2]
          if (paramName.match(/\[\d+\]$/)) {
            // get the index value and add the entry at the appropriate position
            var index = /\[(\d+)\]/.exec(paramName)[1];
            obj[key][index] = paramValue;
          } else {
            // otherwise add the value to the end of the array
            obj[key].push(paramValue);
          }
          } else {
          // we're dealing with a string
          if (!obj[paramName]) {
            // if it doesn't exist, create property
            obj[paramName] = paramValue;
          } else if (obj[paramName] && typeof obj[paramName] === 'string'){
            // if property does exist and it's a string, convert it to an array
            obj[paramName] = [obj[paramName]];
            obj[paramName].push(paramValue);
          } else {
            // otherwise add the property
            obj[paramName].push(paramValue);
          }
        }
      }
    }

    return obj;
  };

  function newsletterSignup(evt) {
    
    // Stop form submission 
    evt.preventDefault();
    const target = evt.target;
    
    // Create object with madatory information
    const formObj = {
      "form_page_url": window.location.href,
      "http_referer": document.referrer,
      "gf_entry_id": 0,
      "page_name": document.title,
      "pcd": getAllUrlParams().pcd,
      "form_type": "candidate_newsletter"
    };

    // Add form data
    const elements = target.getElementsByTagName('input');
    const data = new FormData(target);
    for (var input of data.entries()) {
      formObj[input[0]] = input[1]
    }

    const liberalist_link = "https://qgrk94bap6.execute-api.ca-central-1.amazonaws.com/prod/aperture/olp/candidate_site";
    const query = liberalist_link; 
    
    fetch(query, {
      method: 'POST',
      mode: "no-cors",
      headers: { 
        "Content-Type": "application/json; charset=utf-8" 
      },
      body: JSON.stringify(formObj),
    })
    .then(function (response) { return response.text(); }) // plain response -- can be `response.json()` to parse response as JSON 
    .then(function (data) {
      console.log("success_id: ", data);

      // Update HTML to display success
      const template = document.getElementById('nwsltr_success');
      const clone = template.content.cloneNode(true);
      target?.replaceWith(clone);
    })
    .catch(function (err) {
      console.log("error: ", err);

      // Display error to client
      const template = document.getElementById('nwsltr_error');
      const clone = template.content.cloneNode(true);
      target?.replaceWith(clone);
    });
  };

  document.addEventListener('DOMContentLoaded', function() {
    const form = document.forms.newsletter_signup;
    form.addEventListener('submit', newsletterSignup);
  });
})();