//
// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2009
// http://flock.com
//
// This file may be used under the terms of the
// GNU General Public License Version 2 or later (the "GPL"),
// http://www.gnu.org/licenses/gpl.html
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// END FLOCK GPL
//
const CC = Components.classes;
const CI = Components.interfaces;
const URI_FEED_PROPERTIES = "chrome://flock/locale/feeds/feeds.properties";

function $(aID) { return document.getElementById(aID); }

var addFeedUrl = {}

addFeedUrl.accept = function() {
  var url = $("urlBox").value;
  var fixup = Components.classes["@mozilla.org/docshell/urifixup;1"]
                        .getService(Components.interfaces.nsIURIFixup);
  try {
    var uri = fixup.createFixupURI(url, fixup.FIXUP_FLAG_NONE);
    url = uri.spec;
  }
  catch (e) { }

  if (feedUtils.isValidURL(url)) {
    var feedManager = Components.classes["@flock.com/feed-manager;1"]
                                .getService(Components.interfaces.flockIFeedManager);
    var metrics = Components.classes["@flock.com/metrics-service;1"]
                  .getService(Components.interfaces.flockIMetricsService);
    var sbs = CC["@mozilla.org/intl/stringbundle;1"]
              .getService(CI.nsIStringBundleService);
    var prompts = CC["@mozilla.org/embedcomp/prompt-service;1"]
                  .getService(CI.nsIPromptService);
    // Need this constant as a global variable for the listener
    // to have proper scope
    const gFeedProperties = URI_FEED_PROPERTIES;

    var feedManagerListener = {
      onGetFeedComplete: function(feed) {
        feedManager.getFeedContext("news").getRoot().subscribeFeed(feed);
        metrics.report("FeedsSidebar-AddFeed", "AddFeedDialog");
      },
      onError: function(error) {
        var bundle = sbs.createBundle(gFeedProperties);
        prompts.alert(window,
                      bundle.GetStringFromName("flock.feed.add.error.title"),
                      bundle.formatStringFromName("flock.feed.add.error.msg",
                                                  [url],
                                                  1));
      }
    }
    feedManager.getFeed(uri, feedManagerListener);
    return true;
  }
  $("error").removeAttribute("hidden");
  return false;
}
