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

/**
 * Control the behavior of the menu.
 */


/**
 * @name menuCtrl
 * @static
 * Base class to wrap image function in a simple method
 */
var menuCtrl = {};


menuCtrl.openPrefPane = function() {
  var features = "chrome,titlebar,toolbar,centerscreen,dialog=no";
  var url = "chrome://outwit-modules-docs/content/preferences/panel.xul";
  prefWindow = window.open(url, "docsPrefWindow", features);
  prefWindow.focus();
};


menuCtrl.view = {};

menuCtrl.view.onPopupShowing = function(anEvent){
  var menu    = document.getElementById('left-panel');
  var optMenu = document.getElementById('optionsMenu');
  var splitter= document.getElementById('left-splitter');
  var optionsPanel = document.getElementById('optionsOverlay');

  if( splitter.getAttribute('state') != 'collapsed')
    menu.setAttribute('checked', 'true');
  else
    menu.setAttribute('checked', 'false');

  if(optionsPanel.getAttribute('collapsed') == 'true' ){
    optMenu.setAttribute('checked','false');
  }
  else{
    optMenu.setAttribute('checked','true');
  }
};



menuCtrl.file = {};


menuCtrl.file.onPopupShowing = function(anEvent){
  var VFSelectedLength    = 0;
  for( var item in gContainer.selection) VFSelectedLength++;
  var VFFolderLength   = gContainer.items.length;
  var saveSelected     = document.getElementById('menuFileSaveSelected');
  var saveSelectedAs   = document.getElementById('menuFileSaveSelectedAs');
  var saveAll          = document.getElementById('menuFileSaveAll');
  var saveAllRename    = document.getElementById('menuFileSaveAllRename');

  if( VFSelectedLength){
    if(saveSelected.hasAttribute('disabled')){
      saveSelected.removeAttribute('disabled');
      saveSelectedAs.removeAttribute('disabled');
    }
  }
  else{
    saveSelected.setAttribute('disabled', 'true');
    saveSelectedAs.setAttribute('disabled', 'true');
  }

  if( VFFolderLength ){
    if(saveAll.hasAttribute('disabled')){
      saveAll.removeAttribute('disabled');
      saveAllRename.removeAttribute('disabled');
    }
  }
  else{
    saveAll.setAttribute('disabled', 'true');
    saveAllRename.setAttribute('disabled', 'true');
  }
};


menuCtrl.file.openFromDisk = function(){
  var fm = coreKit.fileManager.filePicker.get();
  if(fm){
    fm.QueryInterface(Components.interfaces.nsIFile);
    var path = "file://" + fm.path;
    historyHandler.newGo(path);
  }
};

menuCtrl.file._retrieveSelected = function(){
  //Retrieve the selected document
  var selected = [];
  var VFSelected  = gContainer.selection;
  var VFFolder    = gContainer.items;
  var selectedDocument  = null;
  for( item in VFSelected ){
    selectedDocument = VFSelected[item];
    var indexOf = VFFolder.indexOf(selectedDocument);
    if( indexOf != -1 ){
      selectedDocument = VFFolder[indexOf];
      selected.push(selectedDocument);
    }
  }

  return selected;
}

menuCtrl.file.saveSelected = function(aSource){
  var selectedItems = aSource.selectedItems;
  
  for( var i = 0 ; i < selectedItems.length ; i++ ){
    //optionsCtrl.autoSaveSwitch();
		// XXX compat fix, remove third and fourth parameter in next version
    gDownloadManager.download(outwitKit.URLHistoryService.getBeanFromString(selectedItems[i].mediaUrl, true), optionsCtrl.autoSaveFolder, "", function() {});
  }
};

menuCtrl.file.saveSelectedAs = function(aSource){
  var fp = coreKit.fileManager.filePicker;
  var title = coreKit.localeService.getString('saveWindowTitle', 'chrome://outwit-modules-docs/locale/main.properties');
  var saveIn = fp.get(title, null);
  if( saveIn && saveIn != '' ){
    var selectedItems = aSource.selectedItems;
    for( var i = 0 ; i < selectedItems.length ; i++ ) {
		  // XXX compat fix, remove third and fourth parameter in next version
      gDownloadManager.download(outwitKit.URLHistoryService.getBeanFromString(selectedItems[i].mediaUrl, true), saveIn, "", function() {});
		}
  }
};

menuCtrl.file.saveAll = function(aSource, canRename) {
  var fp = coreKit.fileManager.filePicker;
  var saveIn, renamePattern = null, title;
  if (canRename) {
    title = coreKit.localeService.getString('saveRenameWindowTitle', 'chrome://outwit-modules-docs/locale/main.properties');
    saveIn = fp.save(title, coreKit.localeService.getString('defaultRenamePattern', 'chrome://outwit-modules-docs/locale/main.properties'));
    if (saveIn) {
      var renamePattern = saveIn.leafName;
      var saveIn = saveIn.parent;
    }
  }
  else {
    title = coreKit.localeService.getString('saveWindowTitle', 'chrome://outwit-modules-docs/locale/main.properties');
    saveIn = fp.get(title, null);
  }
  
  if (saveIn) {
    var items = aSource.items;
    for( var i = 0 ; i < items.length ; i++ ) {
      gDownloadManager.saveFile(outwitKit.URLHistoryService.getBeanFromString(items[i].mediaUrl, true), saveIn, renamePattern);
    }
  }
};

/**
 * @name menuCtrl.nav
 * Lazyness...
 */
menuCtrl.nav = {};

menuCtrl.nav.browse = function(event) {
  menuCtrl.nav.stop(true);
  
  var nodesToRun = "all";
  var eventNodesToRun = event.target.getAttribute("actiontype");
  
  if( (typeof(eventNodesToRun) != "undefined") && (eventNodesToRun != "") ){
    nodesToRun = (eventNodesToRun=="all")?"all":parseInt(eventNodesToRun) ;
  }
  
  //  alert( "nodesToRun:"+nodesToRun);
    
  if (nodesToRun =="all"){
    // just go unlimited browsing here
  }else{
    //go browse here where number of pagesis : parseInt(nodesToRun)
  }
  
  
  if (!searchTreeCtrl.isCurrent(gCategory.getName())) {
    var newCategory = CategoryManager.getCategory(searchTreeCtrl.current[searchTreeCtrl.current.length - 1]);
    var url = newCategory.getNextUrl();
    if (!url) url = newCategory.getLastUrl();
    historyHandler.newGoNext({category: newCategory, url: url}, outwitKit/URLHistoryService.getNsIRUIFromString(newCategory.getLastUrl(), true), true);
  }
  else {
    historyHandler.newGoNext({'category':gCategory, 'url':widgets.page.browser.nextUrl}, widgets.page.browser.currentURI, true);
  }
};

menuCtrl.nav.next = function(wasUserAction) {
  menuCtrl.nav.stop(true);
  if (!searchTreeCtrl.isCurrent(gCategory.getName())) {
    var newCategory = CategoryManager.getCategory(searchTreeCtrl.current[searchTreeCtrl.current.length - 1]);
    var url = newCategory.getNextUrl();
    if (!url) url = newCategory.getLastUrl();
    historyHandler.newGoNext({category: newCategory, url: url}, outwitKit/URLHistoryService.getNsIRUIFromString(newCategory.getLastUrl(), true), false);
  }
  else {
    historyHandler.newGoNext({'category':gCategory, 'url':widgets.page.browser.nextUrl}, widgets.page.browser.currentURI, false);
  }
};


menuCtrl.nav.reload = function(){
  historyHandler.reload();
};


menuCtrl.nav.stop = function(){
  historyHandler.stop(true);
};


menuCtrl.nav.up = function() {
  var newCategory = CategoryManager.getCategory(searchTreeCtrl.current[searchTreeCtrl.current.length - 1]);
  var url = newCategory.getNextUrl();
  if (!url) url = newCategory.getLastUrl();

  var bean = outwitKit.URLHistoryService.getBeanFromString(url, true);
  if (bean.upPageURI) {
    widgets.page.loadURI(bean.upPageURI, url);
  }
  else {
    try {
      coreKit.urlHelper.getUpURL(bean.URI, function(resultBean) {
        if (resultBean) {
          var bean = outwitKit.URLHistoryService.getBeanFromString(url, true);
          outwitKit.URLHistoryService.setBeanData(bean, "upPageURI", resultBean.URI);
          historyHandler.newGo(resultBean.URI.spec, null, null, url);
        }
      });
    }
    catch(e) {
      ow.log.error("Error getting up page", e);
    }
  }
};

menuCtrl.nav.dig = function(event) {
  menuCtrl.nav.stop(true);
  
  var digLimitation="none";
  var depth = 1;
  
  var eventDepth = event.target.getAttribute("digdepth");
  var eventdigLimitation= event.target.getAttribute("digdomain");
  
  if( (typeof(eventDepth) != "undefined") && (eventDepth != "") ){
    depth = parseInt(eventDepth) ;
  }
  
  if( (typeof(eventdigLimitation) != "undefined")&& (eventdigLimitation != "") ){
    digLimitation = String(eventdigLimitation);
  }
  
  //here you have to dig using "digLimitation" and "depth"
    
  //alert("digLimitation:"+digLimitation+" depth:"+depth);
  
  if (!searchTreeCtrl.isCurrent(gCategory.getName())) {
    var newCategory = CategoryManager.getCategory(searchTreeCtrl.current[searchTreeCtrl.current.length - 1]);
    var url = newCategory.getLastUrl();
    historyHandler.newGoNext({category: newCategory, url: url}, outwitKit/URLHistoryService.getNsIRUIFromString(newCategory.getLastUrl(), true), false, true);
  }
  else {
    historyHandler.newGoNext({'category':gCategory, 'url':widgets.page.browser.nextUrl}, widgets.page.browser.currentURI, false, true);
  }
};

menuCtrl.catch = {};

menuCtrl.catch.load = function(){
  var element = gCatch.loadFromSqliteFile();
  if(element){
    var allCategory = CategoryManager.getAll();
    var cat = CategoryManager.getCategory('catch');

    for( let i = 0 ; i < element.length ; i++ ){
  
      var items = cat.getAll();
      for( let i in items){
        for( let j = 0 ; j < allCategory.length ; j++ ){
          if(allCategory[j].getName() != 'catch')
            allCategory[j].mark(i);
        }
      }

      if( searchTreeCtrl.isCurrent('catch') )
          gContainer.appendItem(element[i], true);
    }
  }
};

menuCtrl.catch.save = function(){
  if (gCatch.childNodes.length > 0) gCatch.db.saveTo(gCatch.childNodes);
};

menuCtrl.catch.clear = function(){
  if( gCatch.childNodes.length == 0 ) return;

  gCatch.clear()

  var allCategory = CategoryManager.getAll();

  var cat = CategoryManager.getCategory('catch');
  var items = cat.getAll();
  for( let i in items){
    for( let j = 0 ; j < allCategory.length ; j++ ){
      allCategory[j].unmark(i);
    }
  }
  
  cat.clear();
  if( searchTreeCtrl.isCurrent('catch') ) {
    gContainer.clear();
  }
  else{
    var items = gContainer.selection;
    for( var item in items )
      items[item].inCatch = false;
      items[item].isInCatch = false;
  }
};


menuCtrl.browser = {};

menuCtrl.browser.extWin = null;
menuCtrl.browser.extChromeWin = null;

menuCtrl.browser.open = function(uri){
/*
  var windowsMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                                  .getService(Components.interfaces.nsIWindowMediator);
  var theWin = windowsMediator.getMostRecentWindow("navigator:browser");
  if (menuCtrl.browser.extWin == null || menuCtrl.browser.extWin.closed) {
    menuCtrl.browser.extWin = window.open(anURL);
    menuCtrl.browser.extChromeWin = windowsMediator.getMostRecentWindow("navigator:browser");
  }
  else {
    var brow = theWin.getBrowser();
    brow.selectedTab = brow.addTab(anURL);
    theWin.focus();
  }
*/
  /*
      if(typeof uri == 'string')
    {
        var ioservice = Components.classes["@mozilla.org/network/io-service;1"]
            .getService(Components.interfaces.nsIIOService);
        uri = ioservice.newURI(uri, null, null);
    }

    // Open URL in user's default browser.
    var extps = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]
        .getService(Components.interfaces.nsIExternalProtocolService);
    extps.loadURI(uri, null);
    */

  window.openDialog("chrome://outwit-kernel/content/widgets/page/pageWindow.xul", "outwitBrowser", "chrome,dialog=no,modal=no", { url: uri });
};
