/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-2016 Eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

//
// This file has been generated automatically, relevant repositories:
// * https://hg.adblockplus.org/jshydra/
//

"use strict";
if ("ext" in window && document instanceof HTMLDocument)
{
  document.addEventListener("click", function(event)
  {
    if (event.button == 2)
    {
      return;
    }
    if (event.isTrusted == false)
    {
      return;
    }
    var link = event.target;
    while (!(link instanceof HTMLAnchorElement))
    {
      link = link.parentNode;
      if (!link)
      {
        return;
      }
    }
    var queryString = null;
    if (link.protocol == "http:" || link.protocol == "https:")
    {
      if (link.host == "subscribe.adblockplus.org" && link.pathname == "/")
      {
        queryString = link.search.substr(1);
      }
    }
    else
    {
      var match = /^abp:\/*subscribe\/*\?(.*)/i.exec(link.href);
      if (match)
      {
        queryString = match[1];
      }
    }
    if (!queryString)
    {
      return;
    }
    event.preventDefault();
    event.stopPropagation();
    var params = queryString.split("&");
    var title = null;
    var url = null;
    for (var i = 0; i < params.length; i++)
    {
      var parts = params[i].split("=", 2);
      if (parts.length != 2 || !/\S/.test(parts[1]))
      {
        continue;
      }
      switch (parts[0])
      {
      case "title":
        title = decodeURIComponent(parts[1]);
        break;
      case "location":
        url = decodeURIComponent(parts[1]);
        break;
      }
    }
    if (!url)
    {
      return;
    }
    if (!title)
    {
      title = url;
    }
    title = title.trim();
    url = url.trim();
    if (!/^(https?|ftp):/.test(url))
    {
      return;
    }
    ext.backgroundPage.sendMessage(
    {
      type: "subscriptions.add",
      title: title,
      url: url,
      confirm: true
    });
  }, true);
}
