// NOTE: all vars and functions names are prefixed with a unique project-dependent prefix ('sh') to avoid conflicts with other scripts. 

// Cross browser support errors
const SH_ERROR_NO_QUERYSELECTORS = 100

/** HTML ***********/
let shHtmlTemplateShareAPI = `
<div class="share-l214">
  <button class="jsl-share-button jsl-share" type="button">
      <span class="jsl-share-label">Partager : </span>
      <svg class="jsl-share-ico"><use href="#share"></use></svg>
  </button>
</div>
`

let shHtmlTemplateFallBack = `
<div class="share-l214" data-theme="--theme--">
    <div class="jsl-share-buttons">
      <a class="jsl-share-button jsl-facebook" href="https://www.facebook.com/sharer.php?u=--urlEncoded--" --openMode-- data-rs="facebook">
        <svg class="jsl-share-ico"><use href="#facebook"></use></svg>
        <span class="jsl-share-label">Facebook</span>
      </a>
      <a class="jsl-share-button jsl-twitter" href="https://twitter.com/intent/tweet?text=--tweetEncoded----tweetUrlEncodedOptParam--" --openMode-- data-rs="twitter">
        <svg class="jsl-share-ico"><use href="#twitter"></use></svg>
        <span class="jsl-share-label">Twitter</span>
      </a>
      <a class="jsl-share-button jsl-pinterest" href="http://pinterest.com/pin/create/button/?url=--urlEncoded--&amp;media=--imageEncoded--&amp;description=--messageEncoded--" --openMode-- data-rs="pinterest">
        <svg class="jsl-share-ico"><use href="#pinterest"></use></svg>
        <span class="jsl-share-label">Pinterest</span>
      </a>
      <a class="jsl-share-button jsl-whatsapp" href="https://api.whatsapp.com/send?text=--messageWhatsAppEncoded--" target="_blank" data-rs="whatsapp">
        <svg class="jsl-share-ico"><use href="#whatsapp"></use></svg>
        <span class="jsl-share-label">WhatsApp</span>
      </a>
      <a class="jsl-share-button jsl-gmail" href="https://mail.google.com/mail/u/0/?ui=2&amp;view=cm&amp;fs=1&amp;tf=1&amp;su=--titleMailEncoded--&amp;body=--messageMailEncoded--" --openMode-- data-rs="gmail">
        <svg class="jsl-share-ico"><use href="#gmail"></use></svg>
        <span class="jsl-share-label">Gmail</span>
      </a>
      <a class="jsl-share-button jsl-email" href="mailto:?subject=--titleMailEncoded--&body=--messageMailEncoded--" --openMode-- data-rs="mail">
        <svg class="jsl-share-ico"><use href="#email"></use></svg>
        <span class="jsl-share-label">Email</span>
      </a>
      <a class="jsl-share-button jsl-linkedin" href="https://www.linkedin.com/shareArticle?mini=true&amp;url=--urlEncoded--&amp;title=--titleEncoded--&amp;summary=--messageEncoded--" --openMode-- data-rs="linkedin">
        <svg class="jsl-share-ico"><use href="#linkedin"></use></svg>
        <span class="jsl-share-label">LinkedIn</span>
      </a>
      <a class="jsl-share-button jsl-copylink" href="#" onClick="return shJslCopyToClipboard(event, '--url--'); return false;" data-rs="copy">
        <svg class="jsl-share-ico"><use href="#copylink"></use></svg>
        <span class="jsl-share-label">Copier<span class="done">copié</span></span>
      </a>
</div>
`

let shHtmlTemplateFallBack_svgdefs = `
<svg style="display: none;">
  <defs>
    <symbol id="facebook"   viewBox="0 0 20 20" fill="currentColor"><path d="M17.6 0C18.9 0 20 1 20 2.4v15.2c0 1.3-1 2.4-2.4 2.4h-4.2v-7.5H16l.5-3.3h-3.1v-2c0-1 .4-1.8 1.8-1.8h1.4V2.7s-1.3-.3-2.5-.3C11.6 2.4 10 4 10 6.8v2.4H7.1v3.3h2.8V20H2.4C1.1 20 0 19 0 17.6V2.4C0 1.1 1 0 2.4 0h15.2z"></path></symbol>
    <symbol id="twitter"    viewBox="0 0 23 20" fill="currentColor"><path d="M22.6 3c-.8.4-1.7.6-2.7.7 1-.6 1.7-1.5 2-2.5-.8.5-1.8.9-2.9 1a4.6 4.6 0 00-7.9 4.3c-3.8-.2-7.2-2-9.5-4.8A4.6 4.6 0 003 7.9c-.8 0-1.5-.3-2-.6 0 2.3 1.5 4.2 3.6 4.6a4.7 4.7 0 01-2 0 4.6 4.6 0 004.3 3.3A9.3 9.3 0 010 17c2 1.3 4.5 2 7.1 2A13.1 13.1 0 0020.3 5.5c.9-.7 1.7-1.5 2.3-2.4z"></path></symbol>
    <symbol id="pinterest"  viewBox="0 0 22 22" fill="currentColor"><path d="M11 0a11 11 0 00-4 21.3c-.1-.9-.2-2.2 0-3.2l1.3-5.5S8 12 8 11c0-1.5.9-2.7 2-2.7 1 0 1.4.7 1.4 1.6 0 1-.6 2.3-1 3.6-.2 1.1.6 2 1.7 2 2 0 3.4-2 3.4-5C15.5 7.9 13.7 6 11 6c-3.2 0-5 2.4-5 4.8 0 1 .4 2 .8 2.5v.3L6.7 15c0 .2-.2.2-.4.1-1.4-.6-2.2-2.6-2.2-4.2C4 7.3 6.5 4 11.2 4c3.9 0 6.8 2.7 6.8 6.4s-2.4 6.8-5.7 6.8c-1.1 0-2.1-.6-2.5-1.3l-.7 2.6c-.2 1-1 2.2-1.4 3A11 11 0 1011 0z"/></symbol>
    <symbol id="email"      viewBox="0 0 24 18" fill="currentColor"><path d="M.9 1.5s0 0 0 0l-.1.3-.1.3h0v14a1 1 0 001 1h20.5a1 1 0 001-1V1.9a1 1 0 00-1-1H1.8h0-.3 0-.2 0l-.1.2-.2.1h0l-.1.1v.1s0 0 0 0zm11.6 8.4l8.7-5.3V15H2.8V4l8.6 5.9H11.7l.3.1h.5zM12 7.8L5.1 3h14.7L12 7.8z"></path></symbol>
    <symbol id="gmail"      viewBox="0 0 22 18" fill="currentColor"><path d="M19.8.2H2.2C1 .2 0 1.2 0 2.4v13.2c0 1.2 1 2.2 2.2 2.2h17.6c1.2 0 2.2-1 2.2-2.2V2.4c0-1.2-1-2.2-2.2-2.2zm0 15.4h-2.2V5.9L11 10.1 4.4 5.9v9.7H2.2V2.4h1.3L11 7l7.5-4.6h1.3v13.2z"></path></symbol>
    <symbol id="linkedin"   viewBox="0 0 22 22" fill="currentColor"><path d="M.7 2v18c0 .7.6 1.3 1.4 1.3h17.8c.8 0 1.4-.6 1.4-1.4V2.1c0-.8-.6-1.4-1.4-1.4H2.1C1.3.7.7 1.3.7 2zM6.6 18H4V8.4h2.5v9.5zM5.4 6.5C4.7 6.5 4 6 4 5.3c0-.6.6-1.1 1.3-1.1.6 0 1.2.5 1.2 1.1 0 .7-.6 1.2-1.2 1.2zm12.5 11.4h-2.5V13l-.1-2-.5-.6c-.2-.2-.5-.3-.8-.3-.4 0-.8.1-1.1.4-.4.2-.6.5-.7 1l-.2 2V18H9V8.4h2.5v1.4c.8-1 2-1.6 3.2-1.6.5 0 1 0 1.5.3.5.2.9.4 1 .7.3.4.5.7.6 1.1l.1 1.7v5.9z"></symbol>
    <symbol id="whatsapp"   viewBox="0 0 22 22" fill="currentColor"><path d="M16 13.2l-1.8-.9c-.3 0-.5-.1-.6.1l-1 1.1c0 .2-.2.2-.5 0-.3 0-1.2-.4-2.2-1.3a8.2 8.2 0 01-1.5-1.9c-.2-.2 0-.4 0-.5l.5-.5.3-.5v-.4l-.9-2c-.2-.6-.4-.5-.6-.5h-.5a1 1 0 00-.8.3c-.2.3-1 1-1 2.3 0 1.3 1 2.6 1.2 2.8.1.2 2 3 4.7 4.1l1.5.6c.7.2 1.3.2 1.8 0 .5 0 1.6-.6 1.8-1.2.2-.6.2-1.2.2-1.3l-.6-.3zM11 20c-1.6 0-3.2-.5-4.6-1.3l-.3-.2-3.5 1 1-3.4-.3-.4A9.1 9.1 0 1120.1 11c0 5-4 9-9 9zm7.8-16.8A11 11 0 001.6 16.4L0 22l5.8-1.5a11 11 0 0013-17.3z"/></symbol>
    <symbol id="copylink"   viewBox="0 0 20 22" fill="currentColor"><path d="M14.5 0h-12a2 2 0 00-2 2v14h2V2h12V0zm3 4h-11a2 2 0 00-2 2v14c0 1.1.9 2 2 2h11a2 2 0 002-2V6a2 2 0 00-2-2zm0 16h-11V6h11v14z"/></symbol>
    <symbol id="share"      viewBox="0 0 28 30" fill="currentColor"><path d="M23 21.12C21.86 21.12 20.84 21.57 20.06 22.275L9.365 16.05C9.44 15.705 9.5 15.36 9.5 15C9.5 14.64 9.44 14.295 9.365 13.95L19.94 7.785C20.75 8.535 21.815 9 23 9C25.49 9 27.5 6.99 27.5 4.5C27.5 2.01 25.49 0 23 0C20.51 0 18.5 2.01 18.5 4.5C18.5 4.86 18.56 5.205 18.635 5.55L8.06 11.715C7.25 10.965 6.185 10.5 5 10.5C2.51 10.5 0.5 12.51 0.5 15C0.5 17.49 2.51 19.5 5 19.5C6.185 19.5 7.25 19.035 8.06 18.285L18.74 24.525C18.665 24.84 18.62 25.17 18.62 25.5C18.62 27.915 20.585 29.88 23 29.88C25.415 29.88 27.38 27.915 27.38 25.5C27.38 23.085 25.415 21.12 23 21.12Z"/></symbol>
  </defs>
</svg>
`

/** HTML:END ***********/

/** CSS ****************/
let shWidgetCSS = `
:root {
  --sh-text-color: #000000;
}

[data-theme="dark"] {
  --sh-text-color: #FFFFFF;
}

.share-l214 {
  position: relative;
}
.share-l214 .jsl-share-buttons {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
.share-l214 .jsl-share-button {
  display: flex;
  align-items: center;
  flex-direction: column;

  color: var(--sh-text-color);
  text-decoration: underline;
  margin: 0 15px 12px 15px;
}
@media all and (min-width: 768px) {
  .share-l214 .jsl-share-button {
    flex-direction: row;
  }
}
.share-l214 .jsl-share-button .jsl-share-ico {
  width: 20px;
  height: 20px; 
  box-sizing: content-box;
}
.share-l214 .jsl-share-button:hover .jsl-share-ico {
  transform: scale(.95);
}
.share-l214 .jsl-share-button.jsl-facebook .jsl-share-ico {color: #3b5998 ;}
.share-l214 .jsl-share-button.jsl-twitter .jsl-share-ico {color: #1da1f2;}
.share-l214 .jsl-share-button.jsl-pinterest .jsl-share-ico {color: #E71D27;}
.share-l214 .jsl-share-button.jsl-email .jsl-share-ico {color: #F89B12;}
.share-l214 .jsl-share-button.jsl-gmail .jsl-share-ico {color: #D44F3E;}
.share-l214 .jsl-share-button.jsl-linkedin .jsl-share-ico {color: #0077B5;}
.share-l214 .jsl-share-button.jsl-whatsapp .jsl-share-ico {color: #25D366;}
.share-l214 .jsl-share-button.jsl-copylink .jsl-share-ico {color: var(--sh-text-color);}
.share-l214 .jsl-share-button.jsl-share .jsl-share-ico {color: var(--sh-text-color);}
.share-l214 .jsl-share-button .jsl-share-label {
  font-size: 15px;
  color: var(--sh-text-color);
  font-weight: 700;
  text-transform: uppercase;
  padding-top: 4px;
  margin: 0;
}
@media all and (min-width: 768px) {
  .share-l214 .jsl-share-button .jsl-share-label {
    padding: 0;
    margin-left: 14px;
  }
}  
@media all and (min-width: 768px) {
  .jsl-whatsapp {display: none !important;}
}
.share-l214 .jsl-share-button.jsl-copylink {
  position: relative;
}
.share-l214 .jsl-share-button.jsl-copylink .done {
  position: absolute;
  left: 0; top: 0; right: 0;
  text-align: center;
  text-transform: none;
  font-size: 12px;
  color: var(--sh-text-color);
  opacity: 0;
  transform: translateY(-1em);
  transition: all .500s;
}
.share-l214 .jsl-share-button.jsl-copylink.copied .done {
  opacity: 1;
  transform: translateY(-2em);
}
/* SHARE API CSS */
.share-l214 .jsl-share-button.jsl-share {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;

  background:none;
  color: var(--sh-text-color);
  text-decoration: none;
  border: none;
  outline: none;
}
.share-l214 .jsl-share-button.jsl-share .jsl-share-ico {
    width: 27px;
    height: 30px;
}
.share-l214 .jsl-share-button.jsl-share .jsl-share-label {
    font-size: 18px;
    font-weight: 700;
    text-transform: uppercase;
    color: var(--sh-text-color);
    margin-right: 20px;
}
.share-l214 .jsl-share-button.jsl-share {
  flex-direction: row;
  margin: 0;
}
`
/** CSS:END ************/

function shBuildWidget(widget, noshareapi) {
  if (!widget) {
    return false;
  }

  // Url
  const canonical = shGetCanonicalUrl();
  const url = widget.dataset.url || (canonical ? canonical : window.location.href);

  // Titles
  const title = widget.dataset.title || document.title;
  const titleEmail = widget.dataset.mailTitle || title;

  // Messages
  const metaDescription = shGetAttribute(document.querySelector("meta[name='description']"), 'content');
  const message = widget.dataset.message || (metaDescription ? metaDescription : '');
  const messagePlusUrl = message + ' ' + url;
  const messageEmail = widget.dataset.mailMessage || messagePlusUrl;
  const messageWhatsApp = widget.dataset.whatsappMessage || messagePlusUrl;
  const tweet = widget.dataset.tweet || message;
  const tweetUrl = tweet.indexOf(url) !== -1 ? '' : url;

  // Images
  const metaImage = shGetAttribute(document.querySelector("meta[property='og:image']"), 'content');
  const image = widget.dataset.image || (metaImage ? metaImage : '');

  // Web Share API or Fallback ?
  let shareapi = widget.dataset.shareApi ? widget.dataset.shareApi === "1" : false;
  shareapi = shareapi && typeof navigator.share !== 'undefined';

  // Restrict to specifics verified user agents ?
  const shareapi_agents = widget.dataset.shareApiAgents || '';
  const shareapi_is_allowed = shareapi_agents ? new RegExp(shareapi_agents, 'i').test(navigator.userAgent) : true;
  shareapi = shareapi && shareapi_is_allowed;

  // Temporary : if Web Share API is allowed by verified agents, run an A/B test 
  const test_Ab = shareapi && (widget.dataset.testAb ? widget.dataset.testAb === "1" : false);
  if (test_Ab) {
    shareapi = Math.random() < 0.5;
    // Track result on GA for check
    shGASend('Display', shareapi ? 'Web Share API': 'Share Fallback');
  }

  // Block or Force Web Share API ?
  shareapi = shareapi && !noshareapi;
  shareapi = shareapi || (widget.dataset.forceapishare ? widget.dataset.forceapishare === "1" : false);

  if (shareapi) {
    widget.innerHTML = shHtmlTemplateShareAPI; 

    // Web share API  handlers
    widget.addEventListener('click', function(event) {
      try {
        if (test_Ab) {  
          shGASend('Share', 'Web Share API');
        }
        navigator.share({"title": title, "url": url, "text": message})
      } catch (err) {
        shBuildWidget(widget, true);

        shSentryCapture(err.message);
        console.error(err.message);
      }
    })

    if (typeof(trace) !== 'undefined') {
      trace(widget.dataset, widget, 'Dataset');
      trace({
        navigatorShare: navigator.share,
        navigatorUserAgent: navigator.userAgent,
        shareapi_is_allowed, 
        shareapi,
        test_Ab
      }, widget, 'Config'); 
    } //End trace
  } else {
    // Url paramters : all these url parameters have not empty default values
    widget.innerHTML = shHtmlTemplateFallBack
      .replace(/--url--/g, url)
      .replace(/--urlEncoded--/g, encodeURIComponent(url))
      .replace(/--titleEncoded--/g, encodeURIComponent(title))
      .replace(/--titleMailEncoded--/g, encodeURIComponent(titleEmail))
      .replace(/--messageEncoded--/g, encodeURIComponent(message))
      .replace(/--messagePlusUrlEncoded--/g, encodeURIComponent(messagePlusUrl))
      .replace(/--messageMailEncoded--/g, encodeURIComponent(messageEmail))
      .replace(/--messageWhatsAppEncoded--/g, encodeURIComponent(messageWhatsApp))
      .replace(/--tweetEncoded--/g, encodeURIComponent(tweet))
      .replace(/--imageEncoded--/g, encodeURIComponent(image))
      .replace(/--openMode--/g, `onclick="window.open(this.href, '_blank','left=20,top=20,width=600,height=700,toolbar=0,resizable=1'); return false;"`);
    
    // Optional url parameters (if not empty)
    widget.innerHTML = widget.innerHTML.replace(/--tweetUrlEncodedOptParam--/g, tweetUrl ? '&url=' + encodeURIComponent(tweetUrl) : '');

    // Options
    isPinterest = widget.dataset.pinterest ? (widget.dataset.pinterest === "1") : false;
    isLinkedin = widget.dataset.linkedin ? (widget.dataset.linkedin === "1") : false;
    theme = widget.dataset.theme || 'light';
    widget.innerHTML = widget.innerHTML.replace(/--theme--/g, theme);
    widget.querySelector('.jsl-pinterest').style.display = isPinterest ? '' : 'none';
    widget.querySelector('.jsl-linkedin').style.display = isLinkedin ? '' : 'none';
    widget.querySelector('.jsl-copylink').style.display = navigator.clipboard ? '': 'none';

    widget.addEventListener('click', function(event) {
      const event_target = event.target.closest('.jsl-share-button');
      if (event_target) {
        const button_rs = event_target.getAttribute('data-rs');
        if (test_Ab && button_rs !== 'copy') {
          shGASend('Share', button_rs === 'copy' ? 'Copy' : 'Fallback');
        }
      }
    })

    // Trace function is defined only in demo.html
    if (typeof(trace) !== 'undefined') {
      trace({
        canonical: shGetCanonicalUrl(),
        title: document.title,
        description: metaDescription,
        image: metaImage
      }, widget, 'Metas');
      trace(widget.dataset, widget, 'Dataset');
      trace({
        navigatorClipboard: navigator.clipboard,
        navigatorShare: navigator.share,
        navigatorUserAgent: navigator.userAgent,
        shareapi_is_allowed,
        shareapi,
        test_Ab,
        isPinterest,
        isLinkedin,
      }, widget, 'Config');
      trace_urls(widget, 'Urls');  
    } //End trace
  }
}

function shareL214() {
  if (!shSupportsQuerySelectors) {
    throw {
      id: SH_ERROR_NO_QUERYSELECTORS,
      message: 'querySelector/querySelectorAll methods are not supported on this browser',
    }
  }
  let shareWidgets = document.querySelectorAll(".js-share-l214")
  if (shareWidgets) {
    for (index = 0; index < shareWidgets.length; ++index) {
      const widget = shareWidgets[index];
      shBuildWidget(widget, false);
    }
    // Add SVGs defs
    document.body.insertAdjacentHTML('beforeend', shHtmlTemplateFallBack_svgdefs);
    // Add styles
    shJslAddCss(shWidgetCSS);
  }
}

try {
  document.addEventListener("DOMContentLoaded", function(event) {
    shareL214();
  });
} catch (err) {
  shSentryCapture(err.message);
  console.error(err.message);
}

/* *********************** */
/* ** HELPERS ************ */
/* *********************** */

// Add inline css code into <head>
function shJslAddCss(cssCode)
{
  var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}

// Copy text in clipboard
async function shJslCopyToClipboard(event, text)
{
  /* To prevent url change */
  event = event || window.event;
  event.preventDefault();

  try {
    await navigator.clipboard.writeText(text);

    // 'Copied!' animation trigger
    copyLink = document.querySelector('.jsl-copylink');
    copyLink.classList.add('copied');
    var temp = setInterval( function(){
      copyLink.classList.remove('copied');
      clearInterval(temp);
    }, 600 );
  } catch (err) {
    shSentryCapture(err.message);
    console.error(err.message);
  }
  return false;
}

// Get attribute 'att' of an elements (false if element is invalid or attribute not found)
function shGetAttribute(el, att) {
  if (!el) {
    return false;
  }
  if (!el.hasAttribute(att)) {
    return false;
  }
  return el.getAttribute(att);
}

// Return canonical url of the docuement (false if not found or invalid)
function shGetCanonicalUrl() {
  const canonical_link = document.querySelector("link[rel='canonical']");
  if (!canonical_link) {
    return false;
  }
  return shGetAttribute(canonical_link, "href");
}

// Because querySelector/querySelectorAll are not supported on old IE browsers (6/7/8)
function shSupportsQuerySelectors() {
  return ((document['querySelector'] && document['querySelectorAll']) != null);
}

function shSentryCapture(message) {
  if (typeof Sentry !== "undefined") {
    Sentry.captureException(message);
  }
}

function shGASend(action, label) {
  if (typeof ga !== "undefined") {
    ga('send', {
      hitType: 'event',
      eventCategory: 'Share bar',
      eventAction: action,
      eventLabel: label
    });
  }
}
