// vim: foldmethod=marker

// BEGIN clav.mozdev.org MPL
// 
// Version: MPL 1.1/GPL 2.0/LGPL 2.1
// 
// The contents of this file are subject to the Mozilla Public License Version
// 1.1 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
// http://www.mozilla.org/MPL/
// 
// 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.
// 
// The Original Code is Stephen Clavering code.
// 
// The Initial Developer of the Original Code is
// Stephen Clavering <mozilla@clav.me.uk>
// Portions created by the Initial Developer are Copyright (C) 2005
// the Initial Developer. All Rights Reserved.
// 
// Contributor(s):
// Flock Inc. <contact@flock.com> 
//
// Alternatively, the contents of this file may be used under the terms of
// either of the GNU General Public License Version 2 or later (the "GPL"),
// or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
// in which case the provisions of the GPL or the LGPL are applicable instead
// of those above. If you wish to allow use of your version of this file only
// under the terms of either the GPL or the LGPL, and not to allow others to
// use your version of this file under the terms of the MPL, indicate your
// decision by deleting the provisions above and replace them with the notice
// and other provisions required by the GPL or the LGPL. If you do not delete
// the provisions above, a recipient may use your version of this file under
// the terms of any one of the MPL, the GPL or the LGPL.
// 
// END clav.mozdev.org MPL


const kStopReloadNormalClass = "toolbarbutton-1 stopreload-reload";
const kStopReloadStopClass = "toolbarbutton-1 stopreload-stop";
const FLNS = 'http://flock.com/rdf#';
const MEDIA_FAVES_ROOT = 'urn:media:favorites';
var rdfService = null;
var favsDS = null;
var apiMgr = null;
// toolbox.customizeDone is now initialized.  Proceed with ultra sketchy
// customization notification override
function loadPhase2() {
  stopreloadinit_phase2();
}

function stopreloadinit_phase2() {
  var toolbox = document.getElementById("navigator-toolbox");
  var preStopreloadCustomizeDone = toolbox.customizeDone;
  toolbox.customizeDone = function(anythingChanged) {
    dump("toolbarOverlay.js: Calling toolbox.customizeDone!\n");
    preStopreloadCustomizeDone(anythingChanged);
    if(anythingChanged) stopreload.init();
    searchbarController.uninit();
    searchbarController.init();
  };
}

var stopreload = {
  button: null,
  listenerAdded: false,

  init: function() {
    this.button = document.getElementById('stopreload-button');
    if(this.button) {
      if(this.listenerAdded) return;
      gBrowser.addProgressListener(this, Components.interfaces.nsIWebProgress.NOTIFY_STATE_ALL);
//      gBrowser.addProgressListener(this, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
      this.listenerAdded = true;
      // default label is 'Stop/Reload', for when it's on the palette
      this.button.setAttribute('label', this.button.getAttribute('reloadlabel'));
      this.button.setAttribute('tooltiptext', this.button.getAttribute('reloadtooltip'));
      this.button.stopOnCommand = false;
    } 
    else {
      if(!this.listenerAdded) return;
      gBrowser.removeProgressListener(this);
      this.listenerAdded = false;
    }
  },

  oncommand: function(evt, button) {
    if (button.stopOnCommand) {
      BrowserStop();
    }
    else {
      if (evt.shiftKey) {
        BrowserReloadSkipCache();
      } else {
        BrowserReload();
      }
    }
  },

  QueryInterface: function(aIID) {
    if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
        aIID.equals(Components.interfaces.nsISupports)) {
      return this;
    }
    throw Components.results.NS_NOINTERFACE;
  },

  onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
    const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
    var btn = this.button;
    if(aStateFlags & nsIWebProgressListener.STATE_START) {
      btn.className = kStopReloadStopClass;
      btn.stopOnCommand = true;
      btn.setAttribute('label', btn.getAttribute('stoplabel'));
      btn.setAttribute('tooltiptext',btn.getAttribute('stoptooltip'));
    } 
    else if(aStateFlags & nsIWebProgressListener.STATE_STOP) {
      btn.className = kStopReloadNormalClass;
      btn.stopOnCommand = false;
      btn.setAttribute('label', btn.getAttribute('reloadlabel'));
      btn.setAttribute('tooltiptext', btn.getAttribute('reloadtooltip'));
    }
  },

  onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {},
  onLocationChange: function onLocationChange(aWebProgress, aRequest, aLocation)
  {
    var mailBtn = document.getElementById("mail-button");
    if (mailBtn && aLocation) {
      if (aLocation.schemeIs("http") ||
          aLocation.schemeIs("https") ||
          aLocation.schemeIs("ftp"))
      {
        mailBtn.removeAttribute("disabled");
      } else {
        mailBtn.setAttribute("disabled", "true");
      }
    }
  },
  onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) {},
  onSecurityChange: function(aWebProgress, aRequest, aState) {},

  // tabbrowser.xml calls this for all registered progress listeners,
  // even though it is not part of the nsIWebProgressListener interface
  onLinkIconAvailable: function(href) {}
}

//first we must wait till load.  during this epoch, toolbox.customizeDone is
//initialized
top.addEventListener("load", function() {
  stopreload.init();
  rdfService = Components.classes['@mozilla.org/rdf/rdf-service;1'].getService(Components.interfaces.nsIRDFService);
  favsDS = rdfService.GetDataSource('rdf:flock-favorites');
  favsDS.QueryInterface (Components.interfaces.flockIRDFObservable);
  var unseenItemsPredicate = rdfService.GetResource(FLNS + 'hasUnseenItems');
  var mediaFavsFolder = faves_coop.get(MEDIA_FAVES_ROOT);
  favsDS.addArcObserver(Components.interfaces.flockIRDFObserver.TYPE_ASSERT | Components.interfaces.flockIRDFObserver.TYPE_CHANGE,
                        mediaFavsFolder.resource(),
                        unseenItemsPredicate,
                        null,
                        unseenItemsObs);
  apiMgr = Components.classes['@flock.com/photo-api-manager;1?'].getService(Components.interfaces.flockIPhotoAPIManager)
  updateMediaButton();
  window.setTimeout(loadPhase2, 0); //phase 2 see above
  injectAddTabButton();
}, false);

top.addEventListener("unload", function() {
  var unseenItemsPredicate = rdfService.GetResource(FLNS + 'hasUnseenItems');
  var mediaFavsFolder = faves_coop.get(MEDIA_FAVES_ROOT);
  favsDS.removeArcObserver(Components.interfaces.flockIRDFObserver.TYPE_ASSERT | Components.interfaces.flockIRDFObserver.TYPE_CHANGE,
                           mediaFavsFolder.resource(),
                           unseenItemsPredicate,
                           null,
                           unseenItemsObs);
}, false);
 
var unseenItemsObs = {
  rdfChanged: function (ds, type, source, predicate, target, oldtarget) {
    updateMediaButton();
  }
}
 
function updateMediaButton() {
  if (!document.getElementById("photos-button")) {
    return;
  }
  if (apiMgr.hasNewMedia) {
    document.getElementById("photos-button").setAttribute("hasNew", "true");
  }else{  
    document.getElementById("photos-button").removeAttribute("hasNew");
  }
}

function openMyWorld(aEvent) {
  if (aEvent.button == 2) { // right-click; do nothing
    return;
  }

  for (var i = 0; i < gBrowser.mTabs.length; i++) {
    if (gBrowser.mTabs[i].linkedBrowser.currentURI.spec == "about:myworld") {
      gBrowser.selectedTab = gBrowser.mTabs[i];
      return;
    }
  }

  // If we get here, we didn't find My World.. boo!
  var tabAdded = gBrowser.loadOneTab("about:myworld", null, null, null, null, false);
  gBrowser.selectedTab = tabAdded;
}

function openFeedback(aEvent) {
  if (aEvent.button == 2) { // right-click; do nothing
    return;
  }

  var tabAdded = gBrowser.loadOneTab("http://flock.com/feedback/", null, null, null, null, false);
  gBrowser.selectedTab = tabAdded;
}

/**
 * Inject the "Open a New Tab" button to the chrome.
 */
function injectAddTabButton() {
  // Create the button.
  var button = document.createElement("toolbarbutton");
  button.setAttribute("class", "tabbar-newtab-button");
  button.setAttribute("oncommand", "BrowserOpenTab();");

  var sb = CC["@mozilla.org/intl/stringbundle;1"]
           .getService(CI.nsIStringBundleService)
           .createBundle("chrome://flock/locale/toolbar/toolbarOverlay.properties");

  var tooltipText = sb.GetStringFromName("flock.browser.newTabButton.tooltip");
  button.setAttribute("tooltiptext", tooltipText);

  // Find the tabs element.
  var tabs = document.getAnonymousElementByAttribute(gBrowser,
                                                     "anonid",
                                                     "tabcontainer");

  // Find the tabs container within the tabs element.
  var tabsContainer = document.getAnonymousElementByAttribute(tabs,
                                                              "class",
                                                              "tabs-container");

  // We want to insert our button right after the scrollbox.
  var node = tabsContainer.firstChild;
  var insertLocation = null;
  while (node) {
    if (node.getAttribute("anonid") == "arrowscrollbox") {
      insertLocation = node.nextSibling;
      break;
    }
    node = node.nextSibling
  }

  if (insertLocation) {
    tabsContainer.insertBefore(button, insertLocation);
  }
}
