/**
 * @file
 */

(function ($, Drupal, drupalSettings) {

  'use strict';

  Drupal.nih_extlink = Drupal.nih_extlink || {};

  Drupal.nih_extlink.attach = function (context, drupalSettings) {
    if (!drupalSettings.data.hasOwnProperty('nih_extlink')) {
      return;
    }

    // Strip the host name down, removing ports, subdomains, or www.
    var pattern = /^(([^\/:]+?\.)*)([^\.:]{1,})((\.[a-z0-9]{1,253})*)(:[0-9]{1,5})?$/;
    var host = window.location.host.replace(pattern, '$3$4');
    var subdomain = window.location.host.replace(pattern, '$1');

    // Determine what subdomains are considered internal.
    var subdomains;
    if (drupalSettings.data.nih_extlink.extSubdomains) {
      subdomains = '([^/]*\\.)?';
    }
    else if (subdomain === 'www.' || subdomain === '') {
      subdomains = '(www\\.)?';
    }
    else {
      subdomains = subdomain.replace('.', '\\.');
    }

    // Build regular expressions that define an internal link.
    var internal_link = new RegExp('^https?://' + subdomains + host, 'i');

    // Extra internal link matching.
    var extInclude = false;
    if (drupalSettings.data.nih_extlink.extInclude) {
      extInclude = new RegExp(drupalSettings.data.nih_extlink.extInclude.replace(/\\/, '\\'), 'i');
    }

    // Extra external link matching.
    var extExclude = false;
    if (drupalSettings.data.nih_extlink.extExclude) {
      extExclude = new RegExp(drupalSettings.data.nih_extlink.extExclude.replace(/\\/, '\\'), 'i');
    }

    // Extra external link CSS selector exclusion.
    var extCssExclude = false;
    if (drupalSettings.data.nih_extlink.extCssExclude) {
      extCssExclude = drupalSettings.data.nih_extlink.extCssExclude;
    }

    // Extra external link CSS selector explicit.
    var extCssExplicit = false;
    if (drupalSettings.data.nih_extlink.extCssExplicit) {
      extCssExplicit = drupalSettings.data.nih_extlink.extCssExplicit;
    }

    // Find all links which are NOT internal and begin with http as opposed
    // to ftp://, javascript:, etc. other kinds of links.
    // When operating on the 'this' variable, the host has been appended to
    // all links by the browser, even local ones.
    // In jQuery 1.1 and higher, we'd use a filter method here, but it is not
    // available in jQuery 1.0 (Drupal 5 default).
    var external_links = [];
    var mailto_links = [];
    $('a:not(.' + drupalSettings.data.nih_extlink.extClass + ', .' + drupalSettings.data.nih_extlink.mailtoClass + '), area:not(.' + drupalSettings.data.nih_extlink.extClass + ', .' + drupalSettings.data.nih_extlink.mailtoClass + ')', context).each(function (el) {
      try {
        var url = '';
        if (typeof this.href == 'string') {
          url = this.href.toLowerCase();
        }
        // Handle SVG links (xlink:href).
        else if (typeof this.href == 'object') {
          url = this.href.baseVal;
        }
        if (url.indexOf('http') === 0
          && ((!url.match(internal_link) && !(extExclude && url.match(extExclude))) || (extInclude && url.match(extInclude)))
          && !(extCssExclude && $(this).parents(extCssExclude).length > 0)
          && !(extCssExplicit && $(this).parents(extCssExplicit).length < 1)) {
          external_links.push(this);
        }
        // Do not include area tags with begin with mailto: (this prohibits
        // icons from being added to image-maps).
        else if (this.tagName !== 'AREA'
          && url.indexOf('mailto:') === 0
          && !(extCssExclude && $(this).parents(extCssExclude).length > 0)
          && !(extCssExplicit && $(this).parents(extCssExplicit).length < 1)) {
          mailto_links.push(this);
        }
      }
        // IE7 throws errors often when dealing with irregular links, such as:
        //  Empty tags.
        // example User:pass syntax.
      catch (error) {
        return false;
      }
    });

    if (drupalSettings.data.nih_extlink.extClass) {
      Drupal.nih_extlink.applyClassAndSpan(external_links, drupalSettings.data.nih_extlink.extClass);
    }

    if (drupalSettings.data.nih_extlink.mailtoClass) {
      Drupal.nih_extlink.applyClassAndSpan(mailto_links, drupalSettings.data.nih_extlink.mailtoClass);
    }

    if (drupalSettings.data.nih_extlink.extTarget) {
      // Apply the target attribute to all links.
      if (drupalSettings.data.nih_extlink.extTarget) {
        $(external_links).attr({target:'_blank', rel:'nofollow'});
        $(external_links).attr('rel', function (i, val) {
          // If no rel attribute is present, create one with the values noopener and noreferrer.
          if (val === null) {
            return 'noopener noreferrer';
          }
          // Check to see if rel contains noopener or noreferrer. Add what doesn't exist.
          if (val.indexOf('noopener') > -1 || val.indexOf('noreferrer') > -1) {
            if (val.indexOf('noopener') === -1) {
              return val + ' noopener';
            }
            if (val.indexOf('noreferrer') === -1) {
              return val + ' noreferrer';
            }
            // Both noopener and noreferrer exist. Nothing needs to be added.
            else {
              return val;
            }
          }
          // Else, append noopener and noreferrer to val.
          else {
            return val + ' noopener noreferrer';
          }
        });
      }
    }

      Drupal.nih_extlink = Drupal.nih_extlink || {};

      if(drupalSettings.data.nih_extlink.extAlert){
          $('<div id="extlink-modal" />').dialog({
              autoOpen:false,
              show:{effect:"fade"},
              hide:{effect:"fade"},
              width:600,
              modal:true,
              resizable:false,
              dialogClass:"modal-content",
              buttons: [
                  {
                      text: "OK",

                      click: function() {
                          $( this ).dialog( "close" );
                      }
                  },

              ],
              title:drupalSettings.data.nih_extlink.extIconAlertTitle,
              appendTo:"body"
          }).addClass("extButtonClass");
      }

      // Set up default click function for the external links popup. This should be
      // overridden by modules wanting to alter the popup.
      Drupal.nih_extlink.popupClickHandler = Drupal.nih_extlink.popupClickHandler || function () {
          if (drupalSettings.data.nih_extlink.extAlert && !drupalSettings.data.nih_extlink.extIconAlert  ) {
            return confirm (drupalSettings.data.nih_extlink.extAlertText);
          }
      };


      $(external_links).click(function (e) {
          return Drupal.nih_extlink.popupClickHandler(e, this);
      });
  };

  /**
   * Apply a class and a trailing <span> to all links not containing images.
   *
   * @param {object[]} links
   *   An array of DOM elements representing the links.
   * @param {string} class_name
   *   The class to apply to the links.
   */
  Drupal.nih_extlink.applyClassAndSpan = function (links, class_name) {
    var $links_to_process;
    if (drupalSettings.data.nih_extlink.extImgClass) {
      $links_to_process = $(links);
    }
    else {
      var links_with_images = $(links).find('img').parents('a');
      $links_to_process = $(links).not(links_with_images);
    }
    $links_to_process.addClass(class_name);
    var i;
    var length = $links_to_process.length;
    for (i = 0; i < length; i++) {
      var $link = $($links_to_process[i]);
      if ($link.css('display') === 'inline' || $link.css('display') === 'inline-block' || $link.css('display') === 'block') {

        if (class_name === drupalSettings.data.nih_extlink.mailtoClass) {
          $link.append('<span class="' + class_name + '"><span class="element-invisible"> ' + 'mailto:' +  drupalSettings.data.nih_extlink.mailtoLabel + '</span></span>');
        }  // IF custom behavior is added
         else if(drupalSettings.data.nih_extlink.extIconAlert) {
           if (drupalSettings.data.nih_extlink.extLabel.length > 0) {
              $link.after('<a class="' + class_name + '-icon" href="#"><span class="element-invisible"> ' + drupalSettings.data.nih_extlink.extLabel + '</span></a>')
           }
           else {
              $link.after('<a class="' + class_name + '-icon" href="#"><span class="element-invisible"> external link </span></a>')
           }
              if(parseInt(drupalSettings.data.nih_extlink.extlinkIconDisplay)){
                  $link.next().attr("target","_blank");
              }
              else {
                  // Create modal and fetch content via ajax
                  $link.next().bind("click",function(e){
                      e.preventDefault();
                      if($("#extlink-modal").is(":empty")){
                         $("#extlink-modal").html(drupalSettings.data.nih_extlink.extIconAlertText).dialog("open");
                      } else {
                          //Message has already been loaded, just open the modal
                          $("#extlink-modal").dialog("open");

                      }
                  });
              }
          }
        else {
          if (drupalSettings.data.nih_extlink.extLabel.length > 0) {
            $link.append('<span class="' + class_name + '"><span class="element-invisible"> ' + drupalSettings.data.nih_extlink.extLabel + '</span></span>');
          }
          else {
            $link.append('<span class="' + class_name + '"><span class="element-invisible">external link</span></span>');
          }
        }
      }
    }
  };

  Drupal.behaviors.nih_extlink = Drupal.behaviors.nih_extlink || {};
  Drupal.behaviors.nih_extlink.attach = function (context, drupalSettings) {
    // Backwards compatibility, for the benefit of modules overriding extlink
    // functionality by defining an "extlinkAttach" global function.
    if (typeof extlinkAttach === 'function') {
      extlinkAttach(context);
    }
    else {
      Drupal.nih_extlink.attach(context, drupalSettings);
    }
  };

})(jQuery, Drupal, drupalSettings);