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

/**
 *
 *
 *
 */

var historyHandler = {
  _pause: false,
  _stack: [],
  _stackAppend: function(callArgs) {
    this._stack.push(callArgs);
  },
  _stackExec: function() {
    if (this._stack.length) {
      var action = this._stack.shift();
      //alert("STACKEXEC\n");
      action.callee.apply(historyHandler, action);
    }
  },
  get pause() { return this._pause; },
  set pause(aVal) {
    this._pause = aVal;
    if (!aVal) this._stackExec();
  },
  lock: false,
  items:[],
  _currentIndex:-1,
  set currentIndex(val){
    this._currentIndex = val;

    if(val==0) document.getElementById('cmd_previous').setAttribute('disabled', 'true');
    else document.getElementById('cmd_previous').setAttribute('disabled', 'false');

    if(val==this.items.length-1) document.getElementById('cmd_forward').setAttribute('disabled', 'true');
    else document.getElementById('cmd_forward').setAttribute('disabled', 'false');
  },

  newGo: function(aSearch, forceEngine, forceSearch, aReferer) {
	//ow.log.error("wwwwww newGo start:"+[aSearch, forceEngine, forceSearch, aReferer]);	  
    try {
    if (this.pause) {
      //alert("STACK NEWGO");
      this._stackAppend(arguments);
      return;
    }

      //alert("RUN NEWGO");
    this.lock = true;
    coreKit.coreMessager.observe('throbber_processing', 1, 1, 'start', false, '');
//    dump("newGo : " + aSearch + "\nref " + aReferer + "\n");
    var extensions = [], url, category;
    var types = optionsCtrl.fileTypes;

    switch (ow.app.kernel.prefs.getString("oWDocs.queryTypesInQuery", "all")) {
      case "selectionPanel":
        for (var i in types) {
          if (document.getElementById("fileFormat_" + i).getAttribute("checked") == "true") {
            extensions = extensions.concat(types[i]);
          }
        }
        break;
      case "all":
      default:
        for (var i in types) {
          extensions = extensions.concat(types[i]);
        }
        break;
    }

    // XXX little hack because with "txt" searches we get too much html...
    var idxTxt = extensions.indexOf('txt');
    if (idxTxt != -1) extensions.splice(idxTxt, 1);

    var classOb = outwitKit.getObjectClass(aSearch);
    if(!forceSearch && classOb == "Filepath" && /\.owc$/.test(aSearch)) {
		//ow.log.error("wwwwww newGo 1:"+aSearch);
      // File loading
      aSearch = aSearch.substr(7, aSearch.length);
      gCatch.loadCatchFromFile( aSearch );
      url = aSearch;
      category = CategoryManager.getCategory(CategoryManager.add(url));
    }
    else if (forceSearch || !(classOb.substr(0, 3) == 'URL' || classOb.substr(0, 8) == 'Filepath')) {
		

      //var currentEngine = outwitDocs.gEngineManager.currentEngine;
      var currentEngine = Services.search.currentEngine;
	  //ow.log.error("wwwwww newGo 2:"+currentEngine.name);
	  //ow.log.error("wwwwwwwww newGo "+Object.keys(currentEngine));
	  ow.log.error("wwwwww newGo "+currentEngine?currentEngine.name:"no current engine");
      var queryData = outwitDocs.gEngineManager.buildQuery(currentEngine, aSearch, extensions);
      url = queryData.url;
      // XXXXXX 07/01/2012 NEW BUG
      try{
      	category = CategoryManager.getCategory(CategoryManager.add(url, extensions, aSearch, currentEngine.name, queryData.conf));
      	//category = CategoryManager.getCategory(CategoryManager.add(url, extensions, aSearch, (currentEngine ? currentEngine.name : null), queryData.conf));
      }catch(e){
      	ow.log.error(e+"\n"+e.stack);
      }
    }
    else {
      // URL
      url = aSearch;
      category = CategoryManager.getCategory(CategoryManager.add(url, extensions));
    }

    this.newGoNext({url: url, category: category}, aReferer, false);
    searchTreeCtrl.select( category.getName() );

    historyHandler.items.push({'key':category.getName(), 'url':url});
    historyHandler.currentIndex++;
    }
    catch(e) {
      ow.log.error("Error loading search"+ e + " line:" + e.lineNumber);
    }
  },


  newGoNext: function(aSearch, aReferer, doBrowse, doDig) {
    if (this.pause) {
      this._stackAppend(arguments);
      return;
    }
    //alert("RUN NEWGONEXT");
    this.lock = true;
    try {
//    dump("newGoNext : " + aSearch.url + "\nref " + aReferer + "\n");
    this.stop();

    //var referer = (typeof(aReferer) != 'undefined' ? aSearch.category.getLastUrl() : aReferer);
    //if (!referer) referer = null;
    this.go(aSearch, aReferer, true, doBrowse, doDig);
    }
    catch(e) {
      dump("NEWGONEXT error " + e + "\n");
    }
  },

  /*
   * @param {String} aSearch a search or URL
   * @param {Boolean} forceEngine Force engin to use for search
   * @param {Boolean} forceSearch Force "search" mode, i.e. if an URL is entered, search for it.
   */
  go: function( aSearch, aReferer, doNext, doBrowse, doDig) {
    if (this.pause) {
      this._stackAppend(arguments);
      return;
    }

    gNotification.hideTopNotificationNoResult();
    gNotification.hideTopNotificationManyNoResult();

    //alert("RUN GO");
    this.lock = true;
    coreKit.coreMessager.observe('throbber_processing', 1, 1, 'start', false, '');
    try {
      var url = outwitKit.URLHistoryService.getNsIURIFromString(aSearch.url, true, "http").spec;
      var category = aSearch.category;

      searchTreeCtrl.synchronize();

      gCategory = category;

      if(!outwitDocs.UIControls.URLBar.locked) {
        var words = category.getWords();
        outwitDocs.UIControls.URLBar.value = (words ? words : category.getUrl());
      }

      category.setLastUrl(url);

//      dump("go : " + aSearch.url + "\nref " + aReferer + "\nrefspec " + (aReferer ? aReferer.spec: '') + " " + doBrowse + " " + doDig + " " + doNext + '\n');
      if (doBrowse) {
        widgets.page.browse(url, null, true, -1);
      }
      else if (doDig) {
        widgets.page.dig(url, null, false, 2, null, null, null);
      }
      else if (doNext) {
        widgets.page.browse(url, null, true, ow.app.kernel.prefs.getInt("oWDocs.nextStep", 3));
      }
      else {
        widgets.page.loadURI(url, (typeof(aReferer) != 'undefined' ? aReferer : null));
        searchTreeCtrl.tree.focus();
      }
    }
    catch(e) {
      dump("GO error " + e + "\n");
    }
  },

  get currentIndex(){
    return this._currentIndex;
  },

  goBack: function(){
    outwitDocs.UIControls.URLBar.locked = false;
    this.currentIndex--;
    this.go(this.items[this.currentIndex].key, false, false);
  },

  goForward: function(){
    outwitDocs.UIControls.URLBar.locked = false;
    this.currentIndex++;
    this.go(this.items[this.currentIndex].key, false, false);
  },

  goToIndex: function( anIndex ){
    outwitDocs.UIControls.URLBar.locked = false;
    this.currentIndex = anIndex;
    this.go(this.items[this.currentIndex].key, false, false);
  },

  onCommand: function( anEvent ){
    var index = anEvent.target.getAttribute('index');
    this.goToIndex(index);
  },

  reload: function() {
    this.stop();
    widgets.page.reload();
  },

  stop: function(){
    searchTreeCtrl.stopThrobber();
    widgets.page.stopAll();
  },

  fillHistoryMenu: function(anElement){
    while(anElement.hasChildNodes()) anElement.removeChild(anElement.lastChild);
    var current = this.currentIndex;
    for( var i = current + 5 ; i >= 0 ; i--){
      if(this.items[i]){
        var el = document.createElement('menuitem');
        el.setAttribute('label', this.items[i].key );
        el.setAttribute('tooltiptext', this.items[i].url );
        el.setAttribute('index', i );
        if( i < current ){
          el.className = "findbar-find-previous menuitem-iconic";

        }
        else if(i > current){
          el.className = "findbar-find-next menuitem-iconic";
        }
        else{
          el.setAttribute('type', 'radio');
          el.className = "unified-nav-current";
          el.setAttribute('checked','true');
        }
        anElement.appendChild(el);
      }
    }
  }
};
