// 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 mediabar = {
  _favsCoop : Components.classes['@flock.com/singleton;1']
                           .getService(Components.interfaces.flockISingleton)
                           .getSingleton("chrome://flock/content/common/load-faves-coop.js")
                           .wrappedJSObject,
  initialMedia: null,
  load: function(aAccount) {
    var acctCoop = mediabar._favsCoop.get(aAccount.urn);
    if (!acctCoop) {
      // Invalid account
      return;
    }
    var svc = aAccount.getService();
    if (!(svc instanceof Components.interfaces.flockIMediaWebService)) {
      // Invalid service
      return;
    }

    if (FlockTopbar.JSCtx().gPhotoDrawer) {
      // The mediabar is already open
      FlockTopbar.JSCtx().gPhotoDrawer.loadPhotoPerson(aAccount.urn, svc.shortName);
    }
    else {
      // The mediabar is closed; need to open it
      this.initialMedia = {
        person: {
          urn: aAccount.urn,
          svc: svc.shortName
        }
      }
      mediabar.ensureOpen();
    }
  },
  loadQuery: function(aService, aQuery, aName) {
    if (FlockTopbar.JSCtx().gPhotoDrawer) {
      FlockTopbar.JSCtx().gPhotoDrawer.mFilter = '';
      FlockTopbar.JSCtx().gPhotoDrawer.loadQuery( aService, aQuery, aName );
      FlockTopbar.JSCtx().gPhotoDrawer.emptySearchbox();
    }
    else {
      this.initialMedia = {
        query: {
          service: aService,
          query: aQuery,
          name: aName
        }
      }
      mediabar.ensureOpen();
    }
  },
  loadFromId: function(aId) {
    var id = unescape(aId);
    if (FlockTopbar.JSCtx().gPhotoDrawer) {
      FlockTopbar.JSCtx().gPhotoDrawer.loadFromId(id);
    }
    else {
      var item = mediabar._favsCoop.get(id);
      this.initialMedia = {
        query: {
          service: item.service,
          query: item.query,
          name: item.name
        }
      }
      mediabar.ensureOpen();
    }
  },
  searchService: function mediabar_searchService(aSvcShortname) {
    if (FlockTopbar.JSCtx().gPhotoDrawer) {
      FlockTopbar.JSCtx().gPhotoDrawer.searchService(aSvcShortname);
    }
  },
  showActionMessage: function(aMessage) {
    mediabar.ensureOpen();
    if (FlockTopbar.JSCtx().gPhotoDrawer) {
      FlockTopbar.JSCtx().gPhotoDrawer.showActionMessage(aMessage);
    } else {
      // The mediabar is not initialized yet:
      // set a variable that will be picked up at initialization
      FlockTopbar.JSCtx().gInitialActionMessage = aMessage;
    }
  },
  hideActionMessage: function() {
    if (FlockTopbar.JSCtx().gPhotoDrawer) {
      FlockTopbar.JSCtx().gPhotoDrawer.hideActionMessage();
    }
  },
  lock: function()
  {
    mediabar.ensureOpen();
    var retval = true;
    if (FlockTopbar.JSCtx().gPhotoDrawer) {
      retval = FlockTopbar.JSCtx().gPhotoDrawer.lock();
    }
    return retval;
  },
  unlock: function()
  {
    if (FlockTopbar.JSCtx().gPhotoDrawer)
    {
      FlockTopbar.JSCtx().gPhotoDrawer.unlock();
    }
  },
  ensureOpen: function() {
    FlockTopbar.selectById('flock_MediabarTopbarBroadcaster', true)
  },
  needDiscovery: function(aBrowser, aService, aQuery, aUrl)
  {
    var showDiscovery = true;
   // if the topbar is open with mediabar
    if (document.getElementById("topbarBrowser").getAttribute("src") &&
        FlockTopbar.JSCtx().gPhotoDrawer)
    {
      if ((FlockTopbar.JSCtx().gPhotoDrawer.mApi == aService) &&
          (FlockTopbar.JSCtx().gPhotoDrawer.mQuery.stringVal == aQuery))
      {
        showDiscovery = false;
        var nBox = aBrowser.getNotificationBox();
        nBox.saveToHashtable(aUrl, nBox.FLOCK_PRIORITY_LOW);
      }
    }
    return showDiscovery;
  },
  openViaDiscovery: function mediabar_openViaDiscovery(aMenuitem) {
    var service = aMenuitem.getAttribute("service");
    var query = aMenuitem.getAttribute("query");
    var label = aMenuitem.getAttribute("label");

    aMenuitem.parentNode.hidePopup();
    mediabar._openViaItems(service, query, label);
  },
  _openViaItems: function mediabar__openViaItems(aService, aQuery, aLabel) {
    if (mediabar.lock()) {
      gMetrics.report("MediaBar-Open", "Discovery");
      mediabar.loadQuery(aService, aQuery, aLabel);
      mediabar.unlock();

      // Pop message bar for media detection discovery
      var favItem = faves_coop.MediaQuery.find({ query: aQuery,
                                               isPollable: true });
      if (favItem.length == 0) {
        var msg = flockGetString("favorites/favorites",
                                "flock.favs.media.discovery");
        var nBox = notificationOverlay.getNotificationBox();
        var mediaIcon = "chrome://flock/skin/favorites/media-icon.png";
        nBox.appendUniqueNotification(msg,
                                      "media-discovery-info",
                                      mediaIcon,
                                      nBox.FLOCK_PRIORITY_LOW,
                                      null,
                                      null);
      }
    }
  }
};

var MediaNotifications = {
};

MediaNotifications.mediaObserver = {
  observe: function MNMediaObserver_observe(aSubject, aTopic, aData) {
    if (aTopic == "media" && aData == "media:update") {
      MediaNotifications.updateState();
    }
  }
};

MediaNotifications.init =
function MN_init() {
  this._obs = CC["@mozilla.org/observer-service;1"]
              .getService(CI.nsIObserverService);
  gBrowser.addEventListener("TabSelect",
                            MediaNotifications.updateState,
                            false);
  this._obs.addObserver(MediaNotifications.mediaObserver, "media", false);
};

MediaNotifications.uninit =
function MN_uninit() {
  gBrowser.removeEventListener("TabSelect",
                               MediaNotifications.updateState,
                               false);
  this._obs.removeObserver(MediaNotifications.mediaObserver, "media", false);
};

MediaNotifications.addMediaRSS =
function MN_addMediaRSS(aFlockFeed) {
  var url = aFlockFeed.getURL();
  var title = aFlockFeed.getRealTitle();

  var docshell = top.document.getElementById("content").webNavigation;
  if (!docshell.document._flock_decorations) {
    docshell.document._flock_decorations = {};
  }

  var mediaArr = docshell.document._flock_decorations.mediaArr
               ? docshell.document._flock_decorations.mediaArr
               : [];
  var newMedia = {
    name: title,
    query: "special:" + encodeURIComponent(url.spec),
    label: title,
    favicon: "",
    service: "mediarss"
  }
  for each (var media in mediaArr) {
    if (media.query == newMedia.query) {
      return;
    }
  }

  mediaArr.push(newMedia);
  docshell.document._flock_decorations.mediaArr = mediaArr;
}

MediaNotifications.updateState =
function MN_updateState() {
  // Check for discovered Media
  var mediaBtn = document.getElementById("favoritesPhotoButton");
  // Are we on the chrome?
  if (!mediaBtn) {
    return;
  }

  var docshell = top.document.getElementById("content").webNavigation;
  var decorations = docshell.document._flock_decorations;
  if (decorations && decorations.mediaArr && decorations.mediaArr.length) {
    // Media was discovered
    mediaBtn.removeAttribute("disabled");
    mediaBtn.setAttribute("tooltiptext",
                          flockGetString("favorites/favorites",
                                         "flock.favs.overlay.mediaBtn.new"));
    MediaNotifications._showMessage(decorations);
  } else {
    // No media was discovered
    mediaBtn.setAttribute("disabled", "true");
    mediaBtn.setAttribute("tooltiptext",
                          flockGetString("favorites/favorites",
                                         "flock.favs.overlay.mediaBtn.desc"));
  }
};

MediaNotifications._showMessage =
function MN__showMessage(aDecorations) {
  var nBox = gBrowser.getNotificationBox();
  if (aDecorations && aDecorations.mediaArr) {
    for (var i = 0; i < aDecorations.mediaArr.length; i++) {
      var mStream = aDecorations.mediaArr[i];
      var url = mStream.service + "+" + mStream.query;
      if (mStream &&
          mediabar.needDiscovery(gBrowser, mStream.service,
                                 mStream.query, url))
      {
        // Show message bar
        var brand = brandGetString("brand", "brandShortName");
        var message = flockGetString("favorites/favorites",
                                     "flock.favs.overlay.discovery-media",
                                     [brand, brand]);
        var links = [{
          label: flockGetString("favorites/favorites",
                                "flock.favs.overlay.show-me-how"),
          callback: function MN_showMessage_callback() {
            var favsBtn = document.getElementById("favoritesPhotoButton");
            if (favsBtn) {
              var method = function sM_cb_method() {
                var elt = document.getElementById("favoritesPhotoButton");
                notificationOverlay.flash(0, elt);
              }
              setTimeout(method, 500);
              favsBtn.click();
            }
          }
        }];
        nBox.appendUniqueNotification(message,
                                      "discovery-media",
                                      null,
                                      nBox.FLOCK_PRIORITY_LOW,
                                      null,
                                      links,
                                      url);
        break;
      }
    }
  }
};

MediaNotifications.updatePopup =
function MN_updatePopup() {
  var mediaBtn = document.getElementById("favoritesPhotoButton");
  var mediaPopup = mediaBtn.firstChild;
  var rtval_firstquery = null;
  // Clear out the popup menu
  while (mediaPopup.firstChild) {
    mediaPopup.removeChild(mediaPopup.firstChild);
  }
  // Repopulate the menu based on document decorations
  var docshell = top.document.getElementById("content").webNavigation;
  var decorations = docshell.document._flock_decorations;
  if (decorations && decorations.mediaArr) {
    // Only keep media RSS if there is no other media
    var keepMediaRSS = true;
    for (var i = 0; i < decorations.mediaArr.length && keepMediaRSS; i++) {
      if (decorations.mediaArr[i].service != "mediarss") {
        keepMediaRSS = false;
      }
    }
    for (var i = 0; i < decorations.mediaArr.length; i++) {
      var mStream = decorations.mediaArr[i];
      if (!keepMediaRSS && mStream.service == "mediarss") {
        continue;
      }
      if (mStream) {
        var menuitem = document.createElement("menuitem");
        menuitem.setAttribute("service", mStream.service);
        var parity = (i % 2 == 0) ? "even" : "odd";
        menuitem.setAttribute("parity", parity);
        menuitem.setAttribute("query", mStream.query);
        menuitem.setAttribute("label", mStream.label);
        menuitem.setAttribute("oncommand", "mediabar.openViaDiscovery(this);");
        var urn = "urn:media:favorites:"+mStream.service+":"+mStream.query;
        if (faves_coop.get(urn)) {
          menuitem.setAttribute("class", "menuitem-iconic");
          menuitem.setAttribute("image",
                                "chrome://flock/skin/common/star16.png");
        }
        mediaPopup.appendChild(menuitem);
        if (!rtval_firstquery) {
          rtval_firstquery = mStream.query;
        }
      }
    }

    // If there is only 1 discovered media item, load into the mediabar
    // without showing the popup.
    if (mediaPopup.childNodes.length == 1) {
      mediabar.openViaDiscovery(mediaPopup.firstChild);
    } else {
      mediaBtn.firstChild
              .showPopup(mediaBtn, -1, -1, "popup", "bottomleft", "topleft");
    }
  }
  // Return value will be NULL if no media was found, else it will be the
  // query string for the first discovered media stream
  return rtval_firstquery;
};

var FlockMediaOverlay = {};

FlockMediaOverlay.init =
function FlockMediaOverlay_init() {
  MediaNotifications.init();

  // Only show the "upload image" context menu on images
  var browserContext = document.getElementById("contentAreaContextMenu");
  browserContext.addEventListener("popupshowing",
                                  FlockMediaOverlay.initContextItems,
                                  false);
};

FlockMediaOverlay.uninit =
function FlockMedia_uninit() {
  MediaNotifications.uninit();
};

FlockMediaOverlay.initContextItems =
function FlockMedia_initContextItems() {
  gContextMenu.showItem("context-uploadimage", gContextMenu.onImage);
};

window.addEventListener("load", FlockMediaOverlay.init, false);
window.addEventListener("unload", FlockMediaOverlay.uninit, false);
