// 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 Cr = Components.results;
const Cu = Components.utils;

Cu.import("resource:///modules/FlockStringBundleHelpers.jsm");
Cu.import("resource:///modules/FlockXMLUtils.jsm");
Cu.import("resource:///modules/FlockDateFormatter.jsm");

const MIN_REFRESH_INTERVAL = 5000;

const RDFS = Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService);
function Namespace(ns) { return function (arg) { return RDFS.GetResource(ns+arg); } }
const FLRDF  = Namespace("http://flock.com/rdf#");
const NCRDF  = Namespace("http://home.netscape.com/NC-rdf#");
const kXULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

var gMetrics = Cc["@flock.com/metrics-service;1"].getService(Ci.flockIMetricsService);

function openURL(node, event) {
  if (event.button == 2) {
    return;
  }

  var url = node.childNodes[1].childNodes[1].value;
  this.gMetrics.report("Favorites-FavoriteClick", "MyWorld");

  // Open in new tab
  openURLMyWorld(url, event, false);
}

function openURLMyWorld(url, event, forceWindow) {
  if (event.button == 2) {
    return;
  }

  var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
           .getService(Ci.nsIWindowMediator);
  var win = wm.getMostRecentWindow('navigator:browser');
  if (win) {
    if (forceWindow) {
      var options = "centerscreen,resizable=yes";
#ifdef XP_WIN
      options += ",alwaysRaised";
#endif
      win.open(url, "miniView", options);
    } else {
      // opens url in new tab and switches to it immediately
      // win.openUILinkIn(url,"tab");
      win.FlockTabs.openURL(url, event, "webpage");
    }
  }
}

function openPeopleSidebar(event) {
  if (event.button == 2) {
    return; 
  }

  var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
           .getService(Ci.nsIWindowMediator);
  var win = wm.getMostRecentWindow("navigator:browser");
  if (win) {
    // Only open, don't close if already open
    win.toggleSidebarWithMetric("flockPeopleSidebarBroadcaster",
                                "PeopleSidebar-Open",
                                null,
                                "MyWorldPeopleButton",
                                true);
  }
}

function openWebClipboard(event) {
  if (event.button == 2) {
    return;
  }

  var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
           .getService(Ci.nsIWindowMediator);
  var win = wm.getMostRecentWindow('navigator:browser');
  if (win) {
    // Only open, don't close if already open
    win.toggleSidebarWithMetric("flock_notesSidebarBroadcaster",
                                "WebClipboard-Open",
                                null,
                                "MyWorldWebClipboardButton",
                                true);
  }
}

function openAASSidebar(node, event) {
  if (event.button == 2) {
    return;
  }
  if (node == null) {
    // Just open the sidebar.
    var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
             .getService(Ci.nsIWindowMediator);
    var win = wm.getMostRecentWindow('navigator:browser');
    if (win) {
      // Only open, don't close if already open
      win.toggleSidebarWithMetric("flock_AccountsSidebarBroadcaster",
                                  "AccountSidebar-Open",
                                  null,
                                  "MyWorldAccountsButton",
                                  true);
    }
    
    return;
  }

  var homeURL = node.getAttribute("homeURL");
  openURLMyWorld(homeURL, event, false);
}

function openFavoritesManager(event) {
  if (event.button == 2) {
    return;
  }

  var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
           .getService(Ci.nsIWindowMediator);
  var win = wm.getMostRecentWindow('navigator:browser');
  if (win) {
    // Only open, don't close if already open
    win.toggleSidebarWithMetric("viewBookmarksSidebar",
                                "FavoritesSidebar-Open",
                                null,
                                "MyWorldFavesButton",
                                true);
  }
}

function openNewsSidebar(node, event, aMetricsValue) {
  if (event.button == 2) {
    return;
  }

  //want full box to be hot but we need handle headlines being clicked
  if (event.target.className == "headlinesItem") {
    return;
  }

  var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
          .getService(Ci.nsIWindowMediator);
  var win = wm.getMostRecentWindow('navigator:browser');
  if (win) {
    win.FlockFeeds.openSidebar(aMetricsValue);
    if (node != null) {
      var url = encodeURIComponent(node.getAttribute("url"));
      openURLMyWorld("flock://favorites/urn:flock:feed:" + url, event, false);
    }
  }
}

function openImage(node, event) {
  if (event.button == 2) {
    return;
  }

  var mediaType = "image";
  if (node.getAttribute("isVideo") == "true") {
    mediaType = "video";
  }
  this.gMetrics.report("MyWorld-Media-ItemClick", mediaType);

  var imageURL = node.getAttribute("imageURL");
  var dataNode = node.parentNode;

  // for Truveo videos, always open in new window
  // c.f. http://bugzilla.flock.com/show_bug.cgi?id=7045
  if (dataNode.getAttribute("svc") == "searchvideo") {
    openURLMyWorld(imageURL, event, true);

    // Don't pop the mediabar
  } else {
    openURLMyWorld(imageURL, event, false);

    // Open the media bar
    openMediaBar(dataNode, event, imageURL);
  }
}

function openMediaBar(node, event, imageURL, attempts) {
  if (!attempts) {
    attempts = 0;
  }

  if (event.button == 2) {
    return;
  }

  var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
          .getService(Ci.nsIWindowMediator);
  var win = wm.getMostRecentWindow("navigator:browser");

  // If we are opening an image URL and we are supposed to open it in a new
  // window then we want get the window that was opened for that image
  // (getMostRecentWindow() might not be it).  We will search for the right
  // one to be sure.
  if (imageURL && (win.FlockTabs.getWebpageOpenLocation() == 2)) {
    var winEnum = wm.getEnumerator("navigator:browser");
    var winURI = null;
    while(winEnum.hasMoreElements()) {
      win = winEnum.getNext();
      if (win.getBrowser() && win.getBrowser().currentURI) {
        if (win.getBrowser().currentURI.spec == imageURL) {
          // We found the desired window.  Drop out of the loop.
          break;
        }
      }
      win = null;
    }
    if (!win) {
      // Only try again if less than 3 seconds have elapsed.
      //  (15 attempts * 200ms)
      if (attempts < 15) {
        // Try again in another 200ms, maybe then the window will be open.
        setTimeout(function openMediaBar_callback() {
                     openMediaBar(node, event, imageURL, ++attempts);
                   }, 200);
      } else {
        // Either the windows didn't load, it was closed or it redirected
        // to a different url.  Regardless we will just use the most recent
        // window.  Which will probably be right.
        win = wm.getMostRecentWindow
      }
    }
  }

  if (node) {
    var service = node.getAttribute("svc");
    var query = node.getAttribute("query");
    var name = node.getAttribute("name");
  }
 
  if (win) {
    this.gMetrics.report("MediaBar-Open", "MyWorld");
    win.FlockTopbar.selectById("flock_MediabarTopbarBroadcaster", true);

    if (service != "" && node) {
      win.mediabar.loadQuery(service, query, name);
    }
  }
  event.stopPropagation();
}

function fillTwitterStatusEntry(aTweetId, aStatusText, aToggleSidebarMetric) {
  var win = Cc["@mozilla.org/appshell/window-mediator;1"]
            .getService(Ci.nsIWindowMediator)
            .getMostRecentWindow("navigator:browser");
  var psbBroadcaster
    = win.document.getElementById("flockPeopleSidebarBroadcaster");
  psbBroadcaster.setAttribute("flockAction", "replyId:" + aTweetId);
  if (psbBroadcaster.getAttribute("checked")) {
    // Sidebar is open
    var os = Cc["@mozilla.org/observer-service;1"]
             .getService(Ci.nsIObserverService);
    os.notifyObservers(null,
                       "flock-people-trigger-status-change",
                       aStatusText);
  } else {
    // Sidebar is closed
    psbBroadcaster.setAttribute("prePopStatusText", aStatusText);
    win.toggleSidebarWithMetric("flockPeopleSidebarBroadcaster",
                                "PeopleSidebar-Open",
                                null,
                                aToggleSidebarMetric,
                                true);
  }
}

function setOpacity(node, opacityNum) {
  node.style.opacity = opacityNum;
}

function insertChildAt(i, aChild, aParent) {
  if (i >= aParent.childNodes.length) {
    aParent.appendChild(aChild);
  } else {
    var elementAti = aParent.childNodes[i];
    aParent.insertBefore(aChild, elementAti);
  }
}

function removeChildren(aXulElement) {
  var child;
  while ((child = aXulElement.lastChild) != null) {
    aXulElement.removeChild(child);
  }
}

// Delete elements from the bottom if it exceeds the MaxCount
function cutToMax(aFavBox, aMaxCount) {
  while (aFavBox.childNodes.length > aMaxCount) {
    aFavBox.removeChild(aFavBox.lastChild);
  }
}

function setNoItemMessage(aFavBox, aNoId) {
  var hasItems = aFavBox.firstChild != null;
  document.getElementById(aNoId).setAttribute("hidden", hasItems);
}

function insertElement(aFavBox, aXulElement) {
  // Insert (sorted) in the container
  var children = aFavBox.childNodes;
  for (let i = 0; i < children.length; i++) {
    if (aXulElement.latestDate > children[i].latestDate) {
      aFavBox.insertBefore(aXulElement, children[i]);
      return;
    }
  }
  aFavBox.appendChild(aXulElement);
}
