const CI = Components.interfaces;
const CL = Components.classes;

const Ci = CI;  // used in urlbarBindings.xml
const Cl = CL;  // used in urlbarBindings.xml

const PREFSSERVICE = CL["@mozilla.org/preferences-service;1"].getService(CI.nsIPrefService);
const YNPREFBRANCH = PREFSSERVICE.getBranch("extensions.yoono.");

const HOME = "http://static.yoono.com/redirect/YDbrowserdefault.html";

Components.utils.import("resource://yoono/yoonoYEXTIF.js");
Components.utils.import("resource://yoono/yoonoService.js");
Components.utils.import("resource://yoono/yoonoLog.js");
Components.utils.import("resource://yoono/yoonoDialogs.js");
Components.utils.import("resource://yoono/yoonoUtils.js");
Components.utils.import("resource://yoono/yoonoPrefs.js");
Components.utils.import("resource://yoono/yoonoSidebarService.js");
Components.utils.import("resource://yoono/yoonoStorage.js");
Components.utils.import("resource://yoono/yoonoKeyValueDB.js");


var windowId = "single-window";

function onWindowLoad() {

  // Take the focus, else the window keep behind current opened application ...
  window.focus();
  
  // Retrieve application version
  var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
  var previousRelease = '';
  try {
    previousRelease = YNPREFBRANCH.getCharPref("release");
  } catch(e) {
    // pref not found : first install
    YNPREFBRANCH.setIntPref("install_date", Math.round(new Date().getTime()/1000));
  }
  var currentRelease = appInfo.version;

  // If user just updated
  if(currentRelease != previousRelease) {
    YNPREFBRANCH.setBoolPref("first-release-run", true);
    YNPREFBRANCH.setCharPref("updated.from", previousRelease); // for stats, reset after sent
    YOONO_KEYVALUEDB.setKeyValue('sidebarUpdatedFrom', previousRelease);
    YOONO_KEYVALUEDB.setKeyValue("sidebarFirstReleaseRun", true); // this will be reset by sidebar when it closes
  } else {
    YNPREFBRANCH.setBoolPref("first-release-run", false);
  }
  YNPREFBRANCH.setCharPref("release", currentRelease);
  YOONO_KEYVALUEDB.setKeyValue('sidebarRelease', currentRelease);
  
  // Display release number in title tooltip
  document.getElementById("flying-logo").tooltipText="Yoono Desktop "+currentRelease;

  // Hide close menu item under Linux 
  // (We don't have tray icon nor dock, so "close" doesn't exists)
  if (navigator.platform.indexOf("Linux")!=-1)
    document.getElementById("menu-close").hidden=true;
  
  var yoono = {};
  yoono.log=YOONO_LOG;
  yoono.utils=YOONO_UTILS;
  yoono.server = {
    launch : function (a,b) {
      // Called by YEXTIF when user is registered
      // with arguments ("connect", "no-sync")
      dump("Try to call launch with args : "+a+','+b+'\n');
    }
  }
  yoono.prefs=YOONO_PREFS;
  yoono.yextif=YOONO_YEXTIF;
  yoono.sidebar=YOONO_SIDEBAR;
  
  yoono.main=YOONO_CMPT;
  yoono.bkm = {start:function(){}};
  yoono.dialogs=YOONO_DIALOGS;
  yoono.storage=YOONO_STORAGE;
  
  YOONO_LOG.init(yoono);
  YOONO_PREFS.init(yoono);
  YOONO_DIALOGS.init(yoono);
  YOONO_CMPT.init(yoono);
  YOONO_SIDEBAR.init(YOONO_CMPT);
  YOONO_YEXTIF.init(yoono);
  YOONO_STORAGE.init(yoono);
  
  // Change YEXTIF specifics methods dynamically
  YOONO_YEXTIF.methods.isStandalone = function () {return 1;};
  YOONO_YEXTIF.methods.getClientType = function () {return "dsk";};
  YOONO_YEXTIF.methods.getVersion = function () {
    var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
    return appInfo.version;
  };
  YOONO_YEXTIF.methods.openSidebar = function () {
    trayIcon.restore();
  };
  YOONO_YEXTIF.methods.openWindow = function () {
    trayIcon.restore();
  };
  YOONO_YEXTIF.methods.isStandaloneOpen = function () {
    return trayIcon.isOpen();
  };
  YOONO_YEXTIF.methods.getStandaloneTab = function () {
    return ynWindowHandlers.getTab();
  };  
  YOONO_YEXTIF.methods.isOnTheRight = function () {
    return true;
  }
  YOONO_YEXTIF.methods.showSocialzineTab = function () {
    ynWindowHandlers.toggle('socialzine');
  }
  window.setTimeout(function () {
    var iframe = document.getElementById('website-iframe');
    if(iframe) {
      iframe.setAttribute('src', HOME);
    }
  }, 300);
  
  var iframe = document.getElementById("main-iframe");
  var iframeWin = iframe.contentWindow;
  if (iframeWin.wrappedJSObject)
    iframeWin = iframeWin.wrappedJSObject;
  
  // Automatically install friends and only friends yoodget!
  // set it dynamically because extension's pref take the lead over application's one
  YOONO_PREFS.set("autoinstall","friends");
  
  //////////////////////
  // /!\ Dirty hacks /!\
    // Avoid loading of highlighter
    iframeWin.deferredServices = [];//["adManager"];
    iframeWin.deferDelay = 5000;
    
  //////////////////////
  
  function waitFriendsLoading() {
    if (!YOONO_CMPT.getYServices().yoodgetInstances || !YOONO_CMPT.getYServices().yoodgetInstances.getRegisteredYoodgetWrapper("{friends@yoono.com}",-1)) {
      YOONO_LOG.debug("wait loading of Friends widget ...");
      return window.setTimeout(waitFriendsLoading,500);
    }
    var friends = YOONO_CMPT.getYServices().yoodgetInstances.getRegisteredYoodgetWrapper("{friends@yoono.com}",-1);
    //////////////////////
    // /!\ Dirty hack /!\
    // Disable overlays (which automatically open webpanel but don't close it :/)
    var parent = Components.utils.getGlobalForObject(friends.yoodget);
    parent.mediaPreview = {
      showMediaPreview : function () {},
      hideMediaPreview : function () {}
    };
    //////////////////////
    
//    ynWindowHandlers.restore();
    
    window.setTimeout(function () {
      displayReleasePage();
    }, 1000);
  }
  
  function waitServicesLoading() {
    // TODO : add callback to Yservices.init
    if (!YOONO_YEXTIF || !YOONO_YEXTIF.methods || !YOONO_CMPT || !YOONO_CMPT.getYServices()
      || !YOONO_CMPT.getYServices().core) {// || !YOONO_CMPT.getYServices().browser) {
      YOONO_LOG.debug("wait loading of YServices ...");
      return window.setTimeout(waitServicesLoading,100);
    }
    for(var method in YOONO_YEXTIF.methods) {
      iframeWin.YEXTIF.methods[method] = YOONO_YEXTIF.methods[method];
    }
    iframeWin.document.body.className += " runner";
       
    YOONO_CMPT.getYServices().core.initSubDocument(iframeWin,"yoonoSidebarInit",[windowId, "no-stage"]);
    window.sizeToContent();
    
    waitFriendsLoading();
    
    YOONO_CMPT.getYServices().core.require("skin",function () {
      var textSizes = YOONO_CMPT.getYServices().skin.getTextSizeList();
      var currentSize = YOONO_CMPT.getYServices().skin.getTextSize();
      var container = document.getElementById("text-sizes");
      for (var j in textSizes) {
        var ts = textSizes[j];
        var label = document.createElement("label");
        label.internal_css = ts.css;
        label.setAttribute("value",ts.name);
        if (currentSize == ts.css)
          label.setAttribute("selected","true");
        container.appendChild(label);
      }
    });
  }
  waitServicesLoading();
}


function onWindowUnload() {
  // Call uninit method manually,
  // because it will be called too late if we let iframe's unload call it.
  // (setkeyvalue is failing, when it's called too late)
  var columns = document.getElementById("columns-iframe");
  var columnsWin = columns.contentWindow;
  if (columnsWin && columnsWin.uninit)
    columnsWin.uninit();
  
  YOONO_YEXTIF.goodbye();
  
  var iframe = document.getElementById("main-iframe");
  var iframeWin = iframe.contentWindow;
  if (iframeWin.wrappedJSObject)
    iframeWin = iframeWin.wrappedJSObject;
  iframeWin.yoonoSidebarQuit();

  YOONO_YEXTIF.notifyTabActivity(windowId, null, null, 'close');
  
  YOONO_CMPT.getYServices().observer.notifyObservers("app.quit",null);
  
  YOONO_PREFS.set("firstrun", false);
  
  var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1'].getService(Components.interfaces.nsIAppStartup);
  appStartup.quit(Components.interfaces.nsIAppStartup.eAttemptQuit);
}


window.addEventListener("load",function(event) {
  if (event.originalTarget!=document) return;
  window.removeEventListener("load",arguments.callee,true);
  onWindowLoad();  
},true);

window.addEventListener("unload",function (event) {
  if (event.originalTarget!=document) return;
  onWindowUnload();
  window.removeEventListener("unload",arguments.callee,true);
},true);
  

