function mighty_get_url (url)
{
  var l = document.createElement('a')
  l.href = url
  return l
}

function mighty_get_host_name (url)
{
  var domain
  if (typeof url === 'undefined' || url === null || url === '' || url.match(/^\#/)) {
    return ''
  }
  url = mighty_get_url(url)
  if (url.href.search(/^http[s]?:\/\//) !== -1) {
    domain = url.href.split('/')[2]
  } else {
    return ''
  }
  domain = domain.split(':')[0]
  return domain.toLowerCase()
}

function mighty_base64_encode (str)
{
  return btoa(encodeURIComponent(str).replace(
    /%([0-9A-F]{2})/g,
    function toSolidBytes (match, p1) {
      return String.fromCharCode('0x' + p1)
    }
  ))
}

document.addEventListener('DOMContentLoaded', function (event) {
  if (typeof mighty_url === 'undefined') {
    return
  }
  if (typeof mighty_api_token === 'undefined') {
    return
  }
  var advert_type = 1
  if (typeof mighty_type !== 'undefined') {
    if (mighty_type == 2) {
      advert_type = 2
    }
    if (mighty_type == 0) {
      advert_type = 0
    }
  }
  var anchors = document.getElementsByTagName('a')
  if (typeof mighty_domains !== 'undefined') {
    for (var i = 0; i < anchors.length; i++) {
      var hostname = mighty_get_host_name(anchors[i].getAttribute('href'))
      if (hostname.length > 0 && mighty_domains.indexOf(hostname) > -1) {
        anchors[i].href = mighty_url + 'full/?api=' + encodeURIComponent(
          mighty_api_token
        ) + '&url=' + mighty_base64_encode(anchors[i].href) + '&type=' + encodeURIComponent(
          advert_type
        )
      } else {
        if (anchors[i].protocol === 'magnet:') {
          anchors[i].href = mighty_url + 'full/?api=' + encodeURIComponent(
            mighty_api_token
          ) + '&url=' + mighty_base64_encode(anchors[i].href) + '&type=' + encodeURIComponent(
            advert_type
          )
        }
      }
    }
    return
  }
  if (typeof mighty_exclude_domains !== 'undefined') {
    for (var i = 0; i < anchors.length; i++) {
      var hostname = mighty_get_host_name(anchors[i].getAttribute('href'))
      if (hostname.length > 0 && mighty_exclude_domains.indexOf(hostname) === -1) {
        anchors[i].href = mighty_url + 'full/?api=' + encodeURIComponent(
          mighty_api_token
        ) + '&url=' + mighty_base64_encode(anchors[i].href) + '&type=' + encodeURIComponent(
          advert_type
        )
      } else {
        if (anchors[i].protocol === 'magnet:') {
          anchors[i].href = mighty_url + 'full/?api=' + encodeURIComponent(
            mighty_api_token
          ) + '&url=' + mighty_base64_encode(anchors[i].href) + '&type=' + encodeURIComponent(
            advert_type
          )
        }
      }
    }
    return
  }
})
