// 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
Components.utils.import("resource:///modules/FlockStringBundleHelpers.jsm");

var feedManager;
var subscriptionTree;
var currentWindow;
var contentBrowser;
var promptService;
var dragService;
var scrollTimer;
var windowManager;

var gMetrics =  Components.classes["@flock.com/metrics-service;1"]
                .getService(Components.interfaces.flockIMetricsService);
var faves = Components.classes['@mozilla.org/rdf/datasource;1?name=flock-favorites'].getService(Components.interfaces.nsIRDFDataSource);
var faves_coop = Components.classes["@flock.com/singleton;1"]
                           .getService(Components.interfaces.flockISingleton)
                           .getSingleton("chrome://flock/content/common/load-faves-coop.js")
                           .wrappedJSObject;
const NEWS_FEED_ROOT = "urn:flock:feedcontext:news";
const URI_FEED_PROPERTIES = "chrome://flock/locale/feeds/feeds.properties";
const PREF_AUTO_MARK_AS_READ = "flock.feeds.auto_mark_as_read";

var gPrefs;
var gRdfInitObserver;
var gRdfSvc = Components.classes["@mozilla.org/rdf/rdf-service;1"]
              .getService(Components.interfaces.nsIRDFService);
var gFavesRDF = Components.classes["@mozilla.org/rdf/datasource;1?name=flock-favorites"]
                .getService(Components.interfaces.flockIRDFObservable);
var gLogger = Components.classes["@flock.com/logger;1"]
              .createInstance(Components.interfaces.flockILogger);
gLogger.init("newsSidebar");

var gRefreshQueue = {};

function _getSupportedFlavours() {
  var flavors = new FlavourSet();
  flavors.appendFlavour("application/x-moz-file", "nsIFile");
  flavors.appendFlavour("text/x-moz-url");
  return flavors;
}

var newsDNDObserver = {

  onDragOver: function(aEvent, aFlavor, aSession) {
    dump("newsDNDObserver: onDragOver\n");
  },
    
  onDragEnter: function(aEvent, aSession) {
    dump("newsDNDObserver: onDragEnter\n");
  },
    
  onDragExit: function(aEvent, aSession) {
    dump("newsDNDObserver: onDragExit\n");
  },

  onDragStart: function(event, transferData, action) {
    var index = subscriptionTree.view.selection.currentIndex;
    if(index != -1) {
      var id = subscriptionTree.builder.getResourceAtIndex(index).ValueUTF8;
      var title = subscriptionTree.view.getCellText(index, subscriptionTree.columns.getNamedColumn("title"));
      var type = subscriptionTree.view.getCellText(index, subscriptionTree.columns.getNamedColumn("type"));
    } else {
      return;
    }
    transferData.data = new TransferData();
    transferData.data.addDataForFlavour("moz/rdfitem", id);
  },
  
  onDrop: function(aEvent, aDropData, aSession) {
    dump("newsDNDObserver: onDrop: contentType: " + aDropData.flavour.contentType + " data: " + aDropData.data + "\n");
    switch(aDropData.flavour.contentType) {
      case "application/x-moz-file":
        var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
        var fileHandler = ios.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
        var url = fileHandler.getURLSpecFromFile(aDropData.data);
        break;
      case "text/x-moz-url":
        var url = aDropData.data.split("\n")[0];
        break;
    }
    //var feedService = Components.classes["@flock.com/feed-service;1"].getService(Components.interfaces.flockIFeedService);
    //feedService.subscribeFeed(url, null, null, false);
  },
  
  getSupportedFlavours: function() {
    return _getSupportedFlavours();
  }
  
}

var feedsContainerObserver = {

  canDrop: function(aDOMNode, aOrientation) {
    // Can drop on any node, any orientation
    return true;
  },
  
  onDrop: function(aDOMNode, aOrientation, aDropData) {
    var getFeedParent = function (aCoopFeed) {
      var parents = aCoopFeed.getParents();
      for (var i = 0; i < parents.length; i++) {
        if (parents[i].isA(faves_coop.FeedFolder) ||
            parents[i].id() == NEWS_FEED_ROOT)
        {
          return parents[i];
        }
      }
      return null;
    };

    var coopFeed = faves_coop.get(aDropData.data);

    var newsContext = feedManager.getFeedContext('news');
    var url = aDropData.data.split("\n")[0];
    var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
    var uri = ios.newURI(url, null, null);
    
    // Drop on the root
    if (aDOMNode.localName.toLowerCase() == "richtree") {
      if (!coopFeed) {
        // Add new feed
        var feedRoot = feedManager.getFeedContext("news").getRoot();
        feedManager.getFeed(uri, {
          onGetFeedComplete: function fm_onGetFeedComplete(aFeed) {
            feedRoot.subscribeFeed(aFeed);
            gMetrics.report("FeedsSidebar-AddFeed", "FeedsSidebarDrop");
          },
          onError: function fm_onError(aError) {
          }
        });
      } else {
        // Move an existing feed
        // Remove from the original parent
        var parent = getFeedParent(coopFeed);
        parent.children.remove(coopFeed);

        // Add to the root
        var feedRoot = faves_coop.get(NEWS_FEED_ROOT);
        feedRoot.children.add(coopFeed);
      }
    } else {
      // Calculate insert folder and position
      var pos;
      var target = faves_coop.get(aDOMNode.id);
      var newParent;
      if (target.isA(faves_coop.FeedFolder) && aOrientation == "on") {
        newParent = target;
        pos = -1;
      } else {
        newParent = getFeedParent(target);
        pos = newParent.children.indexOf(target);
        if (aOrientation == "after") {
          pos++;
        }
      }

      if (!coopFeed) {
        // Add new feed.
        var feedFolder = feedManager.getFeedFolderItem(newParent.id());
        feedManager.getFeed(uri, {
          onGetFeedComplete: function fm_onGetFeedComplete(aFeed) {
            feedFolder.subscribeFeed(aFeed);
            gMetrics.report("FeedsSidebar-AddFeed", "FeedsSidebarDrop");
          },
          onError: function fm_onError(aError) {
          }
        });
      } else {
        // Move an existing feed.
        // If someone drops a folder on itself...
        if (coopFeed.id() == newParent.id() ||
            isAncestor(coopFeed, newParent))
        {
          return;
        }

        // Remove from the original parent
        var parent = getFeedParent(coopFeed);
        parent.children.remove(coopFeed);

        // Add to the new parent
        if (pos < 0) {
          newParent.children.add(coopFeed);
        } else {
          newParent.children.insertAt(coopFeed, pos++);
        }
      }
    }
  },
  
  onDragStart: function(aDOMNode) {
  },

  getSupportedFlavours: function() {
    return _getSupportedFlavours();
  }
}

var dropListener = {
  handleEvent: function(event) {
    var dragService = Components.classes["@mozilla.org/widget/dragservice;1"].getService(Components.interfaces.nsIDragService);
    var dragSession = dragService.getCurrentSession();
    var transferable = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
    transferable.addDataFlavor("text/unicode");
    dragSession.getData(transferable, 0);
    var flavor = {};
    var data = {};
    var length = {};
    transferable.getAnyTransferData(flavor, data, length);
    
    var subscribeURL = Components.classes["@mozilla.org/network/standard-url;1"].createInstance(Components.interfaces.nsIStandardURL);
    subscribeURL.init(Components.interfaces.nsIStandardURL.URLTYPE_STANDARD, -1, data.value.QueryInterface(Components.interfaces.nsISupportsString).data.split("\n")[0], null, null);
    subscribeURL.QueryInterface(Components.interfaces.nsIURL);
    
    var feedManagerListener = {
      onGetFeedComplete: function(feed) {
        if (event.target.localName.toLowerCase() == "richtree") {
          feedManager.getFeedContext("news").getRoot().subscribeFeed(feed);
          gMetrics.report("FeedsSidebar-AddFeed", "FeedsSidebarDropTree");
          return;
        }
        var targetItem = feedManager.getFeedFolderItem(event.target.id);
        var insertPos = event.target.getAttribute("insertPos");
        var parentFolder = targetItem.getFolder();
        if (targetItem instanceof Components.interfaces.flockIFeed) {
          parentFolder.subscribeFeedWithPosition(feed, targetItem, parentFolder.ORIENT_BELOW);
          gMetrics.report("FeedsSidebar-AddFeed", "FeedsSidebarDropTree");
        }
        if (targetItem instanceof Components.interfaces.flockIFeedFolder) {
          var orientation;
          switch (insertPos) {
            case "before": orientation = parentFolder.ORIENT_ABOVE; break;
            case "on": orientation = parentFolder.ORIENT_INSIDE; break;
            case "after": orientation = parentFolder.ORIENT_BELOW; break;
          }
          parentFolder.subscribeFeedWithPosition(feed, targetItem, orientation);
          gMetrics.report("FeedsSidebar-AddFeed", "FeedsSidebarDropTree");
        }
      },
      onError: function(error) {
      }
    }
    
    feedManager.getFeed(subscribeURL, feedManagerListener);
  }
}

function init() {
  gMetrics.report("FeedsSidebar-Opened", null);

  feedManager = Components.classes["@flock.com/feed-manager;1"].getService(Components.interfaces.flockIFeedManager);
  
  subscriptionTree = document.getElementById("feedsContainer");
  
  subscriptionTree.addEventListener("richtreedrop", dropListener, true);
  subscriptionTree.addObserver(feedsContainerObserver);
  
  promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  dragService = Components.classes["@mozilla.org/widget/dragservice;1"].getService(Components.interfaces.nsIDragService);
  scrollTimer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
  windowManager = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);

  gPrefs = Components.classes["@mozilla.org/preferences-service;1"]
           .getService(Components.interfaces.nsIPrefBranch);

  currentWindow = windowManager.getMostRecentWindow("navigator:browser");
  contentBrowser = currentWindow.document.getElementById('content');

  addFeedRefreshObservers();
}

function updateSelection() {
  if(contentBrowser.currentURI.scheme == "feed" || contentBrowser.currentURI.scheme == "feeds") {
    var feedUrl = decodeURIComponent(contentBrowser.currentURI.spec.split(contentBrowser.currentURI.scheme + ":")[1]);
    dump("feedUrl: " + feedUrl + "\n");
    for (var c = 0; c < subscriptionTree.view.rowCount; c++) {
      switch (subscriptionTree.view.getCellText(c, subscriptionTree.columns.getNamedColumn("type"))) {
        case "feed":
          if (subscriptionTree.builder.getResourceAtIndex(c).ValueUTF8 == feedUrl) {
            subscriptionTree.view.selection.select(c);
          }
          break;
        case "root":
          if (feedUrl == "") {
            subscriptionTree.view.selection.select(c);
          }
          break;
        case "collection":
          if (feedUrl == subscriptionTree.view.getCellText(c, subscriptionTree.columns.getNamedColumn("title"))) {
            subscriptionTree.view.selection.select(c);
          }
          break;
        case "flagged_collection":
          if (feedUrl == "saved") {
            subscriptionTree.view.selection.select(c);
          }
          break;
      }
    }
  }
}

function close() {
  gMetrics.report("FeedsSidebar-Close", null);
  removeFeedRefreshObservers();
}

function doOnClick(aEvent) {
  dump("News: onClick\n");
  var obj = {};
  var row = {};
  subscriptionTree.treeBoxObject.getCellAt(aEvent.clientX,
                                           aEvent.clientY,
                                           row,
                                           {},
                                           obj);
  row = row.value;
  if (aEvent.button == 2 ||
     aEvent.originalTarget.localName.toLowerCase() != "treechildren" ||
     row == -1)
  {
    return;
  }
  if (obj.value == "twisty") {
    return;
  }
  renderContent(aEvent);
}

function doOnKeyPress(event) {
  dump("News: onKeyPress: " + event.keyCode + "\n");
  if (event.keyCode == 38 || event.keyCode == 40) {
    var timerCallback = {
      notify: function doOnKeyPress_notify(aTimer) { renderContent(event); }
    }
    scrollTimer.cancel();
    scrollTimer.initWithCallback(timerCallback, 400, scrollTimer.TYPE_ONE_SHOT);
  }
}

function renderContent(aEvent) {
  var index = subscriptionTree.view.selection.currentIndex;
  if(index != -1) {
    var id = subscriptionTree.builder.getResourceAtIndex(index).ValueUTF8;
    var title = subscriptionTree.view.getCellText(index, subscriptionTree.columns.getNamedColumn("title"));
    var type = subscriptionTree.view.getCellText(index, subscriptionTree.columns.getNamedColumn("type"));
  } else {
    return;
  }
  
  dump("News: index: " + index + " type: " + type + " id: " + id + "\n");
  
  switch (type) {
    case "feed":
      currentWindow.FlockTabs.openURL("feeds:" + encodeURIComponent(id),
                                      aEvent);
      break;
    case "root":
      currentWindow.FlockTabs.openURL("feeds:", aEvent);
      break;
    case "collection":
      currentWindow.FlockTabs.openURL("feeds:" + encodeURIComponent(title),
                                      aEvent);
      break;
    case "flagged_collection":
      currentWindow.FlockTabs.openURL("feeds:saved", aEvent);
      break;
  }
  
  var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
  if (prefs.getBoolPref("flock.feeds.auto_mark_as_read", true)) {
    if (type != "root") {
      function latentMark() {
        //feedService.markAllRead(id);
        subscriptionTree.view.selection.select(index);
      }
      setTimeout(latentMark, 500);
    }
  }
}

function newFolder(event) {
  var check = {value: false};
  var input = {value: ""};
  var strBundle = document.getElementById('stringBundle');
  var result = promptService.prompt(null,
    strBundle.getString("flock.feed.createNewFolder.title"),
    strBundle.getString("flock.feed.createNewFolder.msg"), input, null, check);
  if (result) {
    try {
      feedManager.getFeedContext("news").getRoot().addFolder(input.value);
    } catch (ex) {
      var errTitle =
        strBundle.getString("flock.feed.addFolder.error.title");
      var errMsg =
        strBundle.getFormattedString("flock.feed.folderTitle.error.msg",
                                     [input.value]);
      promptService.alert(null, errTitle, errMsg);
    }
  }
}

function editItem(event) {
  var urn = subscriptionTree.selectedItem.id;
  var item = feedManager.getFeedFolderItem(urn);
  
  var check = {value: false};
  var input = {value: item.getTitle()};
  var strBundle = document.getElementById('stringBundle');
  if (item instanceof Components.interfaces.flockIFeed) {
    var result =
      promptService.prompt(null,
                           strBundle.getString("flock.feed.editFeed.title"),
                           strBundle.getString("flock.feed.editFeed.msg"),
                           input, null, check);
    if (result) {
      item.setTitle(input.value);
    }
  } else if (item instanceof Components.interfaces.flockIFeedFolder) {
    var result =
      promptService.prompt(null,
                           strBundle.getString("flock.feed.renameFolder.title"),
                           strBundle.getString("flock.feed.editFolder.msg"),
                           input, null, check);
    if (result) {
      try {
        item.setTitle(input.value);
      } catch (ex) {
        var errTitle =
          strBundle.getString("flock.feed.renameFolder.error.title");
        var errMsg =
          strBundle.getFormattedString("flock.feed.folderTitle.error.msg",
                                       [input.value]);
        promptService.alert(null, errTitle, errMsg);
      }
    }
  }
}

function deleteItem(event) {
  var urn = subscriptionTree.selectedItem.id;
  var item = feedManager.getFeedFolderItem(urn);
  if (item instanceof Components.interfaces.flockIFeed) {
    item.getFolder().unsubscribeFeed(item);
  }
  if (item instanceof Components.interfaces.flockIFeedFolder) {
    item.getFolder().removeFolder(item);
  }
}

function markAsRead() {
  var urn = subscriptionTree.selectedItem.id;
  feedManager.getFeedFolderItem(urn).markRead();
}

function addFeedRefreshObservers() {
  var winMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                    .getService(Components.interfaces.nsIWindowMediator);
  gRdfInitObserver = {
    rdfChanged: function feeds_rdfChanged(aDataSource,
                                          aType,
                                          aSource,
                                          aPredicate,
                                          aTarget,
                                          aOldTarget)
    {
      if (!aSource) {
        gLogger.error("rdfChanged: aSource is null");
        return;
      }
      var coopId = aSource.ValueUTF8;
      var domNode = document.getElementById(coopId);
      if (domNode) {
        var coopFeed = faves_coop.Feed.get(coopId, aSource);
        if (!coopFeed) {
          return;
        }
        // There is only one image child, being the favicon
        var favicon = domNode.getElementsByTagName("image")[0];
        if (!coopFeed.isRefreshing) {
          var originalFavicon = favicon.getAttribute("oldSrc");
          if (originalFavicon) {
            // Replace original favIcon to indicate the feed is up to date
            favicon.setAttribute("src", originalFavicon);
            favicon.setAttribute("class", "itemIcon");
            favicon.removeAttribute("oldSrc");
            // If a single node has been added to the queue, remove it
            if (gRefreshQueue[coopId]) {
              delete gRefreshQueue[coopId];
            }
          }
          // Check to see if this folder's transaction is complete
          var parent = domNode.parentNode;
          if (parent) {
            checkForRefreshTxnComplete(parent);
          }
          // If currently viewing the feed, refresh the page
          var win = winMediator.getMostRecentWindow("navigator:browser");
          if (win) {
            var currentURI =
                decodeURIComponent(win.getBrowser().currentURI.spec);
            if (currentURI.indexOf(coopId) != -1) {
              win.getBrowser().reload();
            }
          }
        }
      }
    }
  };
  // Add RDF observer
  gFavesRDF.addArcObserver(Components.interfaces
                                     .flockIRDFObserver.TYPE_CHANGE,
                           null,
                           gRdfSvc.GetResource("http://flock.com/rdf#isRefreshing"),
                           null,
                           gRdfInitObserver);
}

function removeFeedRefreshObservers() {
  // Remove the RDF observer
  gFavesRDF.removeArcObserver(Components.interfaces
                                        .flockIRDFObserver.TYPE_CHANGE,
                              null,
                              gRdfSvc.GetResource("http://flock.com/rdf#isRefreshing"),
                              null,
                              gRdfInitObserver);
}

function checkForRefreshTxnComplete(aFolder) {
  var folderId = aFolder.getAttribute("id");
  // Update the folder count
  if (folderId && gRefreshQueue[folderId]) {
    gRefreshQueue[folderId]--;
    if (gRefreshQueue[folderId] == 0) {
      if (aFolder.hasAttribute("oldClass")) {
        aFolder.setAttribute("class", aFolder.getAttribute("oldClass"));
        aFolder.removeAttribute("oldClass");
      }
      delete gRefreshQueue[folderId];
    }
    if (folderId != "feedsContainer") {
      checkForRefreshTxnComplete(aFolder.parentNode);
    }
  }
}

function initFeedItemThrobber(aFavicon) {
  // first check if this is not already refreshing
  var src = aFavicon.getAttribute("src");
  if (src) {
    // Save the favicon source for future retrieval
    aFavicon.setAttribute("oldSrc", src);
    // Give the favicon an OS specific throbber while refreshing
    aFavicon.removeAttribute("src");
    aFavicon.setAttribute("class", "itemIconThrobber");
  }
}

function initThrobberNodes(aNode) {
  var nodeId = aNode.id;
  var feedCount = 0;
  for each (var childNode in aNode.childNodes) {
    switch (childNode.nodeName) {
    // Register how many feeds need to be updated with the folder id
      case "richtreefolder":
        feedCount+= initThrobberNodes(childNode);
        break;
      case "richtreeitem":
        feedCount++;
        // There is only one image child, being the favicon
        var favicon = childNode.getElementsByTagName("image")[0];
        initFeedItemThrobber(favicon);
        break;
    }
  }
  if (feedCount) {
    gRefreshQueue[nodeId] = feedCount;
    if (nodeId != "feedsContainer" && !aNode.hasAttribute("oldClass")) {
      aNode.setAttribute("oldClass", aNode.getAttribute("class"));
      aNode.setAttribute("class", "folderThrobber");
    }
  }
  return feedCount;
}

function refreshFeeds(aType) {
  var feedManager = Components.classes["@flock.com/feed-manager;1"]
                    .getService(Components.interfaces.flockIFeedManager);
  if (aType == "all") {
    var allFeeds = document.getElementById("feedsContainer");
    initThrobberNodes(allFeeds);
    feedManager.getFeedContext("news").refresh();
  } else {
    var selectedNode = subscriptionTree.selectedItem;
    if (!selectedNode) {
      return;
    }
    var nodeId = selectedNode.id;
    var feedFolderItem = feedManager.getFeedFolderItem(nodeId);
    if (feedFolderItem) {
      if (feedFolderItem instanceof Components.interfaces.flockIFeed) {
        gRefreshQueue[nodeId] = true;
        initFeedItemThrobber(selectedNode.getElementsByTagName("image")[0]);
      } else if (feedFolderItem instanceof Components.interfaces
                                                     .flockIFeedFolder)
      {
        initThrobberNodes(selectedNode);
      }
      feedFolderItem.refresh();
    }
  }
}

function onFeedContextShowing(aEvent) {
  var selectedNode = subscriptionTree.selectedItem;
  if (!selectedNode && subscriptionTree.rowCount) {
    return false;
  }

  var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
            .getService(Components.interfaces.nsIStringBundleService);
  var bundle = sbs.createBundle(URI_FEED_PROPERTIES);

  var label = null;
  var isQueued = gRefreshQueue[selectedNode.id];

  switch (selectedNode.nodeName) {
    case "richtreeitem":
      label = bundle.GetStringFromName("flock.feed.context.refreshFeed");
      // Check to see if we are already refreshing this feed via the parent
      if (!isQueued) {
        isQueued = gRefreshQueue[selectedNode.parentNode.id];
      }
      break;
    case "richtreefolder":
      label = bundle.GetStringFromName("flock.feed.context.refreshFolder");
      break;
    default:
      break;
   }

   var menuitem = document.getElementById("updateFeedMenuitem");
   if (label) {
     menuitem.setAttribute("label", label);
     menuitem.removeAttribute("hidden");
   } else {
     menuitem.setAttribute("hidden", true);
   }

   // If we are currently refreshing this node, disable the command
   if (isQueued) {
     menuitem.setAttribute("disabled", "true");
   } else {
     menuitem.removeAttribute("disabled");
   }
   // If refresh all is currently running, disabled the command
   feedOptionsContextShowing("refreshAllContext");
}

function feedOptionsContextShowing(aElementId) {
  // If refresh all is currently running, disabled the command
  var optionsRefreshAll = document.getElementById(aElementId);
  if (optionsRefreshAll) {
    if (gRefreshQueue["feedsContainer"]) {
      optionsRefreshAll.setAttribute("disabled", "true");
    } else {
      optionsRefreshAll.removeAttribute("disabled");
    }
  }
  initAutoMarkAsReadCheckmark();
}

function onClickItem(aEvent, aObj) {
  var clearSelectionId = aObj.getAttribute("clearSelectionId");
  if (clearSelectionId) {
    document.getElementById(clearSelectionId).clearSelection();
  }
  var element = aObj.selectedItem;
  if (!element) {
    return;
  }
  gMetrics.report("FeedsSidebar-FeedClick", null);

  if (aEvent && (aEvent.button == 0 || aEvent.button == 1)) {
    // Engage for a left/middle mouse click
    var feedUrl = "flock://favorites/"
                + encodeURIComponent(element.getAttribute("id"));
    currentWindow.FlockTabs.openURL(feedUrl, aEvent);
  }
}

function isAncestor(aItem1, aItem2) {
  var parents = aItem2.getParents();
  for (var i in parents) {
    if ((parents[i].id() == aItem1.id()) || isAncestor(aItem1, parents[i])) {
      return true;
    }
  }
  return false;
}

function toggleAutoMarkAsReadPref(aElement) {
  if (aElement) {
    gPrefs.setBoolPref(PREF_AUTO_MARK_AS_READ,
                       (aElement.getAttribute("checked") == "true"));
  }
}

function initAutoMarkAsReadCheckmark() {
  var menuitem = document.getElementById("autoMarkAsReadMenuItem");
  if (menuitem && gPrefs.getPrefType(PREF_AUTO_MARK_AS_READ)) {
    menuitem.setAttribute("checked",
                          gPrefs.getBoolPref(PREF_AUTO_MARK_AS_READ));
  }
}
