<script type="text/javascript">
(function() {
  
  'use strict';

  var sTwitterScriptID = 'shortpoint-twitter-script';

  /**
   * hook method to be executed as soon as shortpoint
   * is available in the page
   */
  function initHook() {

    // exit on edit mode
    if( window.shortPointInserter ) {
        return;
    }

    setTimeout(listenToTabChanges, 500);
  };

  /**
   * whenever a tab is clicked, we need to listen
   */
  function listenToTabChanges() {
    var $ = shortpoint.$;
    var $initialActiveContent = $('.shortpoint-tab-pane.shortpoint-active');
    $('body').on('shown.bs.tab', '[data-toggle="tab"]', function(e) {
      var $self = $(this);
      var sTwitterScriptID = "twitter-script";
      var $content = $( $self.attr( 'href' ) );
      checkTabContent( $content );
      
    });

    if( $initialActiveContent.length ) {
      checkTabContent( $initialActiveContent );
    }
  }

  /**
   * checks a content of a tab if it contains a twitter
   * link, then it will inject the script accordingly
   */
  function checkTabContent( $tabContentRoot ) {
    var $ = shortpoint.$;
    var $twitterLink = $tabContentRoot.find('a[href*="twitter.com"]');

    if( $twitterLink.length && $('#' + sTwitterScriptID).length === 0 ) {
      injectTwitterScript();
    }
  }

  /**
   * inject twitter script tag
   */
  function injectTwitterScript() {
    // shortpoint is ready and rendered on the page
    var jsElm = document.createElement('script');
    // set the type attribute
    jsElm.type = 'application/javascript';
    // mark the script tag for easier retrieval
    jsElm.setAttribute( 'id', sTwitterScriptID );
    // make the script element load file
    jsElm.src = '//platform.twitter.com/widgets.js';
    // finally insert the element to the body element in order to load the script
    document.body.appendChild(jsElm);
  }

  // shortpoint not yet available in the page
  // wait for shortpoint ready dom event
  document.addEventListener( 'shortpoint-render-above-fold', initHook );

})();
</script>