/*
 * OutWit Images
 *
 * Copyright (c) OutWit Technologies 2007-2017.
 * All right reserved
 *
 */


/**
 * @fileOverview Browsing management file for outwit images
 * @author pr
 */



/**
 * Browsing management for outwit images
 *
 * @static
 * @name outwitImages.browserManager
 */
outwitImages.browserControls = {

  /**
   *
   */
  load: function() {
		widgets.page.load(20000, 2500, 3500, true);

    this.browser = widgets.page.browser;

    this.browser.docShell.allowImages = true;
    this.browser.docShell.allowPlugins = false;
    this.browser.docShell.allowAuth = false;
    this.browser.docShell.allowJavascript = ow.app.kernel.prefs.getBool("oWImages.allowBrowserJavascript", true);

  //  this.browser.markupDocumentViewer.authorStyleDisabled = true;

    this.browserManager = widgets.page.browserManager;
    this.browserManager.niceness = 10;
    this.browserManager.doUpPage = false;

    this.browserPilot = widgets.page.browserPilot;

    this.browserPilot.checkCanRun = function() {
      return widgets.page.browserManager.allLinksExtracted && !widgets.page.browserManager.pageLoading;
    };

    this.extractorManager = widgets.page.extractorManager;

    this.browserManager.addEventListener("pageLoaded", this.onAllpageshow);
    this.browserManager.addEventListener("pageLoaded", this.onProgressStop);
    this.browserManager.addEventListener("locationChanged", this.onLocationChange);
  },

  unload: function() {
    this.browserManager.removeEventListener("pageLoaded", this.onProgressStop);
    this.browserManager.removeEventListener("pageLoaded", this.onAllpageshow);
    this.browserManager.removeEventListener("locationChanged", this.onLocationChange);
  },

  onProgressStop: function(event) {
                    dump("ONPROGRESSSTOP " + outwitImages.UIControls.mode + " " + outwitImages.UIControls.MODE_DISCOVER + "\n");
    if (outwitImages.UIControls.mode == outwitImages.UIControls.MODE_DISCOVER) {
      imageEngineService.currentURI = widgets.page.browser.currentURI;
      imageEngineService.get();
    }
  },

  onAllpageshow: function(event) {
		dump("ONALLPAGESHOW " + outwitImages.UIControls.mode + " " + outwitImages.UIControls.MODE_DISCOVER + " " + widgets.page.browsing + "\n");
		
    if (outwitImages.UIControls.mode != outwitImages.UIControls.MODE_DISCOVER && !widgets.page.browsing) {
      outwitImages.UIControls.newPage(widgets.page.currentURI.spec);
      if (optionsCtrl.autoBrowse && !widgets.page.browsing) {
        widgets.page.browseFromCurrent();
      }
    }
		if (outwitImages.browserControls.initialTitle == null) {
			outwitImages.browserControls.initialTitle = outwitImages.browserControls.browserManager.currentTitle;
		}

    widgets.page.updateCommands();
  },

  onLocationChange: function(event) {
    if (!(++outwitImages.browserControls.firstPageBoost)) {
      outwitImages.browserControls.browserPilot.minBrowseTempo = 2500;
    }
  },

  stopAll: function() {
    widgets.page.stopAll();
    outwitImages.extractControls.stop();
  },

  runAutoBrowse: function(anURI) {
//    outwitImages.UIControls.clearOnNew = false;
    if (anURI) {
      widgets.page.browse(anURI, null, true, -1);
    }
    else {
      widgets.page.browseFromCurrent();
    }
//   outwitImages.UIControls.clearOnNew = true;
  },

  stopBrowse: function() {
    widgets.page.stopBrowse();
  },

  runFromSearch: function(url, data, postData, truc, bidule) {
    outwitImages.browserControls.stopAll();

    outwitImages.UIControls.mode = 'discovering';
    imageEngineService.loadURI(url, data, postData, truc, bidule);
  },


  runFromUrl: function(search, data, postData, truc, bidule) {
    outwitImages.browserControls.stopAll();
    
    var url = search;
    var classOb = outwitKit.getObjectClass(url);
    
    function checkCatch( aPath ){
      var el = document.getElementById("mediacatch");
      if( el.childNodes.length == 0){
        el.loadFromSqliteFile(false, aPath);
        return;
      }


      var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
        .getService(Components.interfaces.nsIPromptService);
        var aButtonFlags = (prompts.BUTTON_POS_0) * (prompts.BUTTON_TITLE_IS_STRING) +
                           (prompts.BUTTON_POS_1) * (prompts.BUTTON_TITLE_IS_STRING) +
                           (prompts.BUTTON_POS_2) * (prompts.BUTTON_TITLE_IS_STRING) +
                           prompts.BUTTON_POS_1_DEFAULT;
        var returnValue = {value:false};
        var returnVal = prompts.confirmEx(window,
          coreKit.localeService.getString('catchOWCTitle', 'chrome://outwit-kernel/locale/widgets/catch/catch.properties'),
          coreKit.localeService.getString('catchOWCQuestion', 'chrome://outwit-kernel/locale/widgets/catch/catch.properties'),
          aButtonFlags,
          coreKit.localeService.getString('catchOWCButton2', 'chrome://outwit-kernel/locale/widgets/catch/catch.properties'),
          coreKit.localeService.getString('catchOWCButton1', 'chrome://outwit-kernel/locale/widgets/catch/catch.properties'),
          coreKit.localeService.getString('catchOWCButton3', 'chrome://outwit-kernel/locale/widgets/catch/catch.properties'),
          null,
          returnValue);
        switch( returnVal ){
          case 0://Ajouter
            el.loadFromSqliteFile(false, aPath);
          break;
          case 1://Annuler
          break;
          case 2://Remplacer
            while (el.childNodes.length)
              el.removeItem(el.lastChild);
            el.loadFromSqliteFile(false, aPath);
          break;
        }
      }


    if(classOb == "Filepath" && /\.owc$/.test(url)){ //oki load the file
      url = url.substr(7, url.length);
      checkCatch(url);
      return;
    }
    if(classOb == "URL" && /\.owc$/.test(url)){ //oki load the file
      if( url.substr(0,4) != 'http' ){
        url = 'http://' + url;
      }


      var fileName = coreKit.fileManager.getTempFile(null, 'test.owc');
      var URI = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(url, null, null);

      var file = Components.classes["@mozilla.org/file/local;1"]
               .createInstance(Components.interfaces.nsILocalFile);
      file.initWithPath(fileName.path); // download destination

      var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
          .createInstance(Components.interfaces.nsIWebBrowserPersist);

      persist.progressListener = {
        onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {
        },
        onStateChange: function(aWebProgress, aRequest, aStatus, aMessage) {
          if ((aStatus & Components.interfaces.nsIWebProgressListener.STATE_STOP) &&
            (aStatus & Components.interfaces.nsIWebProgressListener.STATE_IS_REQUEST)){
              checkCatch(fileName.path);
          }

        }
      };

      persist.saveURI(URI, null, null, null, "", file, null);

      return;
    }
    


    // Person
    // "word1 word2" OR "word2 word1"
    var compFlag = false;
    var isURLFlag = false;
    // We can search the search engine information with a nice component
    // http://www.xulplanet.com/references/xpcomref/comps/c_browsersearchservice1.html
    Components.utils.import("resource://gre/modules/Services.jsm");
    var currentEngine = Services.search.defaultEngine;
    var word = "";
    var treated = false;
    if (classOb.substr(0, 6) == 'Person') {
      var stuff = url.split(' ');
      if (stuff.length == 2) {
        word = '"' + url + '" OR "' + stuff[1] + " " + stuff[0] + '"';
      }
      else {
        word = '"' + url + '"';
      }
    }
    else if (classOb.substr(0, 3) == 'URL' || classOb.substr(0, 3) == 'Fil') {
      word = url;
      isURLFlag = true;
    }
    else
      word = url;

    if (!isURLFlag) {
      var submission = currentEngine.getSubmission(word, null);
      url = submission.uri.spec;

      outwitImages.UIControls.mode = 'discovering';
      imageEngineService.loadURI(url, data, postData, truc, bidule, search);
    }
    else {
      var URL = outwitKit.URLHistoryService.getBeanFromString(url, false, "http").URI.spec;
      outwitImages.UIControls.mode = 'url';
      outwitImages.browserControls.loadURI(URL);
    }
  },

  loadURI: function(url) {
		this.initialURI = ""+url;
		this.initialTitle = null;
    outwitImages.browserControls.stopAll();

    if (outwitImages.UIControls.mode == "url") {
      outwitImages.extractControls.start();

      outwitImages.browserControls.browserPilot.minBrowseTempo = 750;
      outwitImages.browserControls.firstPageBoost = -2;
    }

    if (outwitImages.UIControls.clearOnNew) {
      outwitImages.UIControls.container.clear();
    }

    document.getElementById("urlbar").value = url;

    if (outwitImages.UIControls.mode == "url" && optionsCtrl.autoBrowse) {
      outwitImages.browserControls.runAutoBrowse(outwitKit.URLHistoryService.getNsIURIFromString(url));
    }
    else {
      widgets.page.loadURI(url);
    }
  },

  dig: function() {
    widgets.page.digFromCurrent(null, true, 2);
  }
 
};


